repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/study_savvy_app/lib/blocs
mirrored_repositories/study_savvy_app/lib/blocs/files/bloc_specific_file.dart
import 'dart:typed_data'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:study_savvy_app/models/files/model_files.dart'; import 'package:study_savvy_app/services/files/api_files.dart'; import 'package:study_savvy_app/utils/exception.dart'; abstract class FileEvent {} class FileEventOCR extends FileEvent{ final String id; FileEventOCR(this.id); } class FileEventASR extends FileEvent{ final String id; FileEventASR(this.id); } class FileEventDelete extends FileEvent{ final String id; FileEventDelete(this.id); } class FileEventEditOCR extends FileEvent{ final EditFile file; FileEventEditOCR(this.file); } class FileEventEditASR extends FileEvent{ final EditFile file; FileEventEditASR(this.file); } class FileEventClear extends FileEvent{} class FileEventUnknown extends FileEvent{} class FileState { final String status; final String? message; final SpecificFile? file; final Uint8List? media; final String? type; final String? id; FileState(this.status,this.message,this.file,this.media,this.type,this.id); @override String toString(){ return "FileState $status $message $file $media $type $id"; } } class FileBloc extends Bloc<FileEvent,FileState> { final FilesService apiService; FileBloc({FilesService? apiService}):apiService=apiService??FilesService(), super(FileState("INIT",null, null, null,null,null)){ on<FileEvent>((event,emit) async { apiService ??= FilesService(); if (event is FileEventOCR){ try{ SpecificFile file=await apiService!.getSpecificFile(event.id); Uint8List? media=await apiService!.getImage(event.id); emit(FileState("SUCCESS",null,file, media,"OCR",event.id)); } on AuthException { emit(FileState("FAILURE","AUTH", null, null,null,null)); } on ServerException { emit(FileState("FAILURE","SERVER", null, null,null,null)); } on ClientException { emit(FileState("FAILURE","CLIENT", null, null,null,null)); } on ExistException { emit(FileState("FAILURE","EXIST", null, null,null,null)); } catch(e) { emit(FileState("FAILURE","UNKNOWN", null, null,null,null)); } } else if (event is FileEventASR){ try{ SpecificFile file=await apiService!.getSpecificFile(event.id); Uint8List media=await apiService!.getAudio(event.id); emit(FileState("SUCCESS",null,file, media,"ASR",event.id)); } on AuthException { emit(FileState("FAILURE","AUTH", null, null,null,null)); } on ServerException { emit(FileState("FAILURE","SERVER", null, null,null,null)); } on ClientException { emit(FileState("FAILURE","CLIENT", null, null,null,null)); } on ExistException { emit(FileState("FAILURE","EXIST", null, null,null,null)); } catch(e) { emit(FileState("FAILURE","UNKNOWN", null, null,null,null)); } } else if (event is FileEventClear){ emit(FileState("INIT",null,null,null,null,null)); } else if(event is FileEventDelete){ emit(FileState("PENDING",null,null,null,null,null)); try{ await apiService!.deleteSpecificFile(event.id); emit(FileState("SUCCESS_OTHER","Success to delete",null,null,null,null)); } on AuthException { emit(FileState("FAILURE","AUTH", null, null,null,null)); } on ServerException { emit(FileState("FAILURE","SERVER", null, null,null,null)); } on ClientException { emit(FileState("FAILURE","CLIENT", null, null,null,null)); } on ExistException { emit(FileState("FAILURE","EXIST", null, null,null,null)); } catch(e) { emit(FileState("FAILURE","UNKNOWN", null, null,null,null)); } } else if(event is FileEventEditOCR){ emit(FileState("PENDING",null,null,null,null,null)); try{ await apiService!.editSpecificFileOCR(event.file); emit(FileState("SUCCESS_OTHER","Success to upload",null,null,null,null)); } on AuthException { emit(FileState("FAILURE","AUTH", null, null,null,null)); } on ServerException { emit(FileState("FAILURE","SERVER", null, null,null,null)); } on ClientException { emit(FileState("FAILURE","CLIENT", null, null,null,null)); } on ExistException { emit(FileState("FAILURE","EXIST", null, null,null,null)); } catch(e) { emit(FileState("FAILURE","UNKNOWN", null, null,null,null)); } } else if(event is FileEventEditASR){ emit(FileState("PENDING",null,null,null,null,null)); try{ await apiService!.editSpecificFileASR(event.file); emit(FileState("SUCCESS_OTHER","Success to upload",null,null,null,null)); } on AuthException { emit(FileState("FAILURE","AUTH", null, null,null,null)); } on ServerException { emit(FileState("FAILURE","SERVER", null, null,null,null)); } on ClientException { emit(FileState("FAILURE","CLIENT", null, null,null,null)); } on ExistException { emit(FileState("FAILURE","EXIST", null, null,null,null)); } catch(e) { emit(FileState("FAILURE","UNKNOWN", null, null,null,null)); } } else { throw Exception("Error event in specific_file"); } }); } }
0
mirrored_repositories/study_savvy_app/lib/blocs
mirrored_repositories/study_savvy_app/lib/blocs/utils/app_navigator.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:study_savvy_app/blocs/auth/auth_cubit.dart'; import 'package:study_savvy_app/blocs/auth/auth_navigator.dart'; import 'package:study_savvy_app/screens/sign_in/loading_view.dart'; import 'package:study_savvy_app/blocs/session/session_cubit.dart'; import 'package:study_savvy_app/blocs/session/session_state.dart'; import 'package:study_savvy_app/screens/home.dart'; class AppNavigator extends StatelessWidget { @override Widget build(BuildContext context) { return BlocBuilder<SessionCubit, SessionState>(builder: (context, state) { return Navigator( pages: [ // Show loading screen if (state is UnknownSessionState) MaterialPage(child: LoadingView()), // Show auth flow if (state is Unauthenticated) MaterialPage( child: BlocProvider( create: (context) => AuthCubit(sessionCubit: context.read<SessionCubit>()), child: AuthNavigator(), //記得加initial page ), ), // Show session flow if (state is Authenticated) MaterialPage(child: MenuHome()) ], onPopPage: (route, result) => route.didPop(result), ); }); } }
0
mirrored_repositories/study_savvy_app/lib/blocs
mirrored_repositories/study_savvy_app/lib/blocs/utils/bloc_jwt.dart
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:study_savvy_app/services/utils/jwt_storage.dart'; abstract class JWTEvent {} class JWTEventGet extends JWTEvent{} class JWTEventDelete extends JWTEvent{} class JWTEventUnknown extends JWTEvent{} class JWTBloc extends Bloc<JWTEvent,String?> { final JwtService jwtService; JWTBloc({JwtService? jwtService}):jwtService=jwtService??JwtService(),super(null){ jwtService ??= JwtService(); on<JWTEvent>((event,emit) async { if (event is JWTEventGet){ String? jwt = await jwtService!.getJwt(); emit(jwt); } else if (event is JWTEventDelete){ await jwtService!.deleteJwt(); emit(null); } else{ throw Exception("Error event in jwt"); } }); } }
0
mirrored_repositories/study_savvy_app/lib/blocs
mirrored_repositories/study_savvy_app/lib/blocs/utils/bloc_navigator.dart
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:study_savvy_app/screens/article_improver/article_improver.dart'; import 'package:study_savvy_app/screens/files/files.dart'; import 'package:study_savvy_app/screens/profile/profile.dart'; import 'package:study_savvy_app/screens/note_taker/note_taker.dart'; enum PageState { audio,articleImprover,files,profile } final pageWidgets = { PageState.audio: const NoteTakerPage(), PageState.articleImprover: const ArticleImproverPage(), PageState.files:const FilesPage(), PageState.profile:const ProfilePage(), }; final pageIndex = { PageState.audio: 0, PageState.articleImprover: 1, PageState.files:2, PageState.profile:3, }; final pageEvents=[PageEventAudio(),PageEventArticleImprover(),PageEventFiles(),PageEventProfile()]; abstract class PageEvent {} class PageEventAudio extends PageEvent {} class PageEventArticleImprover extends PageEvent {} class PageEventFiles extends PageEvent {} class PageEventProfile extends PageEvent {} class PageEventUnknown extends PageEvent {} class PageBloc extends Bloc<PageEvent,PageState> { PageBloc() : super(PageState.audio){ on<PageEvent>((event, emit) { if (event is PageEventArticleImprover){ emit(PageState.articleImprover); } else if(event is PageEventFiles){ emit(PageState.files); }else if(event is PageEventProfile){ emit(PageState.profile); }else if(event is PageEventAudio){ emit(PageState.audio); }else{ throw Exception("Error event in navigator"); } }); } }
0
mirrored_repositories/study_savvy_app/lib
mirrored_repositories/study_savvy_app/lib/models/model_login.dart
class LoginModel{ final String email; final String password; LoginModel(this.email, this.password); Map<String,String> formatJson(){ return { "mail": email, "password": password, }; } }
0
mirrored_repositories/study_savvy_app/lib
mirrored_repositories/study_savvy_app/lib/models/model_noteTaker.dart
import 'dart:io'; class noteTaker_audio{ final File audio; final String prompt; noteTaker_audio(this.audio, this.prompt); }
0
mirrored_repositories/study_savvy_app/lib
mirrored_repositories/study_savvy_app/lib/models/model_signup.dart
class SignUpModel{ final String gender; final String mail; final String name; final String password; SignUpModel(this.gender, this.mail, this.name, this.password); Map<String,String> formatJson(){ return { "gender":gender, "mail":mail, "name":name, "password":password, }; } }
0
mirrored_repositories/study_savvy_app/lib/models
mirrored_repositories/study_savvy_app/lib/models/profile/model_profile.dart
class Profile{ final String name; final String mail; final String gender; Profile(this.name,this.mail,this.gender); Profile.fromJson(Map<String, dynamic> json) : name=json['name'], mail=json['mail'], gender=json['gender']; @override String toString(){ return "Profile $name $mail $gender"; } } class UpdateProfile{ final String name; final String gender; UpdateProfile(this.name,this.gender); Map<String,String> formatJson(){ return { "name": name, "gender": gender }; } } class UpdatePwd{ final String currentPassword; final String EditPassword; UpdatePwd(this.currentPassword,this.EditPassword); Map<String,String> formatJson(){ return { "current_password": currentPassword, "edit_password": EditPassword }; } } class AIMethods{ final String token; AIMethods(this.token); } class SecureData{ final String data; final String key; SecureData(this.data,this.key); Map<String,String> formatAccessToken(){ return {"aes_key":key,"access_token":data}; } Map<String,String> formatApiKey(){ return {"aes_key":key,"api_key":data}; } }
0
mirrored_repositories/study_savvy_app/lib/models
mirrored_repositories/study_savvy_app/lib/models/article_improver/model_article_improver.dart
import 'dart:io'; class ArticleImage { final File image; final String prompt; ArticleImage(this.image, this.prompt); } class ArticleText { final String content; final String prompt; ArticleText(this.content, this.prompt); Map<String,String> formatJson(){ return { "content":content, "prompt":prompt }; } }
0
mirrored_repositories/study_savvy_app/lib/models
mirrored_repositories/study_savvy_app/lib/models/files/model_files.dart
class File { final String id; final String time; final String status; final String type; File(this.id,this.type,this.status,this.time); @override String toString(){ return "File $id $time $status $type"; } } class Files{ final List<dynamic> files; final int currentPage; final int totalPages; Files(this.files,this.currentPage,this.totalPages); Files.fromJson(Map<String, dynamic> json) : files=(json['data']).map((item){ return File(item['file_id'],item["file_type"],item["status"],item["file_time"]); }).toList(), currentPage=json['current_page'], totalPages=json['total_pages']; @override String toString(){ return "File $currentPage $totalPages $files"; } } class SpecificFile{ final String content; final String prompt; final String summarize; final List<dynamic> details; SpecificFile(this.content,this.prompt,this.summarize,this.details); SpecificFile.fromJson(Map<String, dynamic> json) : content = json['content'] as String, prompt =json['prompt'] as String, summarize =json['summarize'] as String, details =json['details']; @override String toString(){ return "SpecificFile $content $prompt $summarize $details"; } } class EditFile{ final String id; final String prompt; final String content; EditFile(this.id,this.prompt,this.content); Map<String,String> formatJson(){ return {"prompt":prompt,"content":content}; } }
0
mirrored_repositories/study_savvy_app/lib
mirrored_repositories/study_savvy_app/lib/styles/custom_style.dart
import 'package:flutter/material.dart'; class LightStyle { static const MaterialColor primarySwatch = Colors.grey; static const Color primaryLight = Color(0xFFFBFCFF); static const Color borderColor = Colors.black12; static BoxDecoration boxDecoration= BoxDecoration( border: Border.all( color: const Color(0xFF3D3D3D), width: 1, ), ); static const Color fileBoxColor= Color.fromRGBO(236, 236, 236, 0.80); static const Color textColor = Color.fromRGBO(235, 235, 245, 0.60); static final ThemeData theme = ThemeData( primarySwatch: primarySwatch, primaryColor: primaryLight, brightness: Brightness.light, textTheme: const TextTheme( bodyLarge: TextStyle(color: Colors.black, fontSize:36,fontFamily: 'Play',fontWeight: FontWeight.bold), bodyMedium: TextStyle(color: Colors.black38, fontSize:24,fontFamily: 'Play',fontWeight: FontWeight.bold), bodySmall: TextStyle(color: Colors.black, fontSize:17,fontFamily: 'Play',fontWeight: FontWeight.bold), displayMedium: TextStyle(color: Colors.black, fontSize:24,fontFamily: 'Play',fontWeight: FontWeight.bold), displaySmall: TextStyle(color: Colors.black, fontSize:17,fontFamily: 'Play',fontWeight: FontWeight.bold), labelLarge: TextStyle(color: Colors.white), labelMedium: TextStyle(color: Colors.black, fontSize:20,fontFamily: 'Play',fontWeight: FontWeight.bold), labelSmall: TextStyle(color: Colors.white, fontSize:15,fontFamily: 'Play',fontWeight: FontWeight.bold), titleSmall: TextStyle(color: Colors.black, fontSize:15,fontFamily: 'Play',fontWeight: FontWeight.bold), titleMedium: TextStyle(color: Color.fromRGBO(60, 60, 67, 0.6), fontSize:17, fontFamily: 'Play', fontWeight: FontWeight.bold), titleLarge: TextStyle(color: Color.fromRGBO(229, 229, 239, 1), fontSize:17, fontFamily: 'Play', fontWeight: FontWeight.bold), headlineLarge: TextStyle(color: Colors.black, fontSize:30,fontFamily: 'Play',fontWeight: FontWeight.bold), headlineMedium: TextStyle(color: Colors.black, fontSize:17,fontFamily: 'Play',fontWeight: FontWeight.bold), headlineSmall: TextStyle(color: Colors.black, fontSize:13,fontFamily: 'Play',fontWeight: FontWeight.bold), ), elevatedButtonTheme: ElevatedButtonThemeData( style: ButtonStyle( backgroundColor: MaterialStateProperty.all(Colors.black), elevation: MaterialStateProperty.all(5), ), ), ); } class DarkStyle { static const MaterialColor primarySwatch = Colors.grey; static const Color primaryDark = Color(0xFF202124); static const Color borderColor = Colors.white30; static const BoxDecoration boxDecoration= BoxDecoration(color: Color.fromRGBO(118, 118, 128, 0.24)); static const Color fileBoxColor= Colors.black; static const Color textColor = Color.fromRGBO(60, 60, 67, 0.60); static final ThemeData theme = ThemeData( primarySwatch: primarySwatch, primaryColor: primaryDark, brightness: Brightness.dark, textTheme: const TextTheme( bodyLarge: TextStyle(color: Colors.white, fontSize:36,fontFamily: 'Play',fontWeight: FontWeight.bold), bodyMedium: TextStyle(color: Colors.white, fontSize:24,fontFamily: 'Play',fontWeight: FontWeight.bold), bodySmall: TextStyle(color: Colors.white, fontSize:17,fontFamily: 'Play',fontWeight: FontWeight.bold), displayMedium: TextStyle(color: Colors.white, fontSize:24,fontFamily: 'Play',fontWeight: FontWeight.bold), displaySmall: TextStyle(color: Colors.white, fontSize:17,fontFamily: 'Play',fontWeight: FontWeight.bold), labelLarge: TextStyle(color: Color.fromRGBO(99, 99, 102, 1)), labelMedium: TextStyle(color: Colors.white, fontSize:20,fontFamily: 'Play',fontWeight: FontWeight.bold), labelSmall: TextStyle(color: Colors.black, fontSize:15,fontFamily: 'Play',fontWeight: FontWeight.bold), titleSmall: TextStyle(color: Colors.white, fontSize:15,fontFamily: 'Play',fontWeight: FontWeight.bold), titleMedium: TextStyle(color: Color.fromRGBO(235, 235, 245, 0.6), fontSize:17, fontFamily: 'Play', fontWeight: FontWeight.bold), titleLarge: TextStyle(color: Color.fromRGBO(57, 57, 59, 0.8), fontSize:17, fontFamily: 'Play', fontWeight: FontWeight.bold), headlineLarge: TextStyle(color: Colors.white70, fontSize:30,fontFamily: 'Play',fontWeight: FontWeight.bold), headlineMedium: TextStyle(color: Colors.white70, fontSize:17,fontFamily: 'Play',fontWeight: FontWeight.bold), headlineSmall: TextStyle(color: Colors.white70, fontSize:15,fontFamily: 'Play',fontWeight: FontWeight.bold), ), elevatedButtonTheme: ElevatedButtonThemeData( style: ButtonStyle( backgroundColor: MaterialStateProperty.all(const Color.fromRGBO(51, 71, 250, 0.78)), elevation: MaterialStateProperty.all(5), ), ), ); }
0
mirrored_repositories/study_savvy_app/lib
mirrored_repositories/study_savvy_app/lib/utils/routes.dart
import 'package:flutter/material.dart'; import 'package:study_savvy_app/screens/profile/access_token.dart'; import 'package:study_savvy_app/screens/profile/api_key.dart'; import 'package:study_savvy_app/screens/article_improver/camera.dart'; import 'package:study_savvy_app/screens/home.dart'; import 'package:study_savvy_app/screens/profile/information_setting.dart'; import 'package:study_savvy_app/screens/profile/password_setting.dart'; import 'package:study_savvy_app/screens/files/specific_file.dart'; class Routes { static const home='/home'; static const information='/information'; static const password='/password'; static const apikey='/api_key'; static const accessToken='/access_token'; static const specificFile='/specific_file'; static const camera='/camera'; } class RouteGenerator { static Route<dynamic>? generateRoute(RouteSettings settings) { switch (settings.name) { case Routes.home: return MaterialPageRoute(builder: (_) => const MenuHome()); case Routes.information: return MaterialPageRoute(builder: (_) => const InformationPage()); case Routes.password: return MaterialPageRoute(builder: (_) => const PasswordPage()); case Routes.apikey: return MaterialPageRoute(builder: (_) => const ApiKeyPage()); case Routes.accessToken: return MaterialPageRoute(builder: (_) => const AccessTokenPage()); case Routes.specificFile: return MaterialPageRoute(builder: (_) => const SpecificFilePage()); case Routes.camera: return MaterialPageRoute(builder: (_) => const CameraPage()); default: return null; } } }
0
mirrored_repositories/study_savvy_app/lib
mirrored_repositories/study_savvy_app/lib/utils/exception.dart
class AuthException implements Exception { final String message; AuthException(this.message); } class ServerException implements Exception { final String message; ServerException(this.message); } class ClientException implements Exception { final String message; ClientException(this.message); } class ExistException implements Exception { final String message; ExistException(this.message); } class PasswordException implements Exception{ final String message; PasswordException(this.message); }
0
mirrored_repositories/study_savvy_app/lib
mirrored_repositories/study_savvy_app/lib/services/signUp_api.dart
import 'dart:convert'; import 'dart:io'; import 'package:study_savvy_app/utils/exception.dart'; import 'package:study_savvy_app/models/model_signup.dart'; import './api_routes.dart'; import './utils/jwt_storage.dart'; import 'package:http/http.dart' as http; import 'package:http_parser/http_parser.dart'; class SignUpService { JwtService jwtService; http.Client httpClient; SignUpService({JwtService? jwtService, http.Client? httpClient,}): jwtService = jwtService ?? JwtService(), httpClient = httpClient ?? http.Client(); Future<void> sendEmailConfirmation(SignUpModel data) async { print(jsonEncode(data.formatJson())); final response = await httpClient.post( Uri.parse(ApiRoutes.emailSendUrl), headers: { 'Content-Type': 'application/json', }, body: jsonEncode({'mail':data.mail}), ); if (response.statusCode == 200) { return ; } else if(response.statusCode == 400){ throw ClientException("Invalid status value. RequestBody is not match request."); } else{ throw Exception('Failed in unknown reason'); } } Future<bool> verifyEmail(SignUpModel data, String verificationCode) async { final response = await httpClient.get( Uri.parse('${ApiRoutes.emailCheckUrl}/${data.mail}/$verificationCode'), headers: { 'Content-Type': 'application/json', }, ); print(response.statusCode); if (response.statusCode == 200) { //驗證成功 await signup(data); return true; } else if(response.statusCode == 400){ throw ClientException("Invalid status value. RequestBody is not match request."); } else{ throw Exception('Failed in unknown reason'); } } Future<void> signup(SignUpModel data) async { final response = await httpClient.post( Uri.parse(ApiRoutes.signUpUrl), headers: { 'Content-Type': 'application/json', 'Accept':'application/json', }, body: jsonEncode(data.formatJson()), ); print(jsonEncode(data.formatJson())); print(response.body); if (response.statusCode == 200) { return ; }else if(response.statusCode == 400){ throw ClientException("Invalid status value. RequestBody is not match request."); }else if(response.statusCode == 401){ throw ClientException("Unauthorized with information. User have been signup for the service."); } else{ throw Exception('Failed in unknown reason'); } } }
0
mirrored_repositories/study_savvy_app/lib
mirrored_repositories/study_savvy_app/lib/services/api_routes.dart
class ApiRoutes{ static const String apiBaseUrl="https://study-savvy.com/api/"; static const String fileImageUrl="${apiBaseUrl}Files/resources/graph"; static const String fileAudioUrl="${apiBaseUrl}Files/resources/audio"; static const String fileUrl="${apiBaseUrl}Files"; static const String logoutUrl="${apiBaseUrl}User/logout"; static const String profileUrl="${apiBaseUrl}Information"; static const String passwordEditUrl="${apiBaseUrl}Information/password_edit"; static const String apiKeyUrl="${apiBaseUrl}Access_method/api_key"; static const String accessTokenUrl="${apiBaseUrl}Access_method/access_token"; static const String articleImproverUrl="${apiBaseUrl}Predict/OCR"; static const String articleImproverTextUrl="${apiBaseUrl}Predict/OCR_Text"; static const String fileNlpEditOCRUrl="${apiBaseUrl}NLP_edit/OCR"; static const String fileNlpEditASRUrl="${apiBaseUrl}NLP_edit/ASR"; static const String logInUrl="${apiBaseUrl}User/login/app"; static const String signUpUrl="${apiBaseUrl}User/signup"; static const String emailSendUrl="${apiBaseUrl}Mail/verification"; static const String emailCheckUrl="${apiBaseUrl}Mail/verification"; static const String noteTakerUrl="${apiBaseUrl}Predict/ASR"; }
0
mirrored_repositories/study_savvy_app/lib
mirrored_repositories/study_savvy_app/lib/services/login_api.dart
import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:study_savvy_app/models/model_login.dart'; import 'package:http/http.dart' as http; import 'package:study_savvy_app/utils/exception.dart'; import './api_routes.dart'; import './utils/jwt_storage.dart'; class LoginService { JwtService jwtService; http.Client httpClient; LoginService({JwtService? jwtService, http.Client? httpClient,}): jwtService = jwtService ?? JwtService(), httpClient = httpClient ?? http.Client(); Future<void> login(LoginModel data) async { final response = await httpClient.post( Uri.parse(ApiRoutes.logInUrl), headers: { 'Content-Type': 'application/json', 'Accept':'application/json', }, body: jsonEncode(data.formatJson()), ); if (response.statusCode == 200) { final responseBody = jsonDecode(response.body); if (responseBody.containsKey('token')) { String token = responseBody['token']; debugPrint(responseBody['token']); debugPrint("/n Login successfully! /n"); await jwtService.saveJwt(token); } else { throw AuthException("Token not found in response"); } return ; } else if(response.statusCode == 400){ throw ClientException("Invalid status value. RequestBody is not match request."); } else if (response.statusCode == 401){ await jwtService.deleteJwt(); throw AuthException("Unauthorized with information. User have not registered or with incorrect password."); } else{ throw Exception('Failed in unknown reason'); } } }
0
mirrored_repositories/study_savvy_app/lib
mirrored_repositories/study_savvy_app/lib/services/note_taker.dart
import 'dart:convert'; import 'dart:io'; import 'package:study_savvy_app/utils/exception.dart'; import 'package:study_savvy_app/models/model_noteTaker.dart'; import './api_routes.dart'; import './utils/jwt_storage.dart'; import 'package:http/http.dart' as http; import 'package:http_parser/http_parser.dart'; class noteTaker_Service { JwtService jwtService; http.Client httpClient; noteTaker_Service({JwtService? jwtService, http.Client? httpClient,}): jwtService = jwtService ?? JwtService(), httpClient = httpClient ?? http.Client(); Future<void> predictASR(noteTaker_audio data) async { String? jwt=await jwtService.getJwt(); if(jwt==null){ throw AuthException("JWT invalid"); } File audioData=data.audio; String text=data.prompt; final response = await httpClient.send(http.MultipartRequest( 'POST', Uri.parse(ApiRoutes.noteTakerUrl), ) ..fields['prompt']=text ..files.add(await http.MultipartFile.fromPath( 'file', audioData.path, contentType: MediaType('audio', 'mpeg'), )) ..headers.addAll( { 'Authorization': 'Bearer $jwt' }, )); if (response.statusCode == 200) { return ; } else if(response.statusCode == 400){ throw ClientException("Fail to update ASR file.(Client's error)"); } else if(response.statusCode == 404){ throw ExistException("Source not exist"); } else if (response.statusCode == 422){ await jwtService.deleteJwt(); throw AuthException("JWT invalid"); } else if(response.statusCode == 500){ throw ServerException("Server's error"); } else{ throw Exception('Failed in unknown reason'); } } }
0
mirrored_repositories/study_savvy_app/lib/services
mirrored_repositories/study_savvy_app/lib/services/profile/api_profile.dart
import 'dart:convert'; import 'package:study_savvy_app/models/profile/model_profile.dart'; import 'package:http/http.dart' as http; import 'package:study_savvy_app/services/utils/encrypt.dart'; import 'package:study_savvy_app/utils/exception.dart'; import '../api_routes.dart'; import '../utils/jwt_storage.dart'; class ProfileService { JwtService jwtService; http.Client httpClient; ProfileService({JwtService? jwtService, http.Client? httpClient,}): jwtService = jwtService ?? JwtService(), httpClient = httpClient ?? http.Client(); Future<Profile> getProfile() async { String? jwt=await jwtService.getJwt(); if(jwt==null){ throw AuthException("JWT invalid"); } final response = await httpClient.get( Uri.parse(ApiRoutes.profileUrl), headers: {'Authorization': 'Bearer $jwt'}, ); if (response.statusCode == 200) { Map<String,dynamic> result=jsonDecode(response.body); return Profile.fromJson(result); } else if(response.statusCode == 400){ throw ClientException("Client's error"); } else if(response.statusCode == 404){ throw ExistException("Source not exist"); } else if (response.statusCode == 422){ await jwtService.deleteJwt(); throw AuthException("JWT invalid"); } else if(response.statusCode == 500){ throw ServerException("Server's error"); } else{ throw Exception('Failed in unknown reason'); } } Future<void> setProfile(UpdateProfile data) async { String? jwt=await jwtService.getJwt(); if(jwt==null){ throw AuthException("JWT invalid"); } final response = await httpClient.put( Uri.parse(ApiRoutes.profileUrl), headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer $jwt' }, body: jsonEncode(data.formatJson()), ); if (response.statusCode == 200) { return ; } else if(response.statusCode == 400){ throw ClientException("Client's error"); } else if(response.statusCode == 404){ throw ExistException("Source not exist"); } else if (response.statusCode == 422){ await jwtService.deleteJwt(); throw AuthException("JWT invalid"); } else if(response.statusCode == 500){ throw ServerException("Server's error"); } else{ throw Exception('Failed in unknown reason'); } } Future<void> setApiKey(String apikey) async { String? jwt=await jwtService.getJwt(); if(jwt==null){ throw AuthException("JWT invalid"); } SecureData data=await encrypt(apikey); final response = await httpClient.put( Uri.parse(ApiRoutes.apiKeyUrl), headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer $jwt' }, body: jsonEncode(data.formatApiKey()), ); if (response.statusCode == 200) { return ; } else if(response.statusCode == 400){ throw ClientException("Client's error"); } else if(response.statusCode == 404){ throw ExistException("Source not exist"); } else if (response.statusCode == 422){ await jwtService.deleteJwt(); throw AuthException("JWT invalid"); } else if(response.statusCode == 500){ throw ServerException("Server's error"); } else{ throw Exception('Failed in unknown reason'); } } Future<void> setAccessToken(String accessToken) async { String? jwt=await jwtService.getJwt(); if(jwt==null){ throw AuthException("JWT invalid"); } SecureData data=await encrypt(accessToken); final response = await httpClient.put( Uri.parse(ApiRoutes.accessTokenUrl), headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer $jwt' }, body: jsonEncode(data.formatAccessToken()), ); if (response.statusCode == 200) { return ; } else if(response.statusCode == 400){ throw ClientException("Client's error"); } else if(response.statusCode == 404){ throw ExistException("Source not exist"); } else if (response.statusCode == 422){ await jwtService.deleteJwt(); throw AuthException("JWT invalid"); } else if(response.statusCode == 500){ throw ServerException("Server's error"); } else{ throw Exception('Failed in unknown reason'); } } Future<void> resetPassword(UpdatePwd data) async { String? jwt=await jwtService.getJwt(); if(jwt==null){ throw AuthException("JWT invalid"); } final response = await httpClient.put( Uri.parse(ApiRoutes.passwordEditUrl), headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer $jwt' }, body: jsonEncode(data.formatJson()), ); if (response.statusCode == 200) { return ; } else if(response.statusCode == 400){ throw ClientException("Client's error"); } else if(response.statusCode==401){ throw PasswordException("Password's error"); } else if(response.statusCode == 404){ throw ExistException("Source not exist"); } else if (response.statusCode == 422){ await jwtService.deleteJwt(); throw AuthException("JWT invalid"); } else if(response.statusCode == 500){ throw ServerException("Server's error"); } else{ throw Exception('Failed in unknown reason'); } } Future<void> logout() async { String? jwt=await jwtService.getJwt(); if(jwt==null){ throw AuthException("JWT invalid"); } final response = await httpClient.delete( Uri.parse(ApiRoutes.logoutUrl), headers: { 'Authorization': 'Bearer $jwt' }, ); if (response.statusCode == 201) { return ; } else if(response.statusCode == 400){ throw ClientException("Client's error"); } else if(response.statusCode == 404){ throw ExistException("Source not exist"); } else if (response.statusCode == 422){ await jwtService.deleteJwt(); throw AuthException("JWT invalid"); } else if(response.statusCode == 500){ throw ServerException("Server's error"); } else{ throw Exception('Failed in unknown reason'); } } }
0
mirrored_repositories/study_savvy_app/lib/services
mirrored_repositories/study_savvy_app/lib/services/article_improver/api_article_improver.dart
import 'dart:convert'; import 'dart:io'; import 'package:study_savvy_app/utils/exception.dart'; import 'package:study_savvy_app/models/article_improver/model_article_improver.dart'; import '../api_routes.dart'; import '../utils/jwt_storage.dart'; import 'package:http/http.dart' as http; import 'package:http_parser/http_parser.dart'; class ArticleImproverService { JwtService jwtService; http.Client httpClient; ArticleImproverService({JwtService? jwtService, http.Client? httpClient,}): jwtService = jwtService ?? JwtService(), httpClient = httpClient ?? http.Client(); Future<void> predictOcrGraph(ArticleImage data) async { String? jwt=await jwtService.getJwt(); if(jwt==null){ throw AuthException("JWT invalid"); } File imageData=data.image; String text=data.prompt; final response = await httpClient.send(http.MultipartRequest( 'POST', Uri.parse(ApiRoutes.articleImproverUrl), ) ..fields['prompt']=text ..files.add(await http.MultipartFile.fromPath( 'file', imageData.path, contentType: MediaType('image', 'jpeg'), )) ..headers.addAll( { 'Authorization': 'Bearer $jwt' }, )); if (response.statusCode == 200) { return ; } else if(response.statusCode == 400){ throw ClientException("Client's error"); } else if(response.statusCode == 404){ throw ExistException("Source not exist"); } else if (response.statusCode == 422){ await jwtService.deleteJwt(); throw AuthException("JWT invalid"); } else if(response.statusCode == 500){ throw ServerException("Server's error"); } else{ throw Exception('Failed in unknown reason'); } } Future<void> predictOcrText(ArticleText data) async { String? jwt=await jwtService.getJwt(); if(jwt==null){ throw AuthException("JWT invalid"); } final response = await httpClient.post( Uri.parse(ApiRoutes.articleImproverTextUrl), headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer $jwt' }, body: jsonEncode(data.formatJson()), ); if (response.statusCode == 200) { return ; } else if(response.statusCode == 400){ throw ClientException("Client's error"); } else if(response.statusCode == 404){ throw ExistException("Source not exist"); } else if (response.statusCode == 422){ await jwtService.deleteJwt(); throw AuthException("JWT invalid"); } else if(response.statusCode == 500){ throw ServerException("Server's error"); } else{ throw Exception('Failed in unknown reason'); } } }
0
mirrored_repositories/study_savvy_app/lib/services
mirrored_repositories/study_savvy_app/lib/services/files/api_files.dart
import 'dart:convert'; import 'dart:typed_data'; import 'package:http/http.dart' as http; import 'package:study_savvy_app/models/files/model_files.dart'; import 'package:study_savvy_app/services/api_routes.dart'; import 'package:study_savvy_app/services/utils/jwt_storage.dart'; import 'package:study_savvy_app/utils/exception.dart'; class FilesService { JwtService jwtService; http.Client httpClient; FilesService({JwtService? jwtService, http.Client? httpClient,}): jwtService = jwtService ?? JwtService(), httpClient = httpClient ?? http.Client(); Future<Uint8List?> getImage(String id) async { String? jwt=await jwtService.getJwt(); if(jwt==null){ throw AuthException("JWT invalid"); } final response = await httpClient.get( Uri.parse("${ApiRoutes.fileImageUrl}/$id"), headers: {'Authorization': 'Bearer $jwt'}, ); if (response.statusCode == 200) { return response.bodyBytes; } else if (response.statusCode==203){ return null; } else if(response.statusCode == 400){ throw ClientException("Client's error"); } else if(response.statusCode == 404){ throw ExistException("Source not exist"); } else if (response.statusCode == 422){ await jwtService.deleteJwt(); throw AuthException("JWT invalid"); } else if(response.statusCode == 500){ throw ServerException("Server's error"); } else{ throw Exception('Failed in unknown reason'); } } Future<Uint8List> getAudio(String id) async { String? jwt=await jwtService.getJwt(); if(jwt==null){ throw AuthException("JWT invalid"); } final response = await httpClient.get( Uri.parse("${ApiRoutes.fileAudioUrl}/$id"), headers: {'Authorization': 'Bearer $jwt'}, ); if (response.statusCode == 200) { return response.bodyBytes; } else if(response.statusCode == 400){ throw ClientException("Client's error"); } else if(response.statusCode == 404){ throw ExistException("Source not exist"); } else if (response.statusCode == 422){ await jwtService.deleteJwt(); throw AuthException("JWT invalid"); } else if(response.statusCode == 500){ throw ServerException("Server's error"); } else{ throw Exception('Failed in unknown reason'); } } Future<SpecificFile> getSpecificFile(String id) async { String? jwt=await jwtService.getJwt(); if(jwt==null){ throw AuthException("JWT invalid"); } final response = await httpClient.get( Uri.parse("${ApiRoutes.fileUrl}/$id"), headers: {'Authorization': 'Bearer $jwt'}, ); if (response.statusCode == 200) { return SpecificFile.fromJson(jsonDecode(response.body)); } else if(response.statusCode == 400){ throw ClientException("Client's error"); } else if(response.statusCode == 404){ throw ExistException("Source not exist"); } else if (response.statusCode == 422){ await jwtService.deleteJwt(); throw AuthException("JWT invalid"); } else if(response.statusCode == 500){ throw ServerException("Server's error"); } else{ throw Exception('Failed in unknown reason'); } } Future<Files> getFiles(int page) async { String? jwt=await jwtService.getJwt(); if(jwt==null){ throw AuthException("JWT invalid"); } final response = await httpClient.get( Uri.parse("${ApiRoutes.fileUrl}?page=$page"), headers: {'Authorization': 'Bearer $jwt'}, ); if (response.statusCode == 200) { Map<String,dynamic> result=jsonDecode(response.body); return Files.fromJson(result); } else if(response.statusCode == 400){ throw ClientException("Client's error"); } else if(response.statusCode == 404){ throw ExistException("Source not exist"); } else if (response.statusCode == 422){ await jwtService.deleteJwt(); throw AuthException("JWT invalid"); } else if(response.statusCode == 500){ throw ServerException("Server's error"); } else{ throw Exception('Failed in unknown reason'); } } Future<void> deleteSpecificFile(String id) async { String? jwt=await jwtService.getJwt(); if(jwt==null){ throw AuthException("JWT invalid"); } final response = await httpClient.delete( Uri.parse("${ApiRoutes.fileUrl}/$id"), headers: {'Authorization': 'Bearer $jwt'}, ); if (response.statusCode == 201) { return ; } else if(response.statusCode == 400){ throw ClientException("Client's error"); } else if(response.statusCode == 404){ throw ExistException("Source not exist"); } else if (response.statusCode == 422){ await jwtService.deleteJwt(); throw AuthException("JWT invalid"); } else if(response.statusCode == 500){ throw ServerException("Server's error"); } else{ throw Exception('Failed in unknown reason'); } } Future<void> editSpecificFileOCR(EditFile file) async { String? jwt=await jwtService.getJwt(); if(jwt==null){ throw AuthException("JWT invalid"); } final String id=file.id; final response = await httpClient.put( Uri.parse("${ApiRoutes.fileNlpEditOCRUrl}/$id"), headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer $jwt' }, body: jsonEncode(file.formatJson()) ); if (response.statusCode == 200) { return ; } else if(response.statusCode == 400){ throw ClientException("Client's error"); } else if(response.statusCode == 404){ throw ExistException("Source not exist"); } else if (response.statusCode == 422){ await jwtService.deleteJwt(); throw AuthException("JWT invalid"); } else if(response.statusCode == 500){ throw ServerException("Server's error"); } else{ throw Exception('Failed in unknown reason'); } } Future<void> editSpecificFileASR(EditFile file) async { String? jwt=await jwtService.getJwt(); if(jwt==null){ throw AuthException("JWT invalid"); } final String id=file.id; final response = await httpClient.put( Uri.parse("${ApiRoutes.fileNlpEditASRUrl}/$id"), headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer $jwt' }, body: jsonEncode(file.formatJson()) ); if (response.statusCode == 200) { return ; } else if(response.statusCode == 400){ throw ClientException("Client's error"); } else if(response.statusCode == 404){ throw ExistException("Source not exist"); } else if (response.statusCode == 422){ await jwtService.deleteJwt(); throw AuthException("JWT invalid"); } else if(response.statusCode == 500){ throw ServerException("Server's error"); } else{ throw Exception('Failed in unknown reason'); } } }
0
mirrored_repositories/study_savvy_app/lib/services
mirrored_repositories/study_savvy_app/lib/services/utils/jwt_storage.dart
import 'package:flutter_secure_storage/flutter_secure_storage.dart'; class JwtService { static AndroidOptions _getAndroidOptions() => const AndroidOptions( encryptedSharedPreferences: true, ); final FlutterSecureStorage _storage; JwtService({FlutterSecureStorage? storage}) : _storage = storage ?? FlutterSecureStorage(aOptions: _getAndroidOptions()); static const _jwtKey = 'jwt'; Future<void> saveJwt(String jwt) async { await _storage.write(key: _jwtKey, value: jwt); } Future<String?> getJwt() async { return _storage.read(key: _jwtKey); } Future<void> deleteJwt() async { await _storage.delete(key: _jwtKey); } Future<bool?> hasJwt() async { return _storage.containsKey(key: _jwtKey); } }
0
mirrored_repositories/study_savvy_app/lib/services
mirrored_repositories/study_savvy_app/lib/services/utils/encrypt.dart
import 'dart:convert'; import 'package:flutter/services.dart'; import 'package:pointycastle/export.dart'; import 'package:encrypt/encrypt.dart'; import 'package:pointycastle/asymmetric/api.dart'; import 'package:asn1lib/asn1lib.dart'; import 'package:study_savvy_app/models/profile/model_profile.dart'; Future<SecureData> encrypt(String text) async { final plainText = text; final key = Key.fromSecureRandom(32); final iv = IV.fromSecureRandom(16); final encryptAES = Encrypter(AES(key, mode: AESMode.ecb)); final encrypted = encryptAES.encrypt(plainText, iv: iv); final publicKey = await parsePublicKeyFromPemFile('assets/keys/public_key.pem'); final encryptRSA = Encrypter(RSA(publicKey: publicKey,encoding: RSAEncoding.OAEP)); final encryptedKey = encryptRSA.encrypt(key.base64); final encodedEncryptedData = base64.encode(encrypted.bytes); final encodedEncryptedKey = encryptedKey.base64; return SecureData(encodedEncryptedData, encodedEncryptedKey); } Future<RSAPublicKey> parsePublicKeyFromPemFile(String path) async { final publicKeyAsPem = await rootBundle.loadString(path); final publicKeyAsDer = decodePEM(publicKeyAsPem); final asn1Parser = ASN1Parser(publicKeyAsDer); final topLevelSequence = asn1Parser.nextObject() as ASN1Sequence; final publicKeyBitString = topLevelSequence.elements[1]; final publicKeyAsn = ASN1Parser(publicKeyBitString.contentBytes()!); final asnSequence = publicKeyAsn.nextObject() as ASN1Sequence; final modulus = (asnSequence.elements[0] as ASN1Integer).valueAsBigInteger; final exponent = (asnSequence.elements[1] as ASN1Integer).valueAsBigInteger; return RSAPublicKey(modulus!, exponent!); } Uint8List decodePEM(String pem) { final startsWith = [ '-----BEGIN PUBLIC KEY-----', '-----BEGIN RSA PUBLIC KEY-----', ]; final endsWith = [ '-----END PUBLIC KEY-----', '-----END RSA PUBLIC KEY-----', ]; bool isOpenSSLKeys = true; for (var s in startsWith) { if (pem.startsWith(s)) { isOpenSSLKeys = true; } } for (var s in endsWith) { if (pem.endsWith(s)) { isOpenSSLKeys = true; } } if (isOpenSSLKeys) { pem = pem.replaceAll(RegExp(r'-+(BEGIN|END) PUBLIC KEY-+'), ''); } pem = pem.replaceAll('\n', '').replaceAll('\r', ''); return base64.decode(pem); }
0
mirrored_repositories/study_savvy_app/lib/services
mirrored_repositories/study_savvy_app/lib/services/utils/mode_storage.dart
import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; class ModeService{ static const Map<ThemeMode,int> indexThemeMode={ ThemeMode.system:0,ThemeMode.light:1,ThemeMode.dark:2 }; static const Map<int,ThemeMode> themeModeIndex={ 0:ThemeMode.system,1:ThemeMode.light,2:ThemeMode.dark }; void setMode(ThemeMode value) async { final prefs = await SharedPreferences.getInstance(); await prefs.setInt('Mode', indexThemeMode[value]??0); } Future<ThemeMode> getMode() async { final prefs = await SharedPreferences.getInstance(); return themeModeIndex[prefs.getInt('Mode')] ?? ThemeMode.system; } }
0
mirrored_repositories/study_savvy_app/lib
mirrored_repositories/study_savvy_app/lib/screens/home.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:study_savvy_app/blocs/utils/bloc_navigator.dart'; import 'package:study_savvy_app/widgets/custom_navigate.dart'; class MenuHome extends StatefulWidget{ const MenuHome({Key?key}):super(key: key); @override State<MenuHome> createState()=> _HomePage(); } class _HomePage extends State<MenuHome> { @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Theme.of(context).primaryColor, body: BlocBuilder<PageBloc, PageState>( builder: (context, state) { return SafeArea( child: Padding( padding: const EdgeInsets.symmetric(vertical: 10,horizontal: 20), child: pageWidgets[state]??Container(), )); } ), bottomNavigationBar:const CustomNavigate(), ); } }
0
mirrored_repositories/study_savvy_app/lib
mirrored_repositories/study_savvy_app/lib/screens/initial.dart
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:study_savvy_app/blocs/SignUp/sign_up_event.dart'; import 'package:study_savvy_app/blocs/provider/theme_provider.dart'; import 'package:study_savvy_app/screens/sign_in/sign_in.dart'; import 'package:study_savvy_app/screens/signup/sign_up.dart'; import '../blocs/SignUp/sign_up_bloc.dart'; class HomePage extends StatelessWidget { const HomePage({super.key}); @override Widget build(BuildContext context) { final themeProvider = Provider.of<ThemeProvider>(context); return Container( alignment: Alignment.center, decoration: BoxDecoration( image: DecorationImage( image: (themeProvider.themeMode == ThemeMode.light) || (themeProvider.themeMode == ThemeMode.system) ? const AssetImage('assets/images/initial_white.jpg') : const AssetImage('assets/images/initial.jpg'), fit: BoxFit.cover, )), child: Container( margin: const EdgeInsets.only(top: 400.0), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ SizedBox( width: 189, height: 49, child: ElevatedButton( style: ButtonStyle( backgroundColor: MaterialStateProperty.all(themeProvider.themeMode == ThemeMode.dark ? Colors.white : Colors.black), elevation: MaterialStateProperty.all(5), ), child: Text( 'Sign in', textAlign: TextAlign.center, style: TextStyle( color: themeProvider.themeMode == ThemeMode.dark ? Colors.black : Colors.white, fontSize: 23, fontFamily: 'Play', fontWeight: FontWeight.bold, ), ), onPressed: () { Navigator.push( context, MaterialPageRoute(builder: (context) => const SignInPage())); }, ), ), const SizedBox(height: 16), SizedBox( width: 189, height: 49, child: ElevatedButton( style: ButtonStyle( backgroundColor: MaterialStateProperty.all(themeProvider.themeMode == ThemeMode.dark ? Colors.white : Colors.black), elevation: MaterialStateProperty.all(5), ), child: Text( 'Sign up', textAlign: TextAlign.center, style: TextStyle( color: themeProvider.themeMode == ThemeMode.dark ? Colors.black : Colors.white, fontSize: 23, fontFamily: 'Play', fontWeight: FontWeight.bold, ) ), onPressed: () { context.read<SignUpBloc>().add(SignUpEventReset()); Navigator.push(context, MaterialPageRoute(builder: (context) => SignUpView())); }, ) ), ] ) ) ); } }
0
mirrored_repositories/study_savvy_app/lib/screens
mirrored_repositories/study_savvy_app/lib/screens/sign_in/sign_in.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:study_savvy_app/blocs/auth/auth_cubit.dart'; import 'package:study_savvy_app/screens/signup/sign_up.dart'; import 'package:study_savvy_app/blocs/LogIn/login_state.dart'; import 'package:study_savvy_app/blocs/LogIn/login_event.dart'; import 'package:study_savvy_app/blocs/auth/form_submission_status.dart'; import 'package:study_savvy_app/blocs/auth/auth_repository.dart'; import 'package:study_savvy_app/blocs/LogIn/login_bloc.dart'; import '../../blocs/SignUp/sign_up_bloc.dart'; import '../../blocs/SignUp/sign_up_event.dart'; import '../../blocs/profile/bloc_online.dart'; class SignInPage extends StatefulWidget { const SignInPage({super.key}); @override State<SignInPage> createState() => _SignInPageState(); } class _SignInPageState extends State<SignInPage> { final _formKey = GlobalKey<FormState>(); final TextEditingController emailController = TextEditingController(); final TextEditingController passwordController = TextEditingController(); AuthRepository authRepo = AuthRepository(); LoginState loginState = LoginState(); @override void dispose() { emailController.dispose(); passwordController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( resizeToAvoidBottomInset: false, backgroundColor: Theme.of(context).primaryColor, body: BlocProvider<LoginBloc>( create: (context) => LoginBloc( authRepo: context.read<AuthRepository>(), authCubit: context.read<AuthCubit>(), ), child: SafeArea( child: Column(children: [ Expanded(flex: 1, child: Container()), Expanded( flex: 1, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Expanded( flex: 5, child: Text( 'StudySavvy', style: Theme.of(context).textTheme.bodyLarge, textAlign: TextAlign.center, ), ), //Expanded(flex:1,child: Container(),), ], ), ), Expanded( flex: 11, child: BlocListener<LoginBloc, LoginState>( listener: (context, state) { final formStatus = state.formStatus; if (formStatus is SubmissionFailed) { _showSnackBar(context, formStatus.exception.toString()); } else if(formStatus is SubmissionSuccess){ context.read<OnlineBloc>().add(OnlineEventCheck()); Navigator.pop(context); } }, child: Form( key: _formKey, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 40), child: Column( //mainAxisAlignment: MainAxisAlignment.center, children: [ const SizedBox(height: 110,), BlocBuilder<LoginBloc, LoginState>(builder: (context, state) { return TextFormField( controller: emailController, style: TextStyle(color: Theme.of(context).textTheme.titleMedium!.color), decoration: InputDecoration( hintText: 'Email', hintStyle: TextStyle(color: Theme.of(context).textTheme.titleMedium!.color), filled: true, fillColor: Theme.of(context).inputDecorationTheme.fillColor, ), validator: (value) => state.isValidEmail ? null : 'Invalid email address.', onChanged: (value) => context.read<LoginBloc>().add( LoginEmailChanged(email: value), ), ); }), const SizedBox(height: 25,), BlocBuilder<LoginBloc, LoginState>(builder: (context, state) { return TextFormField( controller: passwordController, obscureText: true, style: TextStyle(color: Theme.of(context).textTheme.titleMedium!.color), decoration: InputDecoration( hintText: 'Password', hintStyle: TextStyle(color: Theme.of(context).textTheme.titleMedium!.color), filled: true, fillColor: Theme.of(context).inputDecorationTheme.fillColor, ), validator: (value) => state.isValidPassword ? null : 'Invalid password.', onChanged: (value) => context.read<LoginBloc>().add( LoginPasswordChanged(password: value), ), ); }), const SizedBox(height: 210,), BlocBuilder<LoginBloc, LoginState>(builder: (context, state) { return state.formStatus is FormSubmitting ? const CircularProgressIndicator() : SizedBox( width: 189, height: 49, child: ElevatedButton( style: Theme.of(context).elevatedButtonTheme.style, onPressed: () async { debugPrint('Click "sign in!" button'); if (_formKey.currentState!.validate()) { context.read<LoginBloc>().add(LoginSubmitted()); context.read<OnlineBloc>().add(OnlineEventCheck()); } }, child: const Text( 'Sign in', textAlign: TextAlign.center, style: TextStyle( color: Colors.white, fontSize: 23, fontFamily: 'Play', fontWeight: FontWeight.bold), ), ), ); }) ], ), ), )) ), Expanded( flex: 2, child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text("—————————— sign up ——————————", style: Theme.of(context).textTheme.bodySmall), Text("Don’t have an account?", style: Theme.of(context).textTheme.bodySmall), TextButton( onPressed: () { context.read<SignUpBloc>().add(SignUpEventReset()); Navigator.push( context, MaterialPageRoute( builder: (context) => const SignUpView())); }, child: Text("Sign up", style: Theme.of(context).textTheme.bodyLarge), ), ])) ]), ), ) ); } void _showSnackBar(BuildContext context, String message) { final snackBar = SnackBar(content: Text(message)); ScaffoldMessenger.of(context).showSnackBar(snackBar); } }
0
mirrored_repositories/study_savvy_app/lib/screens
mirrored_repositories/study_savvy_app/lib/screens/sign_in/loading_view.dart
import 'package:flutter/material.dart'; class LoadingView extends StatelessWidget { const LoadingView({super.key}); @override Widget build(BuildContext context) { return const Scaffold( body: Center( child: CircularProgressIndicator(), ), ); } }
0
mirrored_repositories/study_savvy_app/lib/screens
mirrored_repositories/study_savvy_app/lib/screens/note_taker/note_taker.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:provider/provider.dart'; import 'package:study_savvy_app/blocs/note_taker/noteTaker_state.dart'; import 'package:study_savvy_app/styles/custom_style.dart'; import '../../blocs/note_taker/noteTaker_bloc.dart'; import '../../blocs/note_taker/noteTaker_event.dart'; import '../../blocs/provider/audio_provider.dart'; import '../../models/model_noteTaker.dart'; import '../../widgets/loading.dart'; import 'dart:io'; import 'package:wechat_assets_picker/wechat_assets_picker.dart'; import 'package:file_picker/file_picker.dart'; class NoteTakerPage extends StatefulWidget { const NoteTakerPage({Key? key}) : super(key: key); @override State<NoteTakerPage> createState() => _NoteTakerPageState(); } class _NoteTakerPageState extends State<NoteTakerPage> { final _promptController= TextEditingController(); @override Widget build(BuildContext context) { List<PlatformFile> audioFiles = []; //store selected files final audioProvider = Provider.of<FileProvider>(context); void _showAlertDialog(BuildContext context) { showCupertinoModalPopup( context: context, builder: (BuildContext context) { return CupertinoAlertDialog( title: Text('Warn',style: Theme.of(context).textTheme.displayMedium), content: Text("內容不得為空\n請上傳音檔和文字",style: Theme.of(context).textTheme.displaySmall), actions: <Widget>[ CupertinoDialogAction( isDestructiveAction: true, onPressed: (){ Navigator.pop(context); }, child: Text('confirm',style: Theme.of(context).textTheme.displaySmall), ), ], ); }, ); } Future<void> loadAudioFiles() async { FilePickerResult? result = await FilePicker.platform.pickFiles( type: FileType.custom, allowedExtensions: ['mp3', 'mpegwa'], //['mp3', 'wav'], allowMultiple: true, ); if (result != null) { setState(() { audioFiles = result.files; }); } } return GestureDetector( onTap: () { FocusScopeNode currentFocus = FocusScope.of(context); if (!currentFocus.hasPrimaryFocus) { currentFocus.unfocus(); } }, child: Column( children: [ Expanded( flex: 1, child: Text( 'Note taker', style: Theme.of(context).textTheme.bodyLarge, ), ), BlocBuilder<audioBloc, audioState>( builder: (context, state) { if (state.status == "INIT") { return Expanded( flex: 8, //child: SingleChildScrollView( child: Column( children: [ Expanded( flex: 6, child: Container( width: 205, height: 230, decoration: BoxDecoration( border: Border.all( color: const Color(0xA7A7A7), width: 2, ), ), child: IconButton( icon: Image.asset( 'assets/images/recording.png', width: 203, height: 228, ), onPressed: loadAudioFiles, ), ), ), Container( padding: const EdgeInsets.symmetric(horizontal: 45), child: LinearProgressIndicator( backgroundColor: Colors.grey[200], value: 0.5, ), ), const Padding(padding: EdgeInsets.all(20)), Expanded( flex: 4, child: Container( padding: const EdgeInsets.symmetric(vertical: 5), margin: const EdgeInsets.symmetric(horizontal: 10), child: Column( children: [ Container( child: Text( 'Prompt', style: Theme.of(context).textTheme.bodyMedium, ), alignment: Alignment.centerLeft, ), Container( padding: const EdgeInsets.all(8), margin: const EdgeInsets.symmetric(vertical: 5), height: 121, decoration: Theme.of(context).brightness == Brightness.dark ? DarkStyle.boxDecoration : LightStyle.boxDecoration, child: SingleChildScrollView( child: TextField( controller: _promptController, maxLines: null, keyboardType: TextInputType.multiline, decoration: InputDecoration( hintText: "(今日課堂主題)", hintMaxLines: 3, border: InputBorder.none, ), ), ), ), ], ), ), ), // Expanded( // flex: 1, // ), ], ), //), ); } else if(state.status=="PENDING"){ return const Expanded( flex:9, child: Loading() ); } else if (state.status=='SUCCESS'){ return const Expanded( flex:8, child: Center( child:Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Icon(Icons.check_circle_outline,size:40), Text("Success to upload") ], ) ), ); } else{ return const Expanded( flex:8, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Center( child:Icon(Icons.warning_rounded,size:40,color: Colors.red,) ), Text("Fail to upload") ], ) ); } }, ), BlocBuilder<audioBloc, audioState>( builder: (context, state) { if (state.status == "INIT") { return Expanded( flex: 1, child: FractionallySizedBox( widthFactor: 0.5, child: ElevatedButton( onPressed: () { if(audioProvider.file==null){ if(_promptController.text==""){ _showAlertDialog(context); } } else{ context.read<audioBloc>().add(audioChanged(noteTaker_audio(audioProvider.file,_promptController.text))); } }, child: const Text( 'Done', textAlign: TextAlign.center, style: TextStyle( color: Colors.white, fontSize: 23, fontFamily: 'Play', fontWeight: FontWeight.bold, ), ), style: Theme.of(context).elevatedButtonTheme.style, ), ), ); } else if(state.status=="PENDING"){ return Container(); } else{ return Expanded( flex: 1, child:FractionallySizedBox( widthFactor: 0.5, child: ElevatedButton( onPressed: () { audioFiles = []; context.read<audioBloc>().add(audioEventRefresh()); }, style: Theme.of(context).elevatedButtonTheme.style, child:const Text('Reset',textAlign: TextAlign.center,style: TextStyle(color: Colors.white, fontSize:23,fontFamily: 'Play',fontWeight: FontWeight.bold),), ) ) ); } }) ], ), ); } }
0
mirrored_repositories/study_savvy_app/lib/screens
mirrored_repositories/study_savvy_app/lib/screens/signup/sign_up.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:study_savvy_app/blocs/auth/form_submission_status.dart'; import 'package:study_savvy_app/blocs/SignUp/sign_up_bloc.dart'; import 'package:study_savvy_app/blocs/SignUp/sign_up_event.dart'; import 'package:study_savvy_app/blocs/SignUp/sign_up_state.dart'; import 'package:study_savvy_app/models/model_signup.dart'; import 'package:study_savvy_app/screens/sign_in/sign_in.dart'; import '../../blocs/auth/auth_cubit.dart'; import '../../blocs/auth/auth_repository.dart'; import '../../blocs/confirmation/confirmation_bloc.dart'; import '../../blocs/confirmation/confirmation_event.dart'; import '../../blocs/confirmation/confirmation_state.dart'; import '../../widgets/loading.dart'; class SignUpView extends StatefulWidget { const SignUpView({super.key}); @override State<SignUpView> createState() => _SignUpViewState(); } class _SignUpViewState extends State<SignUpView> { final _formKey = GlobalKey<FormState>(); int _currentIndex = 0; late SignUpModel signupModel; @override Widget build(BuildContext context) { return Scaffold( resizeToAvoidBottomInset: false, backgroundColor: Theme.of(context).primaryColor, body: SafeArea( child: Column( children: [ Expanded(flex: 2, child: _topBar(context)), BlocBuilder<SignUpBloc,SignUpState>( builder: ((context, state) { if(state.formStatus=="INIT"){ return Expanded(flex: 11, child: _signUpForm()); } else if(state.formStatus=="PENDING"){ return const Expanded( flex:9, child: Loading(), ); } else if(state.formStatus=="SUCCESS"){ return Expanded( flex:8, child: BlocProvider( create: (context) => ConfirmationBloc( authRepo: context.read<AuthRepository>(), authCubit: context.read<AuthCubit>(), ), child: _confirmationForm(context), ), ); } else if(state.formStatus=="FAILURE"){ return Expanded( flex:8, child: CupertinoAlertDialog( title: Text('Alert',style: Theme.of(context).textTheme.displayMedium), content: const Text('Already have an account? Sign in.'), actions: <Widget>[ CupertinoDialogAction( child: Text('confirm',style: Theme.of(context).textTheme.displaySmall,), onPressed: () { Navigator.of(context).pop(); Navigator.push(context, MaterialPageRoute(builder: (context) => const SignInPage())); }, ), ], ), ); } else if(state.formStatus=="SUCCESS_SIGNUP"){ return Expanded( flex:8, child: CupertinoAlertDialog( title: Text('Success to signup',style: Theme.of(context).textTheme.displayMedium), content: const Text('Go to Sign in!!!'), actions: <Widget>[ CupertinoDialogAction( child: Text('confirm',style: Theme.of(context).textTheme.displaySmall,), onPressed: () { Navigator.of(context).pop(); Navigator.push(context, MaterialPageRoute(builder: (context) => const SignInPage())); }, ), ], ), ); } else{ return Container(); } } ) ), ], ), ), ); //); } Widget _topBar(BuildContext context) { return Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.center, children: [ Expanded( flex: 1, child: IconButton( icon: Icon(Icons.arrow_back_ios_new, color: Theme.of(context).textTheme.bodyLarge!.color), onPressed: () => Navigator.of(context).pop(), ), ), Expanded( flex: 5, child: Row( children: [ Expanded( flex: 5, child: Text( 'StudySavvy', style: Theme.of(context).textTheme.bodyLarge, textAlign: TextAlign.center, ), ), Expanded(flex: 1, child: Container()), ], ), ), ], ); } Widget _signUpForm() { return BlocListener<SignUpBloc, SignUpState>( listener: (context, state) { final formStatus = state.formStatus; if (formStatus is SubmissionFailed) { //改 _showSnackBar(context, formStatus); } }, child: Form( key: _formKey, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 40), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ _emailField(), _usernameField(), _passwordField(), _confirmPasswordField(), Container( padding: const EdgeInsets.only(top: 25), child: Row( children: [ Expanded( flex: 3, child: Text("Gender", style: Theme.of(context).textTheme.displayMedium,)), Expanded(flex:8, child: Container()) ], ), ), _genderSelector(), Container( //button margin: const EdgeInsets.only(top: 80), child: _signUpButton(), ), ], ), ), ), ); } Widget _usernameField() { return BlocBuilder<SignUpBloc, SignUpState>(builder: (context, state) { return TextFormField( decoration: const InputDecoration( hintText: 'Username', ), validator: (value) => state.isValidUsername ? null : 'Username is too short', onChanged: (value) => context.read<SignUpBloc>().add( SignUpUsernameChanged(username: value), ), ); }); } Widget _emailField() { return BlocBuilder<SignUpBloc, SignUpState>(builder: (context, state) { return TextFormField( decoration: const InputDecoration( hintText: 'Email', ), validator: (value) => state.isValidUsername ? null : 'Invalid email', onChanged: (value) => context.read<SignUpBloc>().add( SignUpEmailChanged(email: value), ), ); }); } Widget _passwordField() { return BlocBuilder<SignUpBloc, SignUpState>(builder: (context, state) { return TextFormField( obscureText: true, decoration: const InputDecoration( hintText: 'Password', ), validator: (value) => state.isValidPassword ? null : 'Password is too short', onChanged: (value) => context.read<SignUpBloc>().add( SignUpPasswordChanged(password: value), ), ); }); } Widget _confirmPasswordField() { return BlocBuilder<SignUpBloc, SignUpState>(builder: (context, state) { return TextFormField( obscureText: true, decoration: const InputDecoration( hintText: 'Confirm Password', ), validator: (value) { if (value != state.password) { return 'Password confirmation failed.'; } return null; }, onChanged: (value) => context.read<SignUpBloc>().add( SignUpConfirmPasswordChanged(confirmPassword: value), ), ); }); } Widget _genderSelector(){ return BlocBuilder<SignUpBloc, SignUpState>(builder: (context, state) { return SizedBox( width: 312, height: 50, child: CupertinoSegmentedControl( children: <int, Widget>{ 0: Center(child: Text("Male", style: Theme.of(context).textTheme.bodySmall)), 1: Center(child: Text("Female", style: Theme.of(context).textTheme.bodySmall)), 2: Center(child: Text("Others", style: Theme.of(context).textTheme.bodySmall)), }, groupValue: _currentIndex, //當前選中的 onValueChanged: (int index){ setState(() { _currentIndex = index; }); String selectedGender = _getGenderFromIndex(index); context.read<SignUpBloc>().add(SignUpGenderChanged(gender: selectedGender)); }, selectedColor: Theme.of(context).textTheme.labelLarge!.color, unselectedColor: Theme.of(context).textTheme.titleLarge!.color, borderColor: Theme.of(context).textTheme.titleMedium!.color, pressedColor: Theme.of(context).textTheme.titleMedium!.color!.withOpacity(0.4), ), ); } );} String _getGenderFromIndex(int index) { switch (index) { case 0: return "male"; case 1: return "female"; case 2: return "other"; default: return "male"; } } Widget _signUpButton() { return BlocBuilder<SignUpBloc, SignUpState>(builder: (context, state) { return state.formStatus is FormSubmitting ? const CircularProgressIndicator() : SizedBox( width: 189, height: 49, child: ElevatedButton( onPressed: () { if (_formKey.currentState!.validate()) { signupModel=SignUpModel(_getGenderFromIndex(_currentIndex),state.email,state.username,state.password); context.read<SignUpBloc>().add(SignUpSubmitted(model:signupModel)); } }, child: const Text( 'Sign Up', textAlign: TextAlign.center, style: TextStyle( color: Colors.white, fontSize: 23, fontFamily: 'Play', fontWeight: FontWeight.bold, ), ), ), ); }); } void _showSnackBar(BuildContext context, String message) { final snackBar = SnackBar(content: Text(message)); ScaffoldMessenger.of(context).showSnackBar(snackBar); } Widget _confirmationForm(BuildContext context) { return BlocListener<ConfirmationBloc, ConfirmationState>( listener: (context, state) { final formStatus = state.formStatus; if (formStatus is SubmissionFailed) { _showSnackBar(context, formStatus.exception.toString()); } }, child: Form( key: _formKey, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 40), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( "Please check your email\nfor\nthe confirmation message.", style: Theme.of(context).textTheme.displayMedium, textAlign: TextAlign.center, ), Container( padding: const EdgeInsets.symmetric(vertical: 150), child: _codeField()), _confirmButton(), ], ), ), )); } Widget _codeField() { return BlocBuilder<ConfirmationBloc, ConfirmationState>( builder: (context, state) { return TextFormField( decoration: const InputDecoration( icon: Icon(Icons.cookie_rounded), hintText: 'Confirmation Code', ), validator: (value) => state.isValidCode ? null : 'Invalid confirmation code', onChanged: (value) => context.read<ConfirmationBloc>().add( ConfirmationCodeChanged(code: value), ), ); }); } Widget _confirmButton() { return BlocBuilder<ConfirmationBloc, ConfirmationState>( builder: (context, state) { return state.formStatus is FormSubmitting ? const CircularProgressIndicator() : ElevatedButton( onPressed: () { context.read<SignUpBloc>().add(SignUpVerify(model: signupModel, code: state.code)); }, child: const Text( 'Confirm', textAlign: TextAlign.center, style: TextStyle( color: Colors.white, fontSize: 23, fontFamily: 'Play', fontWeight: FontWeight.bold, ),), ); }); } }
0
mirrored_repositories/study_savvy_app/lib/screens
mirrored_repositories/study_savvy_app/lib/screens/profile/profile.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_cache_manager/flutter_cache_manager.dart'; import 'package:provider/provider.dart'; import 'package:study_savvy_app/blocs/profile/bloc_access_methods.dart'; import 'package:study_savvy_app/blocs/profile/bloc_online.dart'; import 'package:study_savvy_app/blocs/profile/bloc_password.dart'; import 'package:study_savvy_app/blocs/profile/bloc_profile.dart'; import 'package:study_savvy_app/blocs/provider/theme_provider.dart'; import 'package:study_savvy_app/utils/routes.dart'; import 'package:study_savvy_app/widgets/failure.dart'; import 'package:study_savvy_app/widgets/loading.dart'; import 'package:study_savvy_app/widgets/success.dart'; class ProfilePage extends StatefulWidget{ const ProfilePage({Key?key}):super(key: key); @override State<ProfilePage> createState()=> _ProfilePage(); } class _ProfilePage extends State<ProfilePage> { Map<int,ThemeMode> themeModeIndex={ 0:ThemeMode.system,1:ThemeMode.light,2:ThemeMode.dark }; Map<ThemeMode,int> indexThemeMode={ ThemeMode.system:0,ThemeMode.light:1,ThemeMode.dark:2 }; Map<int,String> themeIndex={ 0:"system",1:"light",2:"dark" }; Widget formatThemeUI(int index){ final String gender=themeIndex[index]!; return Container(padding: const EdgeInsets.symmetric(horizontal: 10,vertical: 3),child: Text(gender,style: Theme.of(context).textTheme.displaySmall)); } @override Widget build(BuildContext context) { final themeProvider = Provider.of<ThemeProvider>(context); int groupValue=indexThemeMode[themeProvider.themeMode]??0; void showLogoutDialog(BuildContext context) { showCupertinoModalPopup( context: context, builder: (BuildContext context) { return BlocBuilder<OnlineBloc,OnlineState>( builder: (context,state){ if(state.status==null && state.message==null){ return CupertinoAlertDialog( title: Text('Logout',style: Theme.of(context).textTheme.displayMedium), content: const Loading(), actions: <Widget>[ CupertinoDialogAction( child: Text('close',style: Theme.of(context).textTheme.displaySmall,), onPressed: () { Navigator.of(context).pop(); }, ), ], ); } else if(state.status==true && state.message==null){ return CupertinoAlertDialog( title: Text('Logout',style: Theme.of(context).textTheme.displayMedium), actions: <Widget>[ CupertinoDialogAction( isDestructiveAction: false, child: Text('cancel',style: Theme.of(context).textTheme.displaySmall,), onPressed: () { Navigator.of(context).pop(); }, ), CupertinoDialogAction( isDestructiveAction: true, onPressed: () { context.read<OnlineBloc>().add(OnlineEventLogout()); }, child: Text('confirm',style: Theme.of(context).textTheme.displaySmall,), ), ], ); } else if(state.status==null && state.message!=null && state.message!="SUCCESS"){ return CupertinoAlertDialog( title: Text('Logout',style: Theme.of(context).textTheme.displayMedium), content: Failure(error: state.message!,), actions: <Widget>[ CupertinoDialogAction( child: Text('confirm',style: Theme.of(context).textTheme.displaySmall,), onPressed: () { Navigator.of(context).pop(); }, ), ], ); } else{ return CupertinoAlertDialog( title: Text('Logout',style: Theme.of(context).textTheme.displayMedium), content: const Success(message: "Success to logout",), actions: <Widget>[ CupertinoDialogAction( child: Text('confirm',style: Theme.of(context).textTheme.displaySmall,), onPressed: () { context.read<OnlineBloc>().add(OnlineEventCheck()); Navigator.of(context).pop(); }, ), ], ); } } ); }, ); } return Column( children: [ Expanded( flex: 1, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Expanded(flex:1,child: Container()), Expanded(flex:5,child: Text('Profile',style: Theme.of(context).textTheme.bodyLarge,textAlign: TextAlign.center,),), Expanded(flex:1,child: IconButton(onPressed: (){ showLogoutDialog(context); }, icon: const Icon(Icons.logout),alignment: Alignment.centerRight,)), ], ), ), Expanded( flex: 2, child: Container( margin: const EdgeInsets.symmetric(vertical: 10), child: const Icon(Icons.face_unlock_rounded,size: 130,), ) ), Expanded( flex: 7, child:Container( alignment: Alignment.topLeft, padding: const EdgeInsets.symmetric(vertical: 15), child: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( alignment: Alignment.topLeft, padding: const EdgeInsets.symmetric(horizontal: 10,vertical: 15), child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ Container( margin: const EdgeInsets.only(bottom: 5), child: Text('Information Setting',style: Theme.of(context).textTheme.displayMedium) ), TextButton( onPressed: (){Navigator.pushNamed(context, Routes.information,);context.read<ProfileBloc>().add(ProfileEventGet());}, style: ButtonStyle( overlayColor: MaterialStateProperty.resolveWith<Color>( (Set<MaterialState> states) { if (states.contains(MaterialState.pressed)) { return Theme.of(context).hintColor; } return Colors.transparent; }, ), ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text("Information",style: Theme.of(context).textTheme.displaySmall), Icon(Icons.navigate_next_rounded,size: 25,color: Theme.of(context).hintColor) ], ) ), TextButton( onPressed: (){ context.read<PasswordBloc>().add(PasswordEventReset()); Navigator.pushNamed(context, Routes.password); }, style: ButtonStyle( overlayColor: MaterialStateProperty.resolveWith<Color>( (Set<MaterialState> states) { if (states.contains(MaterialState.pressed)) { return Theme.of(context).hintColor; } return Colors.transparent; }, ), ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text("Change Password",style: Theme.of(context).textTheme.displaySmall), Icon(Icons.navigate_next_rounded,size: 25,color: Theme.of(context).hintColor) ], ) ), ], ), ), Container( alignment: Alignment.topLeft, padding: const EdgeInsets.symmetric(horizontal: 10,vertical: 15), child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ Container( margin: const EdgeInsets.only(bottom: 5), child: Text('CHAT-GPT method',style: Theme.of(context).textTheme.displayMedium) ), TextButton( onPressed: (){context.read<AccessMethodBloc>().add(AccessMethodEventReset());Navigator.pushNamed(context, Routes.apikey);}, style: ButtonStyle( overlayColor: MaterialStateProperty.resolveWith<Color>( (Set<MaterialState> states) { if (states.contains(MaterialState.pressed)) { return Theme.of(context).hintColor; } return Colors.transparent; }, ), ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text("Api_Key",style: Theme.of(context).textTheme.displaySmall), Icon(Icons.navigate_next_rounded,size: 25,color: Theme.of(context).hintColor) ], ) ), TextButton( onPressed: (){context.read<AccessMethodBloc>().add(AccessMethodEventReset());Navigator.pushNamed(context, Routes.accessToken);}, style: ButtonStyle( overlayColor: MaterialStateProperty.resolveWith<Color>( (Set<MaterialState> states) { if (states.contains(MaterialState.pressed)) { return Theme.of(context).hintColor; } return Colors.transparent; }, ), ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text("Access_Token",style: Theme.of(context).textTheme.displaySmall), Icon(Icons.navigate_next_rounded,size: 25,color: Theme.of(context).hintColor) ], ) ), ], ), ), Container( alignment: Alignment.topLeft, padding: const EdgeInsets.symmetric(horizontal: 10,vertical: 15), child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ Container( margin: const EdgeInsets.only(bottom: 10), child: Text('Preference Setting',style: Theme.of(context).textTheme.displayMedium) ), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text("Theme Setting",style: Theme.of(context).textTheme.displaySmall), Theme.of(context).brightness==Brightness.light? Icon(Icons.light_mode,size: 25,color: Theme.of(context).hintColor): Icon(Icons.dark_mode,size: 25,color: Theme.of(context).hintColor) ], ), const Divider(), SizedBox( height: 40, child: ListView( physics: const NeverScrollableScrollPhysics(), children: [ CupertinoSlidingSegmentedControl( groupValue: groupValue, children:{ 0: formatThemeUI(0), 1: formatThemeUI(1), 2: formatThemeUI(2) }, onValueChanged: (value){ themeProvider.themeMode=themeModeIndex[value]!; setState(() { groupValue=value!; }); } ) ], ), ), TextButton( style: ButtonStyle( overlayColor: MaterialStateProperty.resolveWith<Color>( (Set<MaterialState> states) { if (states.contains(MaterialState.pressed)) { return Theme.of(context).hintColor; } return Colors.transparent; }, ), ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text("Empty Cache",style: Theme.of(context).textTheme.displaySmall), Icon(Icons.navigate_next_rounded,size: 25,color: Theme.of(context).hintColor) ], ), onPressed: () async { await DefaultCacheManager().emptyCache(); }, ) ], ), ), ], ), ) ), ), ], ); } }
0
mirrored_repositories/study_savvy_app/lib/screens
mirrored_repositories/study_savvy_app/lib/screens/profile/access_token.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:study_savvy_app/styles/custom_style.dart'; import 'package:url_launcher/url_launcher.dart'; import 'package:study_savvy_app/blocs/profile/bloc_access_methods.dart'; import 'package:study_savvy_app/widgets/loading.dart'; class AccessTokenPage extends StatefulWidget{ const AccessTokenPage({Key?key}):super(key: key); @override State<AccessTokenPage> createState()=> _AccessTokenPage(); } class _AccessTokenPage extends State<AccessTokenPage> { void _launchURL() async { const String url = 'https://chat.openai.com/api/auth/session'; try{ await launchUrl(Uri.parse(url)); } catch (e){ throw("Error to open AccessToken page $e"); } } final _controller= TextEditingController(); @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( resizeToAvoidBottomInset: false, body:GestureDetector( onTap: () { FocusScopeNode currentFocus = FocusScope.of(context); if (!currentFocus.hasPrimaryFocus) { currentFocus.unfocus(); } }, child: SafeArea( child:Padding( padding: const EdgeInsets.symmetric(vertical: 10,horizontal: 20), child: Column( children: [ Expanded( flex: 1, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Expanded(flex:1,child: IconButton(onPressed: (){Navigator.pop(context);}, icon: const Icon(Icons.arrow_back_ios_new),alignment: Alignment.bottomLeft,)), Expanded(flex:5,child: Text('AccessToken',style: Theme.of(context).textTheme.bodyLarge,textAlign: TextAlign.center,),), Expanded(flex:1,child: Container()), ], ), ), Expanded( flex: 8, child:Container( padding: const EdgeInsets.only(bottom: 10), child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Expanded( flex: 1, child: Container() ), BlocBuilder<AccessMethodBloc,AccessMethodState?>( builder: (context,state){ if(state==null){ return Expanded( flex: 5, child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ Text('Access_Token :',style: Theme.of(context).textTheme.displayMedium,), Container( width: double.infinity, decoration: BoxDecoration(borderRadius: BorderRadius.circular(10),border: Border.all(color: Theme.of(context).brightness==Brightness.light?LightStyle.borderColor:DarkStyle.borderColor)), padding: const EdgeInsets.symmetric(horizontal: 10), child: TextField( controller: _controller, onSubmitted: (value){ context.read<AccessMethodBloc>().add(AccessMethodEventAccessToken(_controller.text)); }, maxLines: 1, decoration: const InputDecoration( hintText: "Access_Token", hintMaxLines: 1, border: InputBorder.none, ), ), ) ], ), ); } else if (state.status=="PENDING"){ return const Loading(); } else if (state.status=="SUCCESS"){ return Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ const Icon(Icons.check_circle_outline,color: Color.fromRGBO(48,219,91,1),size: 60,), Text('Success',style: Theme.of(context).textTheme.displayMedium,) ], ); } else{ return Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ const Icon(Icons.dangerous_sharp,color: Colors.red,size: 60,), Text("Failure",style: Theme.of(context).textTheme.displayMedium,) ], ); } }, ), Expanded( flex: 15, child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Text("Have service of chat-gpt by reverse.",style: Theme.of(context).textTheme.displaySmall,), Text("You can give us your ACCESS_TOKEN.",style: Theme.of(context).textTheme.displaySmall,), Text("We won't charge for this service, then you can use the service powered by Open-AI.",style: Theme.of(context).textTheme.displaySmall,), Text("Furthermore, we will use AES, RSA, SSL/TLS algorithm to encrypt your API_KEY.",style: Theme.of(context).textTheme.displaySmall,), Text("Hence, if you want to have the service, gain you ACCESS_TOKEN and give us.",style: Theme.of(context).textTheme.displaySmall,), ], ) ), Expanded( flex: 4, child: TextButton( onPressed: (){_launchURL();}, child: Container( padding: const EdgeInsets.symmetric(horizontal: 20,vertical: 15), decoration: BoxDecoration(border: Border.all(color: Theme.of(context).brightness==Brightness.light?LightStyle.borderColor:DarkStyle.borderColor),borderRadius: BorderRadius.circular(10)), child: Text('Gain your ACCESS_TOKEN',style: Theme.of(context).textTheme.displaySmall,) ) ), ), Expanded( flex: 1, child: Container() ), ], ), ), ), BlocBuilder<AccessMethodBloc,AccessMethodState?>( builder: (context,state){ if (state==null){ return Expanded( flex: 1, child:FractionallySizedBox( widthFactor: 0.5, child: ElevatedButton( onPressed: () { context.read<AccessMethodBloc>().add(AccessMethodEventAccessToken(_controller.text)); }, style: Theme.of(context).elevatedButtonTheme.style, child:const Text('Done',textAlign: TextAlign.center,style: TextStyle(color: Colors.white, fontSize:23,fontFamily: 'Play',fontWeight: FontWeight.bold),), ) ) ); } else{ return Container(); } }, ), ], ) ) ), ), ); } }
0
mirrored_repositories/study_savvy_app/lib/screens
mirrored_repositories/study_savvy_app/lib/screens/profile/information_setting.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:study_savvy_app/models/profile/model_profile.dart'; import 'package:study_savvy_app/styles/custom_style.dart'; import 'package:study_savvy_app/widgets/failure.dart'; import 'package:study_savvy_app/widgets/loading.dart'; import 'package:study_savvy_app/blocs/profile/bloc_profile.dart'; import 'package:study_savvy_app/widgets/success.dart'; class InformationPage extends StatefulWidget{ const InformationPage({Key?key}):super(key: key); @override State<InformationPage> createState()=> _InformationPage(); } class _InformationPage extends State<InformationPage> { void _showAlertDialog(BuildContext context) { showCupertinoModalPopup( context: context, builder: (BuildContext context) { return CupertinoAlertDialog( title: Text('Warn',style: Theme.of(context).textTheme.displayMedium), content: _controller.text.isEmpty?Text("Name 部分不得為空",style: Theme.of(context).textTheme.displaySmall):Text("與原資料相符 未做更動",style: Theme.of(context).textTheme.displaySmall), actions: <Widget>[ CupertinoDialogAction( isDestructiveAction: true, onPressed: (){ Navigator.pop(context); }, child: Text('confirm',style: Theme.of(context).textTheme.displaySmall), ), ], ); }, ); } int groupValue=0; late TextEditingController _controller; late ProfileBloc bloc; late final String originalName; late final String originalGender; Map<int,String> genderIndex={ 0:"male",1:"female",2:"other" }; Widget formatGenderUI(int index){ final String gender=genderIndex[index]!; return Container(padding: const EdgeInsets.symmetric(horizontal: 10,vertical: 3),child: Text(gender,style: Theme.of(context).textTheme.displaySmall)); } @override void initState() { super.initState(); _controller= TextEditingController(); bloc=BlocProvider.of<ProfileBloc>(context); context.read<ProfileBloc>().stream.listen((ProfileState state) { if(state.status=="SUCCESS"){ if(mounted){ _controller.text=state.profile.name; originalName=state.profile.name; originalGender=state.profile.gender; setState(() { if(state.profile.gender=="male"){ groupValue=0; } else if(state.profile.gender=="female"){ groupValue=1; }else{ groupValue=2; } }); } } }); } @override void dispose() { _controller.dispose(); bloc.add(ProfileEventReset()); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( resizeToAvoidBottomInset: false, body: SafeArea( child: Padding( padding: const EdgeInsets.symmetric( vertical: 10, horizontal: 20), child: Column( children: [ Expanded( flex: 1, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Expanded(flex: 1, child: IconButton(onPressed: () { Navigator.pop(context); }, icon: const Icon(Icons.arrow_back_ios_new), alignment: Alignment.bottomLeft,)), Expanded(flex: 5, child: Text('Information', style: Theme .of(context) .textTheme .bodyLarge, textAlign: TextAlign.center,),), Expanded(flex: 1, child: Container()), ], ), ), Expanded( flex: 8, child: BlocBuilder<ProfileBloc,ProfileState>( builder: (context,state) { if (state.status=="INIT" || state.status=="PENDING") { return const Loading(); } else if(state.status=="SUCCESS"){ return Container( width: double.infinity, padding: const EdgeInsets.symmetric(horizontal: 20), child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, children: [ Expanded(flex: 1,child: Container(),), Expanded( flex: 2, child: Container( padding: const EdgeInsets.symmetric(horizontal: 15,vertical: 15), decoration: BoxDecoration(borderRadius: BorderRadius.circular(10),border: Border.all(color: Theme.of(context).brightness==Brightness.light?LightStyle.borderColor:DarkStyle.borderColor)), child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: [ Expanded( flex: 1, child: Text('Name:', style: Theme.of(context).textTheme.displayMedium,) ), Expanded( flex: 1, child: Container( decoration: BoxDecoration(borderRadius: BorderRadius.circular(10),border: Border.all(color: Theme.of(context).brightness==Brightness.light?LightStyle.borderColor:DarkStyle.borderColor)), padding: const EdgeInsets.symmetric(horizontal: 10), child: TextField( controller: _controller, // textAlign: TextAlign.center, textAlignVertical: TextAlignVertical.center, maxLines: 1, decoration: const InputDecoration( hintText: "Name", hintMaxLines: 1, border: InputBorder.none, floatingLabelAlignment: FloatingLabelAlignment.center ), ), ), ), ], ), ), ), Expanded(flex: 1,child: Container(),), Expanded( flex: 2, child: Container( width: double.infinity, padding: const EdgeInsets.symmetric(horizontal: 15,vertical: 15), decoration: BoxDecoration(borderRadius: BorderRadius.circular(10),border: Border.all(color: Theme.of(context).brightness==Brightness.light?LightStyle.borderColor:DarkStyle.borderColor)), child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: [ Expanded( flex:1, child: Text('Email:', style: Theme.of(context).textTheme.displayMedium,) ), Expanded( flex: 1, child: Text(state.profile.mail, style: Theme.of(context).textTheme.displaySmall) ), ], ), ), ), Expanded(flex: 1,child: Container(),), Expanded( flex: 2, child: Container( padding: const EdgeInsets.symmetric(horizontal: 15,vertical: 15), decoration: BoxDecoration(borderRadius: BorderRadius.circular(10),border: Border.all(color: Theme.of(context).brightness==Brightness.light?LightStyle.borderColor:DarkStyle.borderColor)), child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: [ Expanded( flex: 1, child: Text('Gender:', style: Theme.of(context).textTheme.displayMedium,) ), Expanded( flex: 1, child: ListView( physics: const NeverScrollableScrollPhysics(), children: [ CupertinoSlidingSegmentedControl( groupValue: groupValue, children:{ 0: formatGenderUI(0), 1: formatGenderUI(1), 2: formatGenderUI(2) }, onValueChanged: (value){ setState(() { groupValue=value!; }); } ) ], ), ), ], ), ), ), Expanded(flex: 1,child: Container(),), ], ), ); } else if(state.status=="FAILURE"){ return Failure(error: state.message!,); } else if(state.status=="SUCCESS_OTHER"){ return Success(message: state.message!); } else{ return const Failure(error: "UNKNOWN STATUS"); } } ) ), Expanded( flex: 1, child: BlocBuilder<ProfileBloc,ProfileState>( builder: (context,state){ if(state.status=="SUCCESS"){ return FractionallySizedBox( widthFactor: 0.5, child: ElevatedButton( onPressed: () { if(_controller.text.isEmpty){ _showAlertDialog(context); } else if(_controller.text.toString()==originalName && genderIndex[groupValue]==originalGender){ _showAlertDialog(context); } else{ context.read<ProfileBloc>().add(ProfileEventUpdate(UpdateProfile(_controller.text.toString(),genderIndex[groupValue]!))); } }, style: Theme .of(context) .elevatedButtonTheme .style, child: const Text( 'Save', textAlign: TextAlign.center, style: TextStyle(color: Colors.white, fontSize: 23, fontFamily: 'Play', fontWeight: FontWeight.bold),), ) ); } else{ return Container(); } } ), ), ], ) ) ), ); } }
0
mirrored_repositories/study_savvy_app/lib/screens
mirrored_repositories/study_savvy_app/lib/screens/profile/password_setting.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:study_savvy_app/blocs/profile/bloc_password.dart'; import 'package:study_savvy_app/styles/custom_style.dart'; import 'package:study_savvy_app/widgets/loading.dart'; import 'package:study_savvy_app/widgets/success.dart'; import 'package:study_savvy_app/models/profile/model_profile.dart'; import 'package:study_savvy_app/widgets/failure.dart'; class PasswordPage extends StatefulWidget{ const PasswordPage({Key?key}):super(key: key); @override State<PasswordPage> createState()=> _PasswordPage(); } class _PasswordPage extends State<PasswordPage> { final _formKeyOldPassword = GlobalKey<FormState>(); final _formKeyNewPassword = GlobalKey<FormState>(); final _formKeyConfirmPassword = GlobalKey<FormState>(); final oldPasswordController = TextEditingController(); final newPasswordController = TextEditingController(); final confirmPasswordController = TextEditingController(); final FocusNode oldPasswordNode=FocusNode(); final FocusNode newPasswordNode=FocusNode(); final FocusNode confirmPasswordNode=FocusNode(); @override void dispose() { oldPasswordNode.dispose(); oldPasswordController.dispose(); newPasswordNode.dispose(); newPasswordController.dispose(); confirmPasswordNode.dispose(); confirmPasswordController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { void submitForm() { if (_formKeyOldPassword.currentState!.validate() && _formKeyNewPassword.currentState!.validate() && _formKeyConfirmPassword.currentState!.validate()) { context.read<PasswordBloc>().add(PasswordEventUpdate(UpdatePwd(oldPasswordController.text.toString(),newPasswordController.text.toString()))); } } return Scaffold( resizeToAvoidBottomInset: false, body:GestureDetector( onTap: () { FocusScopeNode currentFocus = FocusScope.of(context); if (!currentFocus.hasPrimaryFocus) { currentFocus.unfocus(); } }, child: SafeArea( child:Padding( padding: const EdgeInsets.symmetric(vertical: 10,horizontal: 20), child: Column( children: [ Expanded( flex: 1, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Expanded(flex:1,child: IconButton(onPressed: (){Navigator.pop(context);}, icon: const Icon(Icons.arrow_back_ios_new),alignment: Alignment.bottomLeft,)), Expanded(flex:5,child: Text('Password',style: Theme.of(context).textTheme.bodyLarge,textAlign: TextAlign.center,),), Expanded(flex:1,child: Container()), ], ), ), BlocBuilder<PasswordBloc,PasswordState>( builder: (context,state){ if(state.status=="INIT"){ return Expanded( flex: 9, child:Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( decoration: BoxDecoration(borderRadius: const BorderRadius.all(Radius.circular(10)),border: Border.all(color: Theme.of(context).brightness==Brightness.light?LightStyle.borderColor:DarkStyle.borderColor,)), padding: const EdgeInsets.symmetric(horizontal: 20,vertical: 10), child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Text('Password Edit :',style: Theme.of(context).textTheme.displayMedium,), const Divider(), Container( padding: const EdgeInsets.symmetric(horizontal: 15), decoration: BoxDecoration(borderRadius: const BorderRadius.all(Radius.circular(10)),border: Border.all(color: Theme.of(context).brightness==Brightness.light?LightStyle.borderColor:DarkStyle.borderColor,)), child: Form( key: _formKeyOldPassword, child: TextFormField( controller: oldPasswordController, maxLines: 1, decoration: const InputDecoration( hintText: "Enter the Password", hintMaxLines: 1, border: InputBorder.none, ), obscureText: true, focusNode: oldPasswordNode, onFieldSubmitted: (value){ if (_formKeyOldPassword.currentState!.validate()){ FocusScope.of(context).requestFocus(newPasswordNode); } else{ FocusScope.of(context).requestFocus(oldPasswordNode); } }, validator: (value) { if (value == null || value.isEmpty) { return 'Empty Error'; } else if(value.contains(' ')){ return 'Space Error'; } else if(value.length<8){ return 'At least 8 chars Error'; } return null; }, ), ), ), const Divider(), Container( padding: const EdgeInsets.symmetric(horizontal: 15), decoration: BoxDecoration(borderRadius: const BorderRadius.all(Radius.circular(10)),border: Border.all(color: Theme.of(context).brightness==Brightness.light?LightStyle.borderColor:DarkStyle.borderColor,)), child: Form( key: _formKeyNewPassword, child: TextFormField( controller: newPasswordController, maxLines: 1, focusNode: newPasswordNode, decoration: const InputDecoration( hintText: "Enter new Password", hintMaxLines: 1, border: InputBorder.none, ), obscureText: true, validator: (value) { if (value == null || value.isEmpty) { return 'Empty Error'; } else if(value==oldPasswordController.text.toString()){ return 'Same with current Error'; } else if(value.contains(' ')){ return 'Have space Error'; } else if(value.length<8){ return 'At least 8 chars Error'; } return null; }, onFieldSubmitted: (value){ if (_formKeyOldPassword.currentState!.validate() && _formKeyNewPassword.currentState!.validate()){ FocusScope.of(context).requestFocus(confirmPasswordNode); } else{ FocusScope.of(context).requestFocus(newPasswordNode); } }, ), ), ), const Divider(), Container( padding: const EdgeInsets.symmetric(horizontal: 15), decoration: BoxDecoration(borderRadius: const BorderRadius.all(Radius.circular(10)),border: Border.all(color: Theme.of(context).brightness==Brightness.light?LightStyle.borderColor:DarkStyle.borderColor,)), child: Form( key: _formKeyConfirmPassword, child: TextFormField( controller: confirmPasswordController, maxLines: 1, decoration: const InputDecoration( hintText: "Confirm new Password", hintMaxLines: 1, border: InputBorder.none, ), obscureText: true, focusNode: confirmPasswordNode, onFieldSubmitted: (value){ if (_formKeyOldPassword.currentState!.validate() && _formKeyNewPassword.currentState!.validate() && _formKeyConfirmPassword.currentState!.validate()){ submitForm(); } else{ FocusScope.of(context).requestFocus(confirmPasswordNode); } }, validator: (value) { if (value == null || value.isEmpty) { return 'Empty Error'; } else if (value != newPasswordController.text.toString()) { return 'Match Error'; } return null; }, ), ), ), ], ), ), const Divider(), Center( child: FractionallySizedBox( widthFactor: 0.5, child: ElevatedButton( onPressed: () { submitForm(); }, style: Theme.of(context).elevatedButtonTheme.style, child:const Text('Done',textAlign: TextAlign.center,style: TextStyle(color: Colors.white, fontSize:23,fontFamily: 'Play',fontWeight: FontWeight.bold),), ) ), ) ], ) ); } else if(state.status=="PENDING"){ return const Expanded( flex:9, child: Loading(), ); } else if(state.status=="SUCCESS"){ return const Expanded( flex:8, child: Success(message: "Success to update Password",), ); } else if(state.status=="FAILURE"){ return Expanded( flex:8, child: Failure(error: state.error!,), ); } else{ return Container(); } } ), ], ) ) ), ), ); } }
0
mirrored_repositories/study_savvy_app/lib/screens
mirrored_repositories/study_savvy_app/lib/screens/profile/api_key.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:study_savvy_app/blocs/profile/bloc_access_methods.dart'; import 'package:study_savvy_app/styles/custom_style.dart'; import 'package:study_savvy_app/widgets/loading.dart'; import 'package:url_launcher/url_launcher.dart'; class ApiKeyPage extends StatefulWidget{ const ApiKeyPage({Key?key}):super(key: key); @override State<ApiKeyPage> createState()=> _ApiKeyPage(); } class _ApiKeyPage extends State<ApiKeyPage> { void _launchURL() async { const String url = 'https://platform.openai.com/account/api-keys'; try{ await launchUrl(Uri.parse(url)); } catch (e){ throw("Error to open apikey page $e"); } } final _controller= TextEditingController(); @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( resizeToAvoidBottomInset: false, body:GestureDetector( onTap: () { FocusScopeNode currentFocus = FocusScope.of(context); if (!currentFocus.hasPrimaryFocus) { currentFocus.unfocus(); } }, child: SafeArea( child:Padding( padding: const EdgeInsets.symmetric(vertical: 10,horizontal: 20), child: Column( children: [ Expanded( flex: 1, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Expanded(flex:1,child: IconButton(onPressed: (){Navigator.pop(context);}, icon: const Icon(Icons.arrow_back_ios_new),alignment: Alignment.bottomLeft,)), Expanded(flex:5,child: Text('Api_Key',style: Theme.of(context).textTheme.bodyLarge,textAlign: TextAlign.center,),), Expanded(flex:1,child: Container()), ], ), ), Expanded( flex: 8, child:Container( padding: const EdgeInsets.only(bottom: 10), child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Expanded( flex: 1, child: Container() ), BlocBuilder<AccessMethodBloc,AccessMethodState?>( builder: (context,state){ if(state==null){ return Expanded( flex: 5, child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ Text('Api_Key :',style: Theme.of(context).textTheme.displayMedium,), Container( decoration: BoxDecoration(borderRadius: BorderRadius.circular(10),border: Border.all(color: Theme.of(context).brightness==Brightness.light?LightStyle.borderColor:DarkStyle.borderColor)), padding: const EdgeInsets.symmetric(horizontal: 10), child: TextField( onSubmitted: (value){ context.read<AccessMethodBloc>().add(AccessMethodEventApiKey(_controller.text)); }, controller: _controller, maxLines: 1, decoration: const InputDecoration( hintText: "Api_Key", hintMaxLines: 1, border: InputBorder.none, ), ), ) ], ), ); } else if (state.status=="PENDING"){ return const Loading(); } else if (state.status=="SUCCESS"){ return Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ const Icon(Icons.check_circle_outline,color: Color.fromRGBO(48,219,91,1),size: 60,), Text('Success',style: Theme.of(context).textTheme.displayMedium,) ], ); } else{ return Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ const Icon(Icons.dangerous_sharp,color: Colors.red,size: 60,), Text("Failure",style: Theme.of(context).textTheme.displayMedium,) ], ); } }, ), Expanded( flex: 15, child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Text("To have the service of chat-gpt.",style: Theme.of(context).textTheme.displaySmall,), Text("You can give us your Api_Key in Open-AI.",style: Theme.of(context).textTheme.displaySmall,), Text("We won't charge for this service, then you can use the service powered by Open-AI.",style: Theme.of(context).textTheme.displaySmall,), Text("Furthermore, we will use AES, RSA, SSL/TLS algorithm to encrypt your Api_Key.",style: Theme.of(context).textTheme.displaySmall,), Text("Hence, if you want to have the service, gain you Api_Key and give us.",style: Theme.of(context).textTheme.displaySmall,), ], ) ), Expanded( flex: 4, child: TextButton( onPressed: (){_launchURL();}, child: Container( padding: const EdgeInsets.symmetric(horizontal: 20,vertical: 15), decoration: BoxDecoration(border: Border.all(color: Theme.of(context).brightness==Brightness.light?LightStyle.borderColor:DarkStyle.borderColor),borderRadius: BorderRadius.circular(10)), child: Text('Gain your Api_Key',style: Theme.of(context).textTheme.displaySmall,) ) ), ), Expanded( flex: 1, child: Container() ), ], ), ), ), BlocBuilder<AccessMethodBloc,AccessMethodState?>( builder: (context,state){ if(state==null){ return Expanded( flex: 1, child:FractionallySizedBox( widthFactor: 0.5, child: ElevatedButton( onPressed: () { context.read<AccessMethodBloc>().add(AccessMethodEventApiKey(_controller.text)); }, style: Theme.of(context).elevatedButtonTheme.style, child:const Text('Done',textAlign: TextAlign.center,style: TextStyle(color: Colors.white, fontSize:23,fontFamily: 'Play',fontWeight: FontWeight.bold),), ) ) ); } else{ return Container(); } }, ) ], ) ) ), ), ); } }
0
mirrored_repositories/study_savvy_app/lib/screens
mirrored_repositories/study_savvy_app/lib/screens/article_improver/article_improver.dart
import 'dart:typed_data'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_image_compress/flutter_image_compress.dart'; import 'package:provider/provider.dart'; import 'package:study_savvy_app/blocs/article_improver/bloc_article_improver.dart'; import 'package:study_savvy_app/models/article_improver/model_article_improver.dart'; import 'package:study_savvy_app/styles/custom_style.dart'; import 'package:study_savvy_app/widgets/loading.dart'; import 'package:study_savvy_app/blocs/provider/ocr_image_provider.dart'; import 'package:study_savvy_app/utils/routes.dart'; import 'package:image/image.dart' as img_package; import 'package:path_provider/path_provider.dart'; import 'dart:io'; import 'package:wechat_assets_picker/wechat_assets_picker.dart'; class ArticleImproverPage extends StatefulWidget{ const ArticleImproverPage({Key?key}):super(key: key); @override State<ArticleImproverPage> createState()=> _ArticleImproverPage(); } class _ArticleImproverPage extends State<ArticleImproverPage>{ final _promptController= TextEditingController(); final _contentController= TextEditingController(); @override void dispose() { _promptController.dispose(); _contentController.dispose(); super.dispose(); } void _showAlertDialog(BuildContext context) { showCupertinoModalPopup( context: context, builder: (BuildContext context) { return CupertinoAlertDialog( title: Text('Warn',style: Theme.of(context).textTheme.displayMedium), content: Text("Content 內容不得為空\n至少選擇圖檔或是文字",style: Theme.of(context).textTheme.displaySmall), actions: <Widget>[ CupertinoDialogAction( isDestructiveAction: true, onPressed: (){ Navigator.pop(context); }, child: Text('confirm',style: Theme.of(context).textTheme.displaySmall), ), ], ); }, ); } @override Widget build(BuildContext context) { final ocrImageProvider = Provider.of<OCRImageProvider>(context); List<AssetEntity> images = <AssetEntity>[]; Future<void> processImages() async { ocrImageProvider.setStatus(false); ocrImageProvider.closeStatusFuture(); try{ List<img_package.Image> loadedImages = []; for (AssetEntity asset in images) { File? file = await asset.file; if(file!=null){ Uint8List? imageData = await FlutterImageCompress.compressWithFile( file.absolute.path, autoCorrectionAngle: true, ); if (imageData != null) { img_package.Image img = img_package.decodeImage(imageData)!; loadedImages.add(img_package.copyResize(img, width: asset.width)); } } } final combined = img_package.Image( width:loadedImages[0].width, height:loadedImages.fold<int>(0, (previousValue, element) => previousValue + element.height) ); int offset = 0; for (img_package.Image img in loadedImages) { for (int y = 0; y < img.height; y++) { for (int x = 0; x < img.width; x++) { img_package.Pixel pixel = img.getPixel(x, y); combined.setPixel(x, y + offset, pixel); } } offset += img.height; } final directory = await getApplicationDocumentsDirectory(); final filePath = '${directory.path}/combined.jpg'; File(filePath).writeAsBytesSync(img_package.encodeJpg(combined)); ocrImageProvider.set(File(filePath)); } catch (e){ throw Exception("Error to choose image"); } finally{ ocrImageProvider.setStatus(true); } } Future<void> loadAssets() async { List<AssetEntity>? resultList = await AssetPicker.pickAssets( context, pickerConfig: const AssetPickerConfig( maxAssets: 2, gridCount: 4, requestType: RequestType.image, keepScrollOffset: true ), ); if (!mounted) return; if (resultList != null) { setState(() { images = resultList; }); await processImages(); } } return GestureDetector( onTap: () { FocusScopeNode currentFocus = FocusScope.of(context); if (!currentFocus.hasPrimaryFocus) { currentFocus.unfocus(); } }, child: Column( children: [ Expanded( flex: 1, child: Text('Writing Improver',style: Theme.of(context).textTheme.bodyLarge,), ), BlocBuilder<ArticleBloc,ArticleState>( builder: (context,state){ if(state.status=="INIT"){ return Expanded( flex: 8, child:Container( padding: const EdgeInsets.symmetric(vertical: 5), margin: const EdgeInsets.symmetric(vertical: 10), child: SingleChildScrollView( child: Column( children:[ Container( alignment: Alignment.centerLeft, child: Text('Content',style: Theme.of(context).textTheme.bodyMedium) ), Container( padding: const EdgeInsets.all(15), margin: const EdgeInsets.symmetric(vertical: 15), height: 180, decoration: Theme.of(context).brightness == Brightness.dark ? DarkStyle.boxDecoration : LightStyle.boxDecoration, child: SingleChildScrollView( child: ocrImageProvider.status==false? const Loading() :ocrImageProvider.isNull()? TextField( controller: _contentController, maxLines: null, keyboardType: TextInputType.multiline, decoration: const InputDecoration( hintText: "可以在這寫下你的作文或使用照片", border: InputBorder.none, ), ): Stack( children: [ Image.memory(ocrImageProvider.image as Uint8List), Row( mainAxisAlignment: MainAxisAlignment.end, children: [ IconButton(onPressed: (){ocrImageProvider.clear();}, icon: const Icon(Icons.cancel_outlined,size: 30,color: Colors.red,)), ], ) ] ), ), ), Container( alignment: AlignmentDirectional.centerEnd, child: Row( mainAxisAlignment: MainAxisAlignment.end, children: [ IconButton( onPressed:loadAssets, tooltip: 'Choose come photos.', icon:const Icon(Icons.photo), iconSize: 36.0, ), IconButton( onPressed:(){ Navigator.pushNamed(context, Routes.camera); }, tooltip: 'Take a photo.', icon:const Icon(Icons.camera_alt_outlined), iconSize: 36.0, ), ], ) ), Container( alignment: Alignment.centerLeft, child: Text('Prompt',style: Theme.of(context).textTheme.bodyMedium), ), Container( padding: const EdgeInsets.all(15), margin: const EdgeInsets.symmetric(vertical: 15), height: 150, decoration: Theme.of(context).brightness == Brightness.dark ? DarkStyle.boxDecoration : LightStyle.boxDecoration, child: SingleChildScrollView( child: TextField( controller: _promptController, maxLines: null, keyboardType: TextInputType.multiline, decoration: const InputDecoration( hintText: "可以寫下作文主題以及你認為需加強部分\n(選填)", hintMaxLines: 3, border: InputBorder.none, ), ), ), ), ] ), ), ), ); } else if(state.status=="PENDING"){ return const Expanded( flex:9, child: Loading() ); } else if (state.status=='SUCCESS'){ return const Expanded( flex:8, child: Center( child:Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Icon(Icons.check_circle_outline,size:40), Text("Success to upload") ], ) ), ); } else{ return const Expanded( flex:8, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Center( child:Icon(Icons.warning_rounded,size:40,color: Colors.red,) ), Text("Fail to upload") ], ) ); } }), BlocBuilder<ArticleBloc,ArticleState>( builder: (context,state){ if(state.status=="INIT"){ return Expanded( flex: 1, child:FractionallySizedBox( widthFactor: 0.5, child: ElevatedButton( onPressed: () { if(ocrImageProvider.file==null){ if(_contentController.text==""){ _showAlertDialog(context); } else{ context.read<ArticleBloc>().add(ArticleEventText(ArticleText(_contentController.text,_promptController.text))); } } else{ context.read<ArticleBloc>().add(ArticleEventGraph(ArticleImage(ocrImageProvider.file,_promptController.text))); } }, style: Theme.of(context).elevatedButtonTheme.style, child:const Text('Done',textAlign: TextAlign.center,style: TextStyle(color: Colors.white, fontSize:23,fontFamily: 'Play',fontWeight: FontWeight.bold),), ) ) ); } else if(state.status=="PENDING"){ return Container(); } else{ return Expanded( flex: 1, child:FractionallySizedBox( widthFactor: 0.5, child: ElevatedButton( onPressed: () { ocrImageProvider.clear(); _promptController.text=""; _contentController.text=""; context.read<ArticleBloc>().add(ArticleEventRefresh()); }, style: Theme.of(context).elevatedButtonTheme.style, child:const Text('Reset',textAlign: TextAlign.center,style: TextStyle(color: Colors.white, fontSize:23,fontFamily: 'Play',fontWeight: FontWeight.bold),), ) ) ); } } ), ], ), ); } }
0
mirrored_repositories/study_savvy_app/lib/screens
mirrored_repositories/study_savvy_app/lib/screens/article_improver/camera.dart
import 'dart:io'; import 'dart:typed_data'; import 'package:flutter/material.dart'; import 'package:adv_camera/adv_camera.dart'; import 'package:provider/provider.dart'; import 'package:study_savvy_app/blocs/provider/ocr_image_provider.dart'; class CameraPage extends StatefulWidget { const CameraPage({super.key}); @override State<CameraPage> createState() => _CameraPageState(); } class _CameraPageState extends State<CameraPage> { late AdvCameraController _controller; FlashType flashType = FlashType.auto; @override void dispose() { super.dispose(); } @override Widget build(BuildContext context) { final ocrImageProvider = Provider.of<OCRImageProvider>(context); return SizedBox( width: double.infinity, height: double.infinity, child: Column( children: [ Expanded( flex:9, child: AdvCamera( onCameraCreated: _onCameraCreated, onImageCaptured: (path) async { await ocrImageProvider.set(File(path)).then((value) => { Navigator.pop(context) }); // Navigator.push( // context, // MaterialPageRoute( // builder: (context) => DisplayPictureScreen(imageBytes: imageData), // ), // ); }, ), ), Expanded( flex:1, child: Container( color: Colors.white, child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ TextButton( style: ButtonStyle( overlayColor: MaterialStateProperty.resolveWith<Color>( (Set<MaterialState> states) { if (states.contains(MaterialState.pressed)) { return Theme.of(context).hintColor; } return Colors.transparent; }, ), ), onPressed: _toggleFlash, child: flashIcon(), ), TextButton( style: ButtonStyle( overlayColor: MaterialStateProperty.resolveWith<Color>( (Set<MaterialState> states) { if (states.contains(MaterialState.pressed)) { return Theme.of(context).hintColor; } return Colors.transparent; }, ), ), child: const Icon(Icons.circle,size: 40,color: Colors.black), onPressed: () { _controller.captureImage(); }, ), ], ), ) ) ], ), ); } void _onCameraCreated(AdvCameraController controller) { _controller = controller; } _toggleFlash() { setState(() { switch (flashType) { case FlashType.auto: flashType = FlashType.on; break; case FlashType.on: flashType = FlashType.off; break; case FlashType.off: flashType = FlashType.auto; break; default: flashType = FlashType.auto; } _controller.setFlashType(flashType); }); } Icon flashIcon() { switch (flashType) { case FlashType.auto: return const Icon(Icons.flash_auto,size: 40,color: Colors.black,); case FlashType.on: return const Icon(Icons.flash_on,size: 40,color: Colors.black,); case FlashType.off: return const Icon(Icons.flash_off,size: 40,color: Colors.black,); default: return const Icon(Icons.flash_auto,size: 40,color: Colors.black,); } } } class DisplayPictureScreen extends StatelessWidget { final Uint8List imageBytes; const DisplayPictureScreen({Key? key, required this.imageBytes}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Display the Picture')), body: Center( child: Image.memory(imageBytes), ), ); } }
0
mirrored_repositories/study_savvy_app/lib/screens
mirrored_repositories/study_savvy_app/lib/screens/files/specific_file.dart
import 'dart:typed_data'; import 'package:audioplayers/audioplayers.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:study_savvy_app/blocs/files/bloc_specific_file.dart'; import 'package:study_savvy_app/models/files/model_files.dart'; import 'package:study_savvy_app/styles/custom_style.dart'; import 'package:study_savvy_app/widgets/loading.dart'; import 'package:study_savvy_app/widgets/failure.dart'; import 'package:study_savvy_app/widgets/success.dart'; class SpecificFilePage extends StatefulWidget{ const SpecificFilePage({Key?key}):super(key: key); @override State<SpecificFilePage> createState()=> _SpecificFilePage(); } class _SpecificFilePage extends State<SpecificFilePage> { late TextEditingController _promptController; late TextEditingController _contentController; late FileBloc bloc; bool init=true; bool? playState=false; AudioPlayer audioPlayer = AudioPlayer(); @override void initState() { super.initState(); _contentController= TextEditingController(); _promptController= TextEditingController(); bloc=BlocProvider.of<FileBloc>(context); context.read<FileBloc>().stream.listen((FileState state) { if(state.status=="SUCCESS"){ if(mounted){ _promptController.text=state.file!.prompt; _contentController.text=state.file!.content; } } }); } @override void dispose() { audioPlayer.stop(); audioPlayer.dispose(); bloc.add(FileEventClear()); _contentController.dispose(); _promptController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( body:GestureDetector( onTap: () { FocusScopeNode currentFocus = FocusScope.of(context); if (!currentFocus.hasPrimaryFocus) { currentFocus.unfocus(); } }, child: SafeArea( child:Padding( padding: const EdgeInsets.symmetric(vertical: 10,horizontal: 20), child: Column( children: [ Expanded( flex: 1, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Expanded(flex:1,child: IconButton(onPressed: (){Navigator.pop(context);}, icon: const Icon(Icons.arrow_back_ios_new),alignment: Alignment.bottomLeft,)), Expanded(flex:5,child: Text('SpecificFile',style: Theme.of(context).textTheme.bodyLarge,textAlign: TextAlign.center,),), Expanded(flex:1,child: Container()), ], ), ), Expanded( flex: 8, child:SingleChildScrollView( child: Container( alignment: Alignment.topLeft, child: BlocBuilder<FileBloc,FileState>( builder: (context,state){ if(state.status=="INIT" || state.status=="PENDING"){ return const Loading(); } else if(state.status=="SUCCESS"){ return Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Container( margin: const EdgeInsets.symmetric(vertical: 10), width: double.infinity, padding: const EdgeInsets.symmetric(horizontal: 10,vertical: 15), decoration: BoxDecoration(borderRadius: const BorderRadius.all(Radius.circular(10)),border: Border.all(color: Theme.of(context).brightness==Brightness.light?LightStyle.borderColor:DarkStyle.borderColor,)), child: Column( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ Text("Introduce",style: Theme.of(context).textTheme.headlineLarge,), const Divider(), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text("Summarize",style: Theme.of(context).textTheme.headlineMedium,), Text("代表AI做出的重點或評分",style: Theme.of(context).textTheme.headlineSmall,), ], ), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text("Details",style: Theme.of(context).textTheme.headlineMedium,), Text("代表AI對於每段細節做的評論",style: Theme.of(context).textTheme.headlineSmall,), ], ), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text("Prompt",style: Theme.of(context).textTheme.headlineMedium,), Text("代表你個人所下的提示詞(可做更動)",style: Theme.of(context).textTheme.headlineSmall,), ], ), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text("Content",style: Theme.of(context).textTheme.headlineMedium), Text("代表文章內容或語音內容(可做更動)",style: Theme.of(context).textTheme.headlineSmall), ], ), ], ) ), Container( margin: const EdgeInsets.symmetric(vertical: 10), width: double.infinity, padding: const EdgeInsets.symmetric(horizontal: 10), decoration: BoxDecoration(borderRadius: const BorderRadius.all(Radius.circular(10)),border: Border.all(color: Theme.of(context).brightness==Brightness.light?LightStyle.borderColor:DarkStyle.borderColor,)), child: Column( children: [ ExpansionTile( title: Text('Summarize',style: Theme.of(context).textTheme.labelMedium,), iconColor: Theme.of(context).brightness==Brightness.light?Colors.black:Colors.white, children: [ Container( margin: const EdgeInsets.symmetric(vertical: 15), decoration: BoxDecoration(borderRadius: const BorderRadius.all(Radius.circular(10)),border: Border.all(color: Theme.of(context).brightness==Brightness.light?LightStyle.borderColor:DarkStyle.borderColor,)), padding: const EdgeInsets.symmetric(vertical:10,horizontal: 10), alignment: Alignment.topLeft, child: Text(state.file!.summarize,style: Theme.of(context).textTheme.headlineSmall,maxLines: null,), ) ], ), ], ), ), Container( margin: const EdgeInsets.symmetric(vertical: 10), width: double.infinity, padding: const EdgeInsets.symmetric(horizontal: 10), decoration: BoxDecoration(borderRadius: const BorderRadius.all(Radius.circular(10)),border: Border.all(color: Theme.of(context).brightness==Brightness.light?LightStyle.borderColor:DarkStyle.borderColor,)), child: Column( children:[ ExpansionTile( title: Text('Details',style: Theme.of(context).textTheme.labelMedium,), iconColor: Theme.of(context).brightness==Brightness.light?Colors.black:Colors.white, children: [ Column( children: state.file!.details.map((item){ return Container( margin: const EdgeInsets.symmetric(vertical: 5), decoration: BoxDecoration(borderRadius: const BorderRadius.all(Radius.circular(10)),border: Border.all(color: Theme.of(context).brightness==Brightness.light?LightStyle.borderColor:DarkStyle.borderColor,)), padding: const EdgeInsets.symmetric(vertical: 10,horizontal: 10), alignment: Alignment.topLeft, child: Text(item,style: Theme.of(context).textTheme.headlineSmall,maxLines: null,), ); }).toList(), ) ], ), ], ), ), Container( margin: const EdgeInsets.symmetric(vertical: 10), width: double.infinity, padding: const EdgeInsets.symmetric(horizontal: 10), decoration: BoxDecoration(borderRadius: const BorderRadius.all(Radius.circular(10)),border: Border.all(color: Theme.of(context).brightness==Brightness.light?LightStyle.borderColor:DarkStyle.borderColor,)), child: Column( children: [ ExpansionTile( title: Text('Prompt',style: Theme.of(context).textTheme.labelMedium,), iconColor: Theme.of(context).brightness==Brightness.light?Colors.black:Colors.white, children: [ Container( margin: const EdgeInsets.symmetric(vertical: 15), decoration: BoxDecoration(borderRadius: const BorderRadius.all(Radius.circular(10)),border: Border.all(color: Theme.of(context).brightness==Brightness.light?LightStyle.borderColor:DarkStyle.borderColor,)), padding: const EdgeInsets.symmetric(horizontal: 10), alignment: Alignment.topLeft, child: TextField( controller: _promptController, keyboardType: TextInputType.multiline, style: Theme.of(context).textTheme.headlineSmall, decoration: const InputDecoration( border: InputBorder.none, ), maxLines: null, ), ) ], ), ], ), ), Container( margin: const EdgeInsets.symmetric(vertical: 10), width: double.infinity, padding: const EdgeInsets.symmetric(horizontal: 10), decoration: BoxDecoration(borderRadius: const BorderRadius.all(Radius.circular(10)),border: Border.all(color: Theme.of(context).brightness==Brightness.light?LightStyle.borderColor:DarkStyle.borderColor,)), child: Column( children: [ ExpansionTile( title: Text('Content',style: Theme.of(context).textTheme.labelMedium,), iconColor: Theme.of(context).brightness==Brightness.light?Colors.black:Colors.white, children: [ Container( margin: const EdgeInsets.symmetric(vertical: 15), decoration: BoxDecoration(borderRadius: const BorderRadius.all(Radius.circular(10)),border: Border.all(color: Theme.of(context).brightness==Brightness.light?LightStyle.borderColor:DarkStyle.borderColor,)), padding: const EdgeInsets.symmetric(horizontal: 10), alignment: Alignment.topLeft, child: TextField( controller: _contentController, decoration: const InputDecoration( border: InputBorder.none, ), style: Theme.of(context).textTheme.headlineSmall, maxLines: null,), ) ], ), ], ), ), if (state.type=="OCR") Container( margin: const EdgeInsets.symmetric(vertical: 10), width: double.infinity, padding: const EdgeInsets.symmetric(horizontal: 10), decoration: BoxDecoration(borderRadius: const BorderRadius.all(Radius.circular(10)),border: Border.all(color: Theme.of(context).brightness==Brightness.light?LightStyle.borderColor:DarkStyle.borderColor,)), child: Column( children: [ ExpansionTile( title: Text('Original Photo',style: Theme.of(context).textTheme.labelMedium,), iconColor: Theme.of(context).brightness==Brightness.light?Colors.black:Colors.white, children: [ Container( margin: const EdgeInsets.symmetric(vertical: 15), padding: const EdgeInsets.symmetric(horizontal: 10), child: state.media==null?const Failure(error: "No Image Source"):Image.memory(state.media as Uint8List) ) ], ), ], ), ) else Container( margin: const EdgeInsets.symmetric(vertical: 10), width: double.infinity, padding: const EdgeInsets.symmetric(horizontal: 10), decoration: BoxDecoration(borderRadius: const BorderRadius.all(Radius.circular(10)),border: Border.all(color: Theme.of(context).brightness==Brightness.light?LightStyle.borderColor:DarkStyle.borderColor,)), child: Column( children: [ ExpansionTile( title: Text('Original Audio',style: Theme.of(context).textTheme.labelMedium,), iconColor: Theme.of(context).brightness==Brightness.light?Colors.black:Colors.white, children: [ Container( margin: const EdgeInsets.symmetric(vertical: 15), padding: const EdgeInsets.symmetric(horizontal: 10), child: TextButton( onPressed: () { if(init){ try{ audioPlayer.setSourceBytes(state.media!); audioPlayer.play(audioPlayer.source!); setState(() { init=false; playState=true; }); } catch (e){ setState(() { playState=null; }); } } else{ if(playState==true){ audioPlayer.pause(); setState(() { playState=false; }); } else if(playState==false){ audioPlayer.resume(); setState(() { playState=true; }); } } }, child: playState==null?const Failure(error: "Error to play"):playState==true?Icon(Icons.pause_circle_filled_outlined,color: Theme.of(context).hintColor,size: 50,):Icon(Icons.play_circle_fill_rounded,color: Theme.of(context).hintColor,size: 50,), ) ) ], ), ], ), ) ], ); } else if(state.status=="FAILURE"){ return Failure(error: state.message!,); } else if(state.status=="SUCCESS_OTHER"){ return Success(message: state.message!,); } else{ return Container(); } }, ) ), ) ), BlocBuilder<FileBloc,FileState>( builder: (context,state){ if(state.status=="SUCCESS"){ return Expanded( flex: 1, child:Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ ElevatedButton( onPressed: () async { EditFile file=EditFile(state.id!,_promptController.text.toString(),_contentController.text.toString()); if(state.type=="OCR"){ context.read<FileBloc>().add(FileEventEditOCR(file)); } else{ context.read<FileBloc>().add(FileEventEditASR(file)); } }, style: Theme.of(context).elevatedButtonTheme.style, child:const Text("ReGenerate",textAlign: TextAlign.center,style: TextStyle(color: Colors.white, fontSize:23,fontFamily: 'Play',fontWeight: FontWeight.bold),), ), ElevatedButton( onPressed: () async { context.read<FileBloc>().add(FileEventDelete(state.id!)); }, style: Theme.of(context).elevatedButtonTheme.style, child:const Text("Delete",textAlign: TextAlign.center,style: TextStyle(color: Colors.redAccent, fontSize:23,fontFamily: 'Play',fontWeight: FontWeight.bold),), ) ], ) ); } else{ return Expanded( flex:1, child: Container() ); } }, ), ], ) ) ), ), ); } }
0
mirrored_repositories/study_savvy_app/lib/screens
mirrored_repositories/study_savvy_app/lib/screens/files/files.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:liquid_pull_to_refresh/liquid_pull_to_refresh.dart'; import 'package:study_savvy_app/blocs/files/bloc_files.dart'; import 'package:study_savvy_app/blocs/files/bloc_specific_file.dart'; import 'package:study_savvy_app/utils/routes.dart'; import 'package:study_savvy_app/widgets/failure.dart'; import 'package:study_savvy_app/widgets/loading.dart'; import 'package:study_savvy_app/widgets/success.dart'; import 'package:study_savvy_app/styles/custom_style.dart'; class FilesPage extends StatefulWidget{ const FilesPage({Key?key}):super(key: key); @override State<FilesPage> createState()=> _FilesPage(); } class _FilesPage extends State<FilesPage> { final _scrollController = ScrollController(); @override void initState() { super.initState(); context.read<FilesBloc>().add(FilesEventInit()); _scrollController.addListener(() { FilesState? state=context.read<FilesBloc>().state; if (_scrollController.position.pixels >= _scrollController.position.maxScrollExtent*0.9) { context.read<FilesBloc>().add(FilesEventLoadMore(state.files)); } }); } Future<void> _refresh() async { context.read<FilesBloc>().add(FilesEventRefresh()); return await Future.delayed(const Duration(seconds: 2)); } @override Widget build(BuildContext context) { return Column( children: [ Expanded( flex: 1, child: Container( alignment: Alignment.center, child: Text('Files',style: Theme.of(context).textTheme.bodyLarge), ), ), Expanded( flex: 9, child: BlocBuilder<FilesBloc,FilesState>( builder: (context,state){ if(state.status=="INIT"){ return const Loading(); } else if (state.status=="SUCCESS" || state.status=="PENDING"){ return LiquidPullToRefresh( animSpeedFactor:1.5, color: Theme.of(context).hintColor, onRefresh: _refresh, showChildOpacityTransition: false, child: ListView.builder( key: const PageStorageKey<String>('FilesKey'), physics: const BouncingScrollPhysics(), controller: _scrollController, itemCount: state.status=="PENDING"?state.files.files.length+1:state.files.files.length, itemBuilder: (context, index) { if(index==state.files.files.length){ return const Loading(); } return TextButton( onPressed: (){ if ((state.files.files[index]).status=='SUCCESS'){ Navigator.pushNamed(context, Routes.specificFile); if((state.files.files[index]).type=="OCR"){ context.read<FileBloc>().add(FileEventOCR((state.files.files[index]).id)); } else if((state.files.files[index]).type=="ASR"){ context.read<FileBloc>().add(FileEventASR((state.files.files[index]).id)); } } else if((state.files.files[index]).status=='FAILURE'){ showCupertinoModalPopup( context: context, builder: (BuildContext context) { return BlocBuilder<FileBloc,FileState>( builder: (context,stateFile){ if(stateFile.status=="INIT"){ return CupertinoAlertDialog( title: const Text('刪除錯誤檔案'), content: const Text('這份檔案執行失敗\n目前無法開啟,是否刪除?'), actions: <Widget>[ CupertinoDialogAction( isDestructiveAction: false, child: const Text('取消'), onPressed: () { Navigator.of(context).pop(); }, ), CupertinoDialogAction( isDestructiveAction: true, child: const Text('刪除'), onPressed: () { context.read<FileBloc>().add(FileEventDelete((state.files.files[index]).id)); }, ), ], ); } else if(stateFile.status=="PENDING"){ return const CupertinoAlertDialog( title: Text('刪除錯誤檔案'), content: Loading() ); } else if(stateFile.status=="FAILURE"){ return CupertinoAlertDialog( title: const Text('刪除錯誤檔案'), content: Failure(error: stateFile.message!), actions: [ CupertinoDialogAction( child: const Text('確定'), onPressed: () { Navigator.of(context).pop(); }, ), ] ); } else if(stateFile.status=='SUCCESS_OTHER'){ return CupertinoAlertDialog( title: const Text('刪除錯誤檔案'), content: Success(message: stateFile.message!), actions: [ CupertinoDialogAction( child: const Text('確定'), onPressed: () { Navigator.of(context).pop(); }, ), ] ); } else{ return Container(); } }); }, ).then((value) => { context.read<FileBloc>().add(FileEventClear()) }); } else{ showDialog( context: context, builder: (BuildContext context) { return CupertinoAlertDialog( title: const Text('錯誤'), content: const Text('這份檔案正在執行\n目前無法開啟'), actions: <Widget>[ TextButton( child: const Text('确定'), onPressed: () { Navigator.of(context).pop(); }, ), ], ); }, ); } }, style: ButtonStyle( overlayColor: MaterialStateProperty.resolveWith<Color>( (Set<MaterialState> states) { if (states.contains(MaterialState.pressed)) { return Theme.of(context).hintColor; } return Colors.transparent; }, ), ), child: Container( padding: const EdgeInsets.symmetric(vertical: 10,horizontal: 15), height: 100, decoration: BoxDecoration(borderRadius: const BorderRadius.all(Radius.circular(10)),border: Border.all(color: Theme.of(context).brightness==Brightness.light?LightStyle.borderColor:DarkStyle.borderColor)), child: Row( children: [ Expanded( flex:2, child: Column( mainAxisAlignment: MainAxisAlignment.spaceAround, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text('Title',style: Theme.of(context).textTheme.bodySmall,), Text('Type',style: Theme.of(context).textTheme.bodySmall,), Text('Date_Time',style: Theme.of(context).textTheme.bodySmall,), ], ), ), Expanded( flex:3, child: Column( mainAxisAlignment: MainAxisAlignment.spaceAround, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text('',style: Theme.of(context).textTheme.bodySmall,), Text((state.files.files[index]).type,style: Theme.of(context).textTheme.titleSmall,), Text((state.files.files[index]).time.toString(),style: Theme.of(context).textTheme.titleSmall,), ], ), ), Expanded( flex: 1, child: Container( padding: const EdgeInsets.only(left: 5), decoration: BoxDecoration(border: Border(left: BorderSide(color: Theme.of(context).brightness==Brightness.light?LightStyle.borderColor:DarkStyle.borderColor))), child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: CrossAxisAlignment.center, children: (state.files.files[index]).status=='SUCCESS'? [const Icon(Icons.check_circle_outline,color: Color.fromRGBO(48,219,91,1),size: 45,),Text('OK',style: Theme.of(context).textTheme.bodySmall,textAlign: TextAlign.center,)] : (state.files.files[index]).status=='FAILURE'? [const Icon(Icons.dangerous_sharp,color: Colors.red,size: 45,),Text('Fail',style: Theme.of(context).textTheme.bodySmall,textAlign: TextAlign.center,)]: [Icon(Icons.query_stats_rounded,color: Colors.yellow[900],size: 45,),Text('Wait',style: Theme.of(context).textTheme.bodySmall,textAlign: TextAlign.center,)], ), ), ) ], ), )); } ), ); } else{ return Failure(error: state.error!); } }, ), ), ] ); } @override void dispose() { _scrollController.dispose(); super.dispose(); } }
0
mirrored_repositories/study_savvy_app
mirrored_repositories/study_savvy_app/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility in the flutter_test package. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:study_savvy_app/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(const MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/study_savvy_app/test
mirrored_repositories/study_savvy_app/test/function/jwt_test.mocks.dart
// Mocks generated by Mockito 5.4.2 from annotations // in study_savvy_app/test/function/jwt_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i3; import 'package:flutter_secure_storage/flutter_secure_storage.dart' as _i2; 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 _FakeIOSOptions_0 extends _i1.SmartFake implements _i2.IOSOptions { _FakeIOSOptions_0( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeAndroidOptions_1 extends _i1.SmartFake implements _i2.AndroidOptions { _FakeAndroidOptions_1( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeLinuxOptions_2 extends _i1.SmartFake implements _i2.LinuxOptions { _FakeLinuxOptions_2( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeWindowsOptions_3 extends _i1.SmartFake implements _i2.WindowsOptions { _FakeWindowsOptions_3( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeWebOptions_4 extends _i1.SmartFake implements _i2.WebOptions { _FakeWebOptions_4( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeMacOsOptions_5 extends _i1.SmartFake implements _i2.MacOsOptions { _FakeMacOsOptions_5( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } /// A class which mocks [FlutterSecureStorage]. /// /// See the documentation for Mockito's code generation for more information. class MockFlutterSecureStorage extends _i1.Mock implements _i2.FlutterSecureStorage { MockFlutterSecureStorage() { _i1.throwOnMissingStub(this); } @override _i2.IOSOptions get iOptions => (super.noSuchMethod( Invocation.getter(#iOptions), returnValue: _FakeIOSOptions_0( this, Invocation.getter(#iOptions), ), ) as _i2.IOSOptions); @override _i2.AndroidOptions get aOptions => (super.noSuchMethod( Invocation.getter(#aOptions), returnValue: _FakeAndroidOptions_1( this, Invocation.getter(#aOptions), ), ) as _i2.AndroidOptions); @override _i2.LinuxOptions get lOptions => (super.noSuchMethod( Invocation.getter(#lOptions), returnValue: _FakeLinuxOptions_2( this, Invocation.getter(#lOptions), ), ) as _i2.LinuxOptions); @override _i2.WindowsOptions get wOptions => (super.noSuchMethod( Invocation.getter(#wOptions), returnValue: _FakeWindowsOptions_3( this, Invocation.getter(#wOptions), ), ) as _i2.WindowsOptions); @override _i2.WebOptions get webOptions => (super.noSuchMethod( Invocation.getter(#webOptions), returnValue: _FakeWebOptions_4( this, Invocation.getter(#webOptions), ), ) as _i2.WebOptions); @override _i2.MacOsOptions get mOptions => (super.noSuchMethod( Invocation.getter(#mOptions), returnValue: _FakeMacOsOptions_5( this, Invocation.getter(#mOptions), ), ) as _i2.MacOsOptions); @override _i3.Future<void> write({ required String? key, required String? value, _i2.IOSOptions? iOptions, _i2.AndroidOptions? aOptions, _i2.LinuxOptions? lOptions, _i2.WebOptions? webOptions, _i2.MacOsOptions? mOptions, _i2.WindowsOptions? wOptions, }) => (super.noSuchMethod( Invocation.method( #write, [], { #key: key, #value: value, #iOptions: iOptions, #aOptions: aOptions, #lOptions: lOptions, #webOptions: webOptions, #mOptions: mOptions, #wOptions: wOptions, }, ), returnValue: _i3.Future<void>.value(), returnValueForMissingStub: _i3.Future<void>.value(), ) as _i3.Future<void>); @override _i3.Future<String?> read({ required String? key, _i2.IOSOptions? iOptions, _i2.AndroidOptions? aOptions, _i2.LinuxOptions? lOptions, _i2.WebOptions? webOptions, _i2.MacOsOptions? mOptions, _i2.WindowsOptions? wOptions, }) => (super.noSuchMethod( Invocation.method( #read, [], { #key: key, #iOptions: iOptions, #aOptions: aOptions, #lOptions: lOptions, #webOptions: webOptions, #mOptions: mOptions, #wOptions: wOptions, }, ), returnValue: _i3.Future<String?>.value(), ) as _i3.Future<String?>); @override _i3.Future<bool> containsKey({ required String? key, _i2.IOSOptions? iOptions, _i2.AndroidOptions? aOptions, _i2.LinuxOptions? lOptions, _i2.WebOptions? webOptions, _i2.MacOsOptions? mOptions, _i2.WindowsOptions? wOptions, }) => (super.noSuchMethod( Invocation.method( #containsKey, [], { #key: key, #iOptions: iOptions, #aOptions: aOptions, #lOptions: lOptions, #webOptions: webOptions, #mOptions: mOptions, #wOptions: wOptions, }, ), returnValue: _i3.Future<bool>.value(false), ) as _i3.Future<bool>); @override _i3.Future<void> delete({ required String? key, _i2.IOSOptions? iOptions, _i2.AndroidOptions? aOptions, _i2.LinuxOptions? lOptions, _i2.WebOptions? webOptions, _i2.MacOsOptions? mOptions, _i2.WindowsOptions? wOptions, }) => (super.noSuchMethod( Invocation.method( #delete, [], { #key: key, #iOptions: iOptions, #aOptions: aOptions, #lOptions: lOptions, #webOptions: webOptions, #mOptions: mOptions, #wOptions: wOptions, }, ), returnValue: _i3.Future<void>.value(), returnValueForMissingStub: _i3.Future<void>.value(), ) as _i3.Future<void>); @override _i3.Future<Map<String, String>> readAll({ _i2.IOSOptions? iOptions, _i2.AndroidOptions? aOptions, _i2.LinuxOptions? lOptions, _i2.WebOptions? webOptions, _i2.MacOsOptions? mOptions, _i2.WindowsOptions? wOptions, }) => (super.noSuchMethod( Invocation.method( #readAll, [], { #iOptions: iOptions, #aOptions: aOptions, #lOptions: lOptions, #webOptions: webOptions, #mOptions: mOptions, #wOptions: wOptions, }, ), returnValue: _i3.Future<Map<String, String>>.value(<String, String>{}), ) as _i3.Future<Map<String, String>>); @override _i3.Future<void> deleteAll({ _i2.IOSOptions? iOptions, _i2.AndroidOptions? aOptions, _i2.LinuxOptions? lOptions, _i2.WebOptions? webOptions, _i2.MacOsOptions? mOptions, _i2.WindowsOptions? wOptions, }) => (super.noSuchMethod( Invocation.method( #deleteAll, [], { #iOptions: iOptions, #aOptions: aOptions, #lOptions: lOptions, #webOptions: webOptions, #mOptions: mOptions, #wOptions: wOptions, }, ), returnValue: _i3.Future<void>.value(), returnValueForMissingStub: _i3.Future<void>.value(), ) as _i3.Future<void>); }
0
mirrored_repositories/study_savvy_app/test
mirrored_repositories/study_savvy_app/test/function/jwt_test.dart
import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'package:study_savvy_app/services/utils/jwt_storage.dart'; import 'jwt_test.mocks.dart'; @GenerateMocks([FlutterSecureStorage]) void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('JwtService', () { test('JwtService saveJwt test', () async { MockFlutterSecureStorage storage=MockFlutterSecureStorage(); when(storage.write(key: anyNamed('key'), value: anyNamed('value'))).thenAnswer((_) => Future.value()); JwtService jwtService=JwtService(storage: storage); await jwtService.saveJwt('test_jwt'); verify(storage.write(key: 'jwt', value: 'test_jwt')).called(1); }); test('JwtService getJwt test', () async { MockFlutterSecureStorage storage=MockFlutterSecureStorage(); when(storage.read(key: anyNamed('key'))).thenAnswer((_) => Future.value()); JwtService jwtService=JwtService(storage: storage); await jwtService.getJwt(); verify(storage.read(key: 'jwt')).called(1); }); test('JwtService deleteJwt test', () async { MockFlutterSecureStorage storage=MockFlutterSecureStorage(); when(storage.delete(key: anyNamed('key'))).thenAnswer((_) => Future.value()); JwtService jwtService=JwtService(storage: storage); await jwtService.deleteJwt(); verify(storage.delete(key: 'jwt')).called(1); }); test('JwtService hasJwt returns true when jwt exists', () async { final storage = MockFlutterSecureStorage(); when(storage.containsKey(key: anyNamed('key'))).thenAnswer((_) => Future.value(true)); final jwtService = JwtService(storage: storage); bool? result = await jwtService.hasJwt(); verify(storage.containsKey(key: 'jwt')).called(1); expect(result, isTrue); }); test('JwtService hasJwt returns false when jwt does not exist', () async { final storage = MockFlutterSecureStorage(); when(storage.containsKey(key: anyNamed('key'))).thenAnswer((_) => Future.value(false)); final jwtService = JwtService(storage: storage); bool? result = await jwtService.hasJwt(); verify(storage.containsKey(key: 'jwt')).called(1); expect(result, isFalse); }); }); }
0
mirrored_repositories/study_savvy_app/test
mirrored_repositories/study_savvy_app/test/bloc/bloc_access_methods_test.dart
import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'package:study_savvy_app/blocs/profile/bloc_access_methods.dart'; import 'package:study_savvy_app/services/profile/api_profile.dart'; import 'package:study_savvy_app/utils/exception.dart'; import 'bloc_access_methods_test.mocks.dart'; @GenerateMocks([ProfileService]) void main() { group("AccessMethodBloc", () { test('emit null when AccessMethodEventAccessToken build', () async { final AccessMethodBloc accessMethodBloc=AccessMethodBloc(); expect(accessMethodBloc.state, null); }); }); group('AccessMethodBloc ApiKey Event', () { test('emits [PENDING, SUCCESS] when AccessMethodEventApiKey succeeded', () async { final MockProfileService mockProfileService=MockProfileService(); final AccessMethodBloc accessMethodBloc=AccessMethodBloc(apiService: mockProfileService); when(mockProfileService.setApiKey(any)).thenAnswer((_) async => ''); final expectedStates = [ AccessMethodState("PENDING", null).toString(), AccessMethodState("SUCCESS", null).toString(), ]; accessMethodBloc.add(AccessMethodEventApiKey('apiKey')); await expectLater( accessMethodBloc.stream.map((event) => event.toString()), emitsInOrder(expectedStates), ); await untilCalled(mockProfileService.setApiKey(any)); verify(mockProfileService.setApiKey(any)).called(1); }); test('emits [PENDING, FAILURE-Client] when AccessMethodEventApiKey fail', () async { final MockProfileService mockProfileService=MockProfileService(); final AccessMethodBloc accessMethodBloc=AccessMethodBloc(apiService: mockProfileService); when(mockProfileService.setApiKey(any)).thenThrow(ClientException("Client's error")); final expectedStates = [ AccessMethodState("PENDING", null).toString(), AccessMethodState("FAILURE", "CLIENT").toString(), ]; accessMethodBloc.add(AccessMethodEventApiKey('apiKey')); await expectLater( accessMethodBloc.stream.map((event) => event.toString()), emitsInOrder(expectedStates), ); await untilCalled(mockProfileService.setApiKey(any)); verify(mockProfileService.setApiKey(any)).called(1); }); test('emits [PENDING, FAILURE-Exist] when AccessMethodEventApiKey fail', () async { final MockProfileService mockProfileService=MockProfileService(); final AccessMethodBloc accessMethodBloc=AccessMethodBloc(apiService: mockProfileService); when(mockProfileService.setApiKey(any)).thenThrow(ExistException("Source not exist")); final expectedStates = [ AccessMethodState("PENDING", null).toString(), AccessMethodState("FAILURE", "EXIST").toString(), ]; accessMethodBloc.add(AccessMethodEventApiKey('apiKey')); await expectLater( accessMethodBloc.stream.map((event) => event.toString()), emitsInOrder(expectedStates), ); await untilCalled(mockProfileService.setApiKey(any)); verify(mockProfileService.setApiKey(any)).called(1); }); test('emits [PENDING, FAILURE-Auth] when AccessMethodEventApiKey fail', () async { final MockProfileService mockProfileService=MockProfileService(); final AccessMethodBloc accessMethodBloc=AccessMethodBloc(apiService: mockProfileService); when(mockProfileService.setApiKey(any)).thenThrow(AuthException("JWT invalid")); final expectedStates = [ AccessMethodState("PENDING", null).toString(), AccessMethodState("FAILURE", "AUTH").toString(), ]; accessMethodBloc.add(AccessMethodEventApiKey('apiKey')); await expectLater( accessMethodBloc.stream.map((event) => event.toString()), emitsInOrder(expectedStates), ); await untilCalled(mockProfileService.setApiKey(any)); verify(mockProfileService.setApiKey(any)).called(1); }); test('emits [PENDING, FAILURE-Server] when AccessMethodEventApiKey fail', () async { final MockProfileService mockProfileService=MockProfileService(); final AccessMethodBloc accessMethodBloc=AccessMethodBloc(apiService: mockProfileService); when(mockProfileService.setApiKey(any)).thenThrow(ServerException("Server's error")); final expectedStates = [ AccessMethodState("PENDING", null).toString(), AccessMethodState("FAILURE", "SERVER").toString(), ]; accessMethodBloc.add(AccessMethodEventApiKey('apiKey')); await expectLater( accessMethodBloc.stream.map((event) => event.toString()), emitsInOrder(expectedStates), ); await untilCalled(mockProfileService.setApiKey(any)); verify(mockProfileService.setApiKey(any)).called(1); }); test('emits [PENDING, FAILURE-Unknown] when AccessMethodEventApiKey fail', () async { final MockProfileService mockProfileService=MockProfileService(); final AccessMethodBloc accessMethodBloc=AccessMethodBloc(apiService: mockProfileService); when(mockProfileService.setApiKey(any)).thenThrow(Exception("Failed in unknown reason")); final expectedStates = [ AccessMethodState("PENDING", null).toString(), AccessMethodState("FAILURE", "UNKNOWN").toString(), ]; accessMethodBloc.add(AccessMethodEventApiKey('apiKey')); await expectLater( accessMethodBloc.stream.map((event) => event.toString()), emitsInOrder(expectedStates), ); await untilCalled(mockProfileService.setApiKey(any)); verify(mockProfileService.setApiKey(any)).called(1); }); }); group('AccessMethodBloc AccessToken Event', () { test('emits [PENDING, SUCCESS] when AccessMethodEventAccessToken succeeded', () async { final MockProfileService mockProfileService=MockProfileService(); final AccessMethodBloc accessMethodBloc=AccessMethodBloc(apiService: mockProfileService); when(mockProfileService.setAccessToken(any)).thenAnswer((_) async => ''); final expectedStates = [ AccessMethodState("PENDING", null).toString(), AccessMethodState("SUCCESS", null).toString(), ]; accessMethodBloc.add(AccessMethodEventAccessToken('AccessToken')); await expectLater( accessMethodBloc.stream.map((event) => event.toString()), emitsInOrder(expectedStates), ); await untilCalled(mockProfileService.setAccessToken(any)); verify(mockProfileService.setAccessToken(any)).called(1); }); test('emits [PENDING, FAILURE-Client] when AccessMethodEventAccessToken fail', () async { final MockProfileService mockProfileService=MockProfileService(); final AccessMethodBloc accessMethodBloc=AccessMethodBloc(apiService: mockProfileService); when(mockProfileService.setAccessToken(any)).thenThrow(ClientException("Client's error")); final expectedStates = [ AccessMethodState("PENDING", null).toString(), AccessMethodState("FAILURE", "CLIENT").toString(), ]; accessMethodBloc.add(AccessMethodEventAccessToken('AccessToken')); await expectLater( accessMethodBloc.stream.map((event) => event.toString()), emitsInOrder(expectedStates), ); await untilCalled(mockProfileService.setAccessToken(any)); verify(mockProfileService.setAccessToken(any)).called(1); }); test('emits [PENDING, FAILURE-Exist] when AccessMethodEventAccessToken fail', () async { final MockProfileService mockProfileService=MockProfileService(); final AccessMethodBloc accessMethodBloc=AccessMethodBloc(apiService: mockProfileService); when(mockProfileService.setAccessToken(any)).thenThrow(ExistException("Source not exist")); final expectedStates = [ AccessMethodState("PENDING", null).toString(), AccessMethodState("FAILURE", "EXIST").toString(), ]; accessMethodBloc.add(AccessMethodEventAccessToken('AccessToken')); await expectLater( accessMethodBloc.stream.map((event) => event.toString()), emitsInOrder(expectedStates), ); await untilCalled(mockProfileService.setAccessToken(any)); verify(mockProfileService.setAccessToken(any)).called(1); }); test('emits [PENDING, FAILURE-Auth] when AccessMethodEventAccessToken fail', () async { final MockProfileService mockProfileService=MockProfileService(); final AccessMethodBloc accessMethodBloc=AccessMethodBloc(apiService: mockProfileService); when(mockProfileService.setAccessToken(any)).thenThrow(AuthException("JWT invalid")); final expectedStates = [ AccessMethodState("PENDING", null).toString(), AccessMethodState("FAILURE", "AUTH").toString(), ]; accessMethodBloc.add(AccessMethodEventAccessToken('AccessToken')); await expectLater( accessMethodBloc.stream.map((event) => event.toString()), emitsInOrder(expectedStates), ); await untilCalled(mockProfileService.setAccessToken(any)); verify(mockProfileService.setAccessToken(any)).called(1); }); test('emits [PENDING, FAILURE-Server] when AccessMethodEventAccessToken fail', () async { final MockProfileService mockProfileService=MockProfileService(); final AccessMethodBloc accessMethodBloc=AccessMethodBloc(apiService: mockProfileService); when(mockProfileService.setAccessToken(any)).thenThrow(ServerException("Server's error")); final expectedStates = [ AccessMethodState("PENDING", null).toString(), AccessMethodState("FAILURE", "SERVER").toString(), ]; accessMethodBloc.add(AccessMethodEventAccessToken('AccessToken')); await expectLater( accessMethodBloc.stream.map((event) => event.toString()), emitsInOrder(expectedStates), ); await untilCalled(mockProfileService.setAccessToken(any)); verify(mockProfileService.setAccessToken(any)).called(1); }); test('emits [PENDING, FAILURE-Unknown] when AccessMethodEventAccessToken fail', () async { final MockProfileService mockProfileService=MockProfileService(); final AccessMethodBloc accessMethodBloc=AccessMethodBloc(apiService: mockProfileService); when(mockProfileService.setAccessToken(any)).thenThrow(Exception("Failed in unknown reason")); final expectedStates = [ AccessMethodState("PENDING", null).toString(), AccessMethodState("FAILURE", "UNKNOWN").toString(), ]; accessMethodBloc.add(AccessMethodEventAccessToken('AccessToken')); await expectLater( accessMethodBloc.stream.map((event) => event.toString()), emitsInOrder(expectedStates), ); await untilCalled(mockProfileService.setAccessToken(any)); verify(mockProfileService.setAccessToken(any)).called(1); }); }); group("AccessMethodBloc Reset Event", () { test('emits null when Reset', () async { final AccessMethodBloc accessMethodBloc=AccessMethodBloc(); accessMethodBloc.add(AccessMethodEventReset()); expect(accessMethodBloc.state, null); }); }); group("AccessMethodBloc Unknown Event", () { test('throw exception when Unknown happen', () async { final AccessMethodBloc accessMethodBloc=AccessMethodBloc(); }); }); }
0
mirrored_repositories/study_savvy_app/test
mirrored_repositories/study_savvy_app/test/bloc/bloc_access_methods_test.mocks.dart
// Mocks generated by Mockito 5.4.2 from annotations // in study_savvy_app/test/bloc/bloc_access_methods_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i6; import 'package:http/http.dart' as _i3; import 'package:mockito/mockito.dart' as _i1; import 'package:study_savvy_app/models/profile/model_profile.dart' as _i4; import 'package:study_savvy_app/services/profile/api_profile.dart' as _i5; import 'package:study_savvy_app/services/utils/jwt_storage.dart' as _i2; // 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 _FakeJwtService_0 extends _i1.SmartFake implements _i2.JwtService { _FakeJwtService_0( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeClient_1 extends _i1.SmartFake implements _i3.Client { _FakeClient_1( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeProfile_2 extends _i1.SmartFake implements _i4.Profile { _FakeProfile_2( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } /// A class which mocks [ProfileService]. /// /// See the documentation for Mockito's code generation for more information. class MockProfileService extends _i1.Mock implements _i5.ProfileService { MockProfileService() { _i1.throwOnMissingStub(this); } @override _i2.JwtService get jwtService => (super.noSuchMethod( Invocation.getter(#jwtService), returnValue: _FakeJwtService_0( this, Invocation.getter(#jwtService), ), ) as _i2.JwtService); @override set jwtService(_i2.JwtService? _jwtService) => super.noSuchMethod( Invocation.setter( #jwtService, _jwtService, ), returnValueForMissingStub: null, ); @override _i3.Client get httpClient => (super.noSuchMethod( Invocation.getter(#httpClient), returnValue: _FakeClient_1( this, Invocation.getter(#httpClient), ), ) as _i3.Client); @override set httpClient(_i3.Client? _httpClient) => super.noSuchMethod( Invocation.setter( #httpClient, _httpClient, ), returnValueForMissingStub: null, ); @override _i6.Future<_i4.Profile> getProfile() => (super.noSuchMethod( Invocation.method( #getProfile, [], ), returnValue: _i6.Future<_i4.Profile>.value(_FakeProfile_2( this, Invocation.method( #getProfile, [], ), )), ) as _i6.Future<_i4.Profile>); @override _i6.Future<void> setApiKey(String? apikey) => (super.noSuchMethod( Invocation.method( #setApiKey, [apikey], ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); @override _i6.Future<void> setAccessToken(String? accessToken) => (super.noSuchMethod( Invocation.method( #setAccessToken, [accessToken], ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); @override _i6.Future<void> resetPassword(_i4.UpdatePwd? data) => (super.noSuchMethod( Invocation.method( #resetPassword, [data], ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); @override _i6.Future<void> logout() => (super.noSuchMethod( Invocation.method( #logout, [], ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); }
0
mirrored_repositories/study_savvy_app/test
mirrored_repositories/study_savvy_app/test/bloc/bloc_article_improver_test.mocks.dart
// Mocks generated by Mockito 5.4.2 from annotations // in study_savvy_app/test/bloc/bloc_article_improver_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i5; import 'dart:convert' as _i6; import 'dart:io' as _i2; import 'dart:typed_data' as _i7; import 'package:http/http.dart' as _i4; import 'package:mockito/mockito.dart' as _i1; import 'package:study_savvy_app/models/article_improver/model_article_improver.dart' as _i9; import 'package:study_savvy_app/services/article_improver/api_article_improver.dart' as _i8; import 'package:study_savvy_app/services/utils/jwt_storage.dart' as _i3; // 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 _FakeFile_0 extends _i1.SmartFake implements _i2.File { _FakeFile_0( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeUri_1 extends _i1.SmartFake implements Uri { _FakeUri_1( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeDirectory_2 extends _i1.SmartFake implements _i2.Directory { _FakeDirectory_2( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeDateTime_3 extends _i1.SmartFake implements DateTime { _FakeDateTime_3( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeRandomAccessFile_4 extends _i1.SmartFake implements _i2.RandomAccessFile { _FakeRandomAccessFile_4( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeIOSink_5 extends _i1.SmartFake implements _i2.IOSink { _FakeIOSink_5( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeFileStat_6 extends _i1.SmartFake implements _i2.FileStat { _FakeFileStat_6( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeFileSystemEntity_7 extends _i1.SmartFake implements _i2.FileSystemEntity { _FakeFileSystemEntity_7( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeJwtService_8 extends _i1.SmartFake implements _i3.JwtService { _FakeJwtService_8( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeClient_9 extends _i1.SmartFake implements _i4.Client { _FakeClient_9( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } /// A class which mocks [File]. /// /// See the documentation for Mockito's code generation for more information. class MockFile extends _i1.Mock implements _i2.File { MockFile() { _i1.throwOnMissingStub(this); } @override _i2.File get absolute => (super.noSuchMethod( Invocation.getter(#absolute), returnValue: _FakeFile_0( this, Invocation.getter(#absolute), ), ) as _i2.File); @override String get path => (super.noSuchMethod( Invocation.getter(#path), returnValue: '', ) as String); @override Uri get uri => (super.noSuchMethod( Invocation.getter(#uri), returnValue: _FakeUri_1( this, Invocation.getter(#uri), ), ) as Uri); @override bool get isAbsolute => (super.noSuchMethod( Invocation.getter(#isAbsolute), returnValue: false, ) as bool); @override _i2.Directory get parent => (super.noSuchMethod( Invocation.getter(#parent), returnValue: _FakeDirectory_2( this, Invocation.getter(#parent), ), ) as _i2.Directory); @override _i5.Future<_i2.File> create({ bool? recursive = false, bool? exclusive = false, }) => (super.noSuchMethod( Invocation.method( #create, [], { #recursive: recursive, #exclusive: exclusive, }, ), returnValue: _i5.Future<_i2.File>.value(_FakeFile_0( this, Invocation.method( #create, [], { #recursive: recursive, #exclusive: exclusive, }, ), )), ) as _i5.Future<_i2.File>); @override void createSync({ bool? recursive = false, bool? exclusive = false, }) => super.noSuchMethod( Invocation.method( #createSync, [], { #recursive: recursive, #exclusive: exclusive, }, ), returnValueForMissingStub: null, ); @override _i5.Future<_i2.File> rename(String? newPath) => (super.noSuchMethod( Invocation.method( #rename, [newPath], ), returnValue: _i5.Future<_i2.File>.value(_FakeFile_0( this, Invocation.method( #rename, [newPath], ), )), ) as _i5.Future<_i2.File>); @override _i2.File renameSync(String? newPath) => (super.noSuchMethod( Invocation.method( #renameSync, [newPath], ), returnValue: _FakeFile_0( this, Invocation.method( #renameSync, [newPath], ), ), ) as _i2.File); @override _i5.Future<_i2.File> copy(String? newPath) => (super.noSuchMethod( Invocation.method( #copy, [newPath], ), returnValue: _i5.Future<_i2.File>.value(_FakeFile_0( this, Invocation.method( #copy, [newPath], ), )), ) as _i5.Future<_i2.File>); @override _i2.File copySync(String? newPath) => (super.noSuchMethod( Invocation.method( #copySync, [newPath], ), returnValue: _FakeFile_0( this, Invocation.method( #copySync, [newPath], ), ), ) as _i2.File); @override _i5.Future<int> length() => (super.noSuchMethod( Invocation.method( #length, [], ), returnValue: _i5.Future<int>.value(0), ) as _i5.Future<int>); @override int lengthSync() => (super.noSuchMethod( Invocation.method( #lengthSync, [], ), returnValue: 0, ) as int); @override _i5.Future<DateTime> lastAccessed() => (super.noSuchMethod( Invocation.method( #lastAccessed, [], ), returnValue: _i5.Future<DateTime>.value(_FakeDateTime_3( this, Invocation.method( #lastAccessed, [], ), )), ) as _i5.Future<DateTime>); @override DateTime lastAccessedSync() => (super.noSuchMethod( Invocation.method( #lastAccessedSync, [], ), returnValue: _FakeDateTime_3( this, Invocation.method( #lastAccessedSync, [], ), ), ) as DateTime); @override _i5.Future<dynamic> setLastAccessed(DateTime? time) => (super.noSuchMethod( Invocation.method( #setLastAccessed, [time], ), returnValue: _i5.Future<dynamic>.value(), ) as _i5.Future<dynamic>); @override void setLastAccessedSync(DateTime? time) => super.noSuchMethod( Invocation.method( #setLastAccessedSync, [time], ), returnValueForMissingStub: null, ); @override _i5.Future<DateTime> lastModified() => (super.noSuchMethod( Invocation.method( #lastModified, [], ), returnValue: _i5.Future<DateTime>.value(_FakeDateTime_3( this, Invocation.method( #lastModified, [], ), )), ) as _i5.Future<DateTime>); @override DateTime lastModifiedSync() => (super.noSuchMethod( Invocation.method( #lastModifiedSync, [], ), returnValue: _FakeDateTime_3( this, Invocation.method( #lastModifiedSync, [], ), ), ) as DateTime); @override _i5.Future<dynamic> setLastModified(DateTime? time) => (super.noSuchMethod( Invocation.method( #setLastModified, [time], ), returnValue: _i5.Future<dynamic>.value(), ) as _i5.Future<dynamic>); @override void setLastModifiedSync(DateTime? time) => super.noSuchMethod( Invocation.method( #setLastModifiedSync, [time], ), returnValueForMissingStub: null, ); @override _i5.Future<_i2.RandomAccessFile> open( {_i2.FileMode? mode = _i2.FileMode.read}) => (super.noSuchMethod( Invocation.method( #open, [], {#mode: mode}, ), returnValue: _i5.Future<_i2.RandomAccessFile>.value(_FakeRandomAccessFile_4( this, Invocation.method( #open, [], {#mode: mode}, ), )), ) as _i5.Future<_i2.RandomAccessFile>); @override _i2.RandomAccessFile openSync({_i2.FileMode? mode = _i2.FileMode.read}) => (super.noSuchMethod( Invocation.method( #openSync, [], {#mode: mode}, ), returnValue: _FakeRandomAccessFile_4( this, Invocation.method( #openSync, [], {#mode: mode}, ), ), ) as _i2.RandomAccessFile); @override _i5.Stream<List<int>> openRead([ int? start, int? end, ]) => (super.noSuchMethod( Invocation.method( #openRead, [ start, end, ], ), returnValue: _i5.Stream<List<int>>.empty(), ) as _i5.Stream<List<int>>); @override _i2.IOSink openWrite({ _i2.FileMode? mode = _i2.FileMode.write, _i6.Encoding? encoding = const _i6.Utf8Codec(), }) => (super.noSuchMethod( Invocation.method( #openWrite, [], { #mode: mode, #encoding: encoding, }, ), returnValue: _FakeIOSink_5( this, Invocation.method( #openWrite, [], { #mode: mode, #encoding: encoding, }, ), ), ) as _i2.IOSink); @override _i5.Future<_i7.Uint8List> readAsBytes() => (super.noSuchMethod( Invocation.method( #readAsBytes, [], ), returnValue: _i5.Future<_i7.Uint8List>.value(_i7.Uint8List(0)), ) as _i5.Future<_i7.Uint8List>); @override _i7.Uint8List readAsBytesSync() => (super.noSuchMethod( Invocation.method( #readAsBytesSync, [], ), returnValue: _i7.Uint8List(0), ) as _i7.Uint8List); @override _i5.Future<String> readAsString( {_i6.Encoding? encoding = const _i6.Utf8Codec()}) => (super.noSuchMethod( Invocation.method( #readAsString, [], {#encoding: encoding}, ), returnValue: _i5.Future<String>.value(''), ) as _i5.Future<String>); @override String readAsStringSync({_i6.Encoding? encoding = const _i6.Utf8Codec()}) => (super.noSuchMethod( Invocation.method( #readAsStringSync, [], {#encoding: encoding}, ), returnValue: '', ) as String); @override _i5.Future<List<String>> readAsLines( {_i6.Encoding? encoding = const _i6.Utf8Codec()}) => (super.noSuchMethod( Invocation.method( #readAsLines, [], {#encoding: encoding}, ), returnValue: _i5.Future<List<String>>.value(<String>[]), ) as _i5.Future<List<String>>); @override List<String> readAsLinesSync( {_i6.Encoding? encoding = const _i6.Utf8Codec()}) => (super.noSuchMethod( Invocation.method( #readAsLinesSync, [], {#encoding: encoding}, ), returnValue: <String>[], ) as List<String>); @override _i5.Future<_i2.File> writeAsBytes( List<int>? bytes, { _i2.FileMode? mode = _i2.FileMode.write, bool? flush = false, }) => (super.noSuchMethod( Invocation.method( #writeAsBytes, [bytes], { #mode: mode, #flush: flush, }, ), returnValue: _i5.Future<_i2.File>.value(_FakeFile_0( this, Invocation.method( #writeAsBytes, [bytes], { #mode: mode, #flush: flush, }, ), )), ) as _i5.Future<_i2.File>); @override void writeAsBytesSync( List<int>? bytes, { _i2.FileMode? mode = _i2.FileMode.write, bool? flush = false, }) => super.noSuchMethod( Invocation.method( #writeAsBytesSync, [bytes], { #mode: mode, #flush: flush, }, ), returnValueForMissingStub: null, ); @override _i5.Future<_i2.File> writeAsString( String? contents, { _i2.FileMode? mode = _i2.FileMode.write, _i6.Encoding? encoding = const _i6.Utf8Codec(), bool? flush = false, }) => (super.noSuchMethod( Invocation.method( #writeAsString, [contents], { #mode: mode, #encoding: encoding, #flush: flush, }, ), returnValue: _i5.Future<_i2.File>.value(_FakeFile_0( this, Invocation.method( #writeAsString, [contents], { #mode: mode, #encoding: encoding, #flush: flush, }, ), )), ) as _i5.Future<_i2.File>); @override void writeAsStringSync( String? contents, { _i2.FileMode? mode = _i2.FileMode.write, _i6.Encoding? encoding = const _i6.Utf8Codec(), bool? flush = false, }) => super.noSuchMethod( Invocation.method( #writeAsStringSync, [contents], { #mode: mode, #encoding: encoding, #flush: flush, }, ), returnValueForMissingStub: null, ); @override _i5.Future<bool> exists() => (super.noSuchMethod( Invocation.method( #exists, [], ), returnValue: _i5.Future<bool>.value(false), ) as _i5.Future<bool>); @override bool existsSync() => (super.noSuchMethod( Invocation.method( #existsSync, [], ), returnValue: false, ) as bool); @override _i5.Future<String> resolveSymbolicLinks() => (super.noSuchMethod( Invocation.method( #resolveSymbolicLinks, [], ), returnValue: _i5.Future<String>.value(''), ) as _i5.Future<String>); @override String resolveSymbolicLinksSync() => (super.noSuchMethod( Invocation.method( #resolveSymbolicLinksSync, [], ), returnValue: '', ) as String); @override _i5.Future<_i2.FileStat> stat() => (super.noSuchMethod( Invocation.method( #stat, [], ), returnValue: _i5.Future<_i2.FileStat>.value(_FakeFileStat_6( this, Invocation.method( #stat, [], ), )), ) as _i5.Future<_i2.FileStat>); @override _i2.FileStat statSync() => (super.noSuchMethod( Invocation.method( #statSync, [], ), returnValue: _FakeFileStat_6( this, Invocation.method( #statSync, [], ), ), ) as _i2.FileStat); @override _i5.Future<_i2.FileSystemEntity> delete({bool? recursive = false}) => (super.noSuchMethod( Invocation.method( #delete, [], {#recursive: recursive}, ), returnValue: _i5.Future<_i2.FileSystemEntity>.value(_FakeFileSystemEntity_7( this, Invocation.method( #delete, [], {#recursive: recursive}, ), )), ) as _i5.Future<_i2.FileSystemEntity>); @override void deleteSync({bool? recursive = false}) => super.noSuchMethod( Invocation.method( #deleteSync, [], {#recursive: recursive}, ), returnValueForMissingStub: null, ); @override _i5.Stream<_i2.FileSystemEvent> watch({ int? events = 15, bool? recursive = false, }) => (super.noSuchMethod( Invocation.method( #watch, [], { #events: events, #recursive: recursive, }, ), returnValue: _i5.Stream<_i2.FileSystemEvent>.empty(), ) as _i5.Stream<_i2.FileSystemEvent>); } /// A class which mocks [ArticleImproverService]. /// /// See the documentation for Mockito's code generation for more information. class MockArticleImproverService extends _i1.Mock implements _i8.ArticleImproverService { MockArticleImproverService() { _i1.throwOnMissingStub(this); } @override _i3.JwtService get jwtService => (super.noSuchMethod( Invocation.getter(#jwtService), returnValue: _FakeJwtService_8( this, Invocation.getter(#jwtService), ), ) as _i3.JwtService); @override set jwtService(_i3.JwtService? _jwtService) => super.noSuchMethod( Invocation.setter( #jwtService, _jwtService, ), returnValueForMissingStub: null, ); @override _i4.Client get httpClient => (super.noSuchMethod( Invocation.getter(#httpClient), returnValue: _FakeClient_9( this, Invocation.getter(#httpClient), ), ) as _i4.Client); @override set httpClient(_i4.Client? _httpClient) => super.noSuchMethod( Invocation.setter( #httpClient, _httpClient, ), returnValueForMissingStub: null, ); @override _i5.Future<void> predictOcrGraph(_i9.ArticleImage? data) => (super.noSuchMethod( Invocation.method( #predictOcrGraph, [data], ), returnValue: _i5.Future<void>.value(), returnValueForMissingStub: _i5.Future<void>.value(), ) as _i5.Future<void>); @override _i5.Future<void> predictOcrText(_i9.ArticleText? data) => (super.noSuchMethod( Invocation.method( #predictOcrText, [data], ), returnValue: _i5.Future<void>.value(), returnValueForMissingStub: _i5.Future<void>.value(), ) as _i5.Future<void>); }
0
mirrored_repositories/study_savvy_app/test
mirrored_repositories/study_savvy_app/test/bloc/bloc_article_improver_test.dart
import 'dart:io'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'package:study_savvy_app/blocs/article_improver/bloc_article_improver.dart'; import 'package:study_savvy_app/models/article_improver/model_article_improver.dart'; import 'package:study_savvy_app/services/article_improver/api_article_improver.dart'; import 'package:study_savvy_app/utils/exception.dart'; import 'bloc_article_improver_test.mocks.dart'; @GenerateMocks([File,ArticleImproverService]) void main() { group("ArticleBloc", () { test('emit null when ArticleEventText build', () async { final ArticleBloc articleBloc=ArticleBloc(); expect(articleBloc.state.toString(), ArticleState("INIT",null).toString()); }); }); group('ArticleBloc Graph Event', () { test('emits [PENDING, SUCCESS] when ArticleEventGraph succeeded', () async { final MockArticleImproverService mockArticleImproverService=MockArticleImproverService(); final ArticleBloc articleBloc=ArticleBloc(apiService: mockArticleImproverService); when(mockArticleImproverService.predictOcrGraph(any)).thenAnswer((_) async => ''); final expectedStates = [ ArticleState("PENDING", null).toString(), ArticleState("SUCCESS", null).toString(), ]; const String testPrompt="Test prompt"; final MockFile testFile=MockFile(); ArticleImage testArticleImage=ArticleImage(testFile, testPrompt); articleBloc.add(ArticleEventGraph(testArticleImage)); await expectLater( articleBloc.stream.map((event) => event.toString()), emitsInOrder(expectedStates), ); await untilCalled(mockArticleImproverService.predictOcrGraph(any)); verify(mockArticleImproverService.predictOcrGraph(any)).called(1); }); test('emits [PENDING, FAILURE-Client] when ArticleEventGraph fail', () async { final MockArticleImproverService mockArticleImproverService=MockArticleImproverService(); final ArticleBloc articleBloc=ArticleBloc(apiService: mockArticleImproverService); when(mockArticleImproverService.predictOcrGraph(any)).thenThrow(ClientException("Client's error")); final expectedStates = [ ArticleState("PENDING", null).toString(), ArticleState("FAILURE", "CLIENT").toString(), ]; const String testPrompt="Test prompt"; final MockFile testFile=MockFile(); ArticleImage testArticleImage=ArticleImage(testFile, testPrompt); articleBloc.add(ArticleEventGraph(testArticleImage)); await expectLater( articleBloc.stream.map((event) => event.toString()), emitsInOrder(expectedStates), ); await untilCalled(mockArticleImproverService.predictOcrGraph(any)); verify(mockArticleImproverService.predictOcrGraph(any)).called(1); }); test('emits [PENDING, FAILURE-Exist] when ArticleEventGraph fail', () async { final MockArticleImproverService mockArticleImproverService=MockArticleImproverService(); final ArticleBloc articleBloc=ArticleBloc(apiService: mockArticleImproverService); when(mockArticleImproverService.predictOcrGraph(any)).thenThrow(ExistException("Source not exist")); final expectedStates = [ ArticleState("PENDING", null).toString(), ArticleState("FAILURE", "EXIST").toString(), ]; const String testPrompt="Test prompt"; final MockFile testFile=MockFile(); ArticleImage testArticleImage=ArticleImage(testFile, testPrompt); articleBloc.add(ArticleEventGraph(testArticleImage)); await expectLater( articleBloc.stream.map((event) => event.toString()), emitsInOrder(expectedStates), ); await untilCalled(mockArticleImproverService.predictOcrGraph(any)); verify(mockArticleImproverService.predictOcrGraph(any)).called(1); }); test('emits [PENDING, FAILURE-Auth] when ArticleEventGraph fail', () async { final MockArticleImproverService mockArticleImproverService=MockArticleImproverService(); final ArticleBloc articleBloc=ArticleBloc(apiService: mockArticleImproverService); when(mockArticleImproverService.predictOcrGraph(any)).thenThrow(AuthException("JWT invalid")); final expectedStates = [ ArticleState("PENDING", null).toString(), ArticleState("FAILURE", "AUTH").toString(), ]; const String testPrompt="Test prompt"; final MockFile testFile=MockFile(); ArticleImage testArticleImage=ArticleImage(testFile, testPrompt); articleBloc.add(ArticleEventGraph(testArticleImage)); await expectLater( articleBloc.stream.map((event) => event.toString()), emitsInOrder(expectedStates), ); await untilCalled(mockArticleImproverService.predictOcrGraph(any)); verify(mockArticleImproverService.predictOcrGraph(any)).called(1); }); test('emits [PENDING, FAILURE-Server] when ArticleEventGraph fail', () async { final MockArticleImproverService mockArticleImproverService=MockArticleImproverService(); final ArticleBloc articleBloc=ArticleBloc(apiService: mockArticleImproverService); when(mockArticleImproverService.predictOcrGraph(any)).thenThrow(ServerException("Server's error")); final expectedStates = [ ArticleState("PENDING", null).toString(), ArticleState("FAILURE", "SERVER").toString(), ]; const String testPrompt="Test prompt"; final MockFile testFile=MockFile(); ArticleImage testArticleImage=ArticleImage(testFile, testPrompt); articleBloc.add(ArticleEventGraph(testArticleImage)); await expectLater( articleBloc.stream.map((event) => event.toString()), emitsInOrder(expectedStates), ); await untilCalled(mockArticleImproverService.predictOcrGraph(any)); verify(mockArticleImproverService.predictOcrGraph(any)).called(1); }); test('emits [PENDING, FAILURE-Unknown] when ArticleEventGraph fail', () async { final MockArticleImproverService mockArticleImproverService=MockArticleImproverService(); final ArticleBloc articleBloc=ArticleBloc(apiService: mockArticleImproverService); when(mockArticleImproverService.predictOcrGraph(any)).thenThrow(Exception("Failed in unknown reason")); final expectedStates = [ ArticleState("PENDING", null).toString(), ArticleState("FAILURE", "UNKNOWN").toString(), ]; const String testPrompt="Test prompt"; final MockFile testFile=MockFile(); ArticleImage testArticleImage=ArticleImage(testFile, testPrompt); articleBloc.add(ArticleEventGraph(testArticleImage)); await expectLater( articleBloc.stream.map((event) => event.toString()), emitsInOrder(expectedStates), ); await untilCalled(mockArticleImproverService.predictOcrGraph(any)); verify(mockArticleImproverService.predictOcrGraph(any)).called(1); }); }); group('ArticleBloc Text Event', () { test('emits [PENDING, SUCCESS] when ArticleEventText succeeded', () async { final MockArticleImproverService mockArticleImproverService=MockArticleImproverService(); final ArticleBloc articleBloc=ArticleBloc(apiService: mockArticleImproverService); when(mockArticleImproverService.predictOcrText(any)).thenAnswer((_) async => ''); final expectedStates = [ ArticleState("PENDING", null).toString(), ArticleState("SUCCESS", null).toString(), ]; const testContent="Test content"; const testPrompt="Test prompt"; ArticleText testArticleText=ArticleText(testContent,testPrompt); articleBloc.add(ArticleEventText(testArticleText)); await expectLater( articleBloc.stream.map((event) => event.toString()), emitsInOrder(expectedStates), ); await untilCalled(mockArticleImproverService.predictOcrText(any)); verify(mockArticleImproverService.predictOcrText(any)).called(1); }); test('emits [PENDING, FAILURE-Client] when ArticleEventText fail', () async { final MockArticleImproverService mockArticleImproverService=MockArticleImproverService(); final ArticleBloc articleBloc=ArticleBloc(apiService: mockArticleImproverService); when(mockArticleImproverService.predictOcrText(any)).thenThrow(ClientException("Client's error")); final expectedStates = [ ArticleState("PENDING", null).toString(), ArticleState("FAILURE", "CLIENT").toString(), ]; const testContent="Test content"; const testPrompt="Test prompt"; ArticleText testArticleText=ArticleText(testContent,testPrompt); articleBloc.add(ArticleEventText(testArticleText)); await expectLater( articleBloc.stream.map((event) => event.toString()), emitsInOrder(expectedStates), ); await untilCalled(mockArticleImproverService.predictOcrText(any)); verify(mockArticleImproverService.predictOcrText(any)).called(1); }); test('emits [PENDING, FAILURE-Exist] when ArticleEventText fail', () async { final MockArticleImproverService mockArticleImproverService=MockArticleImproverService(); final ArticleBloc articleBloc=ArticleBloc(apiService: mockArticleImproverService); when(mockArticleImproverService.predictOcrText(any)).thenThrow(ExistException("Source not exist")); final expectedStates = [ ArticleState("PENDING", null).toString(), ArticleState("FAILURE", "EXIST").toString(), ]; const testContent="Test content"; const testPrompt="Test prompt"; ArticleText testArticleText=ArticleText(testContent,testPrompt); articleBloc.add(ArticleEventText(testArticleText)); await expectLater( articleBloc.stream.map((event) => event.toString()), emitsInOrder(expectedStates), ); await untilCalled(mockArticleImproverService.predictOcrText(any)); verify(mockArticleImproverService.predictOcrText(any)).called(1); }); test('emits [PENDING, FAILURE-Auth] when ArticleEventText fail', () async { final MockArticleImproverService mockArticleImproverService=MockArticleImproverService(); final ArticleBloc articleBloc=ArticleBloc(apiService: mockArticleImproverService); when(mockArticleImproverService.predictOcrText(any)).thenThrow(AuthException("JWT invalid")); final expectedStates = [ ArticleState("PENDING", null).toString(), ArticleState("FAILURE", "AUTH").toString(), ]; const testContent="Test content"; const testPrompt="Test prompt"; ArticleText testArticleText=ArticleText(testContent,testPrompt); articleBloc.add(ArticleEventText(testArticleText)); await expectLater( articleBloc.stream.map((event) => event.toString()), emitsInOrder(expectedStates), ); await untilCalled(mockArticleImproverService.predictOcrText(any)); verify(mockArticleImproverService.predictOcrText(any)).called(1); }); test('emits [PENDING, FAILURE-Server] when ArticleEventText fail', () async { final MockArticleImproverService mockArticleImproverService=MockArticleImproverService(); final ArticleBloc articleBloc=ArticleBloc(apiService: mockArticleImproverService); when(mockArticleImproverService.predictOcrText(any)).thenThrow(ServerException("Server's error")); final expectedStates = [ ArticleState("PENDING", null).toString(), ArticleState("FAILURE", "SERVER").toString(), ]; const testContent="Test content"; const testPrompt="Test prompt"; ArticleText testArticleText=ArticleText(testContent,testPrompt); articleBloc.add(ArticleEventText(testArticleText)); await expectLater( articleBloc.stream.map((event) => event.toString()), emitsInOrder(expectedStates), ); await untilCalled(mockArticleImproverService.predictOcrText(any)); verify(mockArticleImproverService.predictOcrText(any)).called(1); }); test('emits [PENDING, FAILURE-Unknown] when ArticleEventText fail', () async { final MockArticleImproverService mockArticleImproverService=MockArticleImproverService(); final ArticleBloc articleBloc=ArticleBloc(apiService: mockArticleImproverService); when(mockArticleImproverService.predictOcrText(any)).thenThrow(Exception("Failed in unknown reason")); final expectedStates = [ ArticleState("PENDING", null).toString(), ArticleState("FAILURE", "UNKNOWN").toString(), ]; const testContent="Test content"; const testPrompt="Test prompt"; ArticleText testArticleText=ArticleText(testContent,testPrompt); articleBloc.add(ArticleEventText(testArticleText)); await expectLater( articleBloc.stream.map((event) => event.toString()), emitsInOrder(expectedStates), ); await untilCalled(mockArticleImproverService.predictOcrText(any)); verify(mockArticleImproverService.predictOcrText(any)).called(1); }); }); group("ArticleBloc Refresh Event", () { test('emits null when Refresh', () async { final ArticleBloc articleBloc=ArticleBloc(); articleBloc.add(ArticleEventRefresh()); expect(articleBloc.state.toString(),ArticleState("INIT", null).toString()); }); }); group("ArticleBloc Unknown Event", () { test('throw exception when Unknown happen', () async { final ArticleBloc articleBloc=ArticleBloc(); }); }); }
0
mirrored_repositories/study_savvy_app/test
mirrored_repositories/study_savvy_app/test/class/article_improver_test.mocks.dart
// Mocks generated by Mockito 5.4.2 from annotations // in study_savvy_app/test/class/article_improver_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i3; import 'dart:convert' as _i4; import 'dart:io' as _i2; import 'dart:typed_data' as _i5; 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 _FakeFile_0 extends _i1.SmartFake implements _i2.File { _FakeFile_0( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeUri_1 extends _i1.SmartFake implements Uri { _FakeUri_1( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeDirectory_2 extends _i1.SmartFake implements _i2.Directory { _FakeDirectory_2( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeDateTime_3 extends _i1.SmartFake implements DateTime { _FakeDateTime_3( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeRandomAccessFile_4 extends _i1.SmartFake implements _i2.RandomAccessFile { _FakeRandomAccessFile_4( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeIOSink_5 extends _i1.SmartFake implements _i2.IOSink { _FakeIOSink_5( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeFileStat_6 extends _i1.SmartFake implements _i2.FileStat { _FakeFileStat_6( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeFileSystemEntity_7 extends _i1.SmartFake implements _i2.FileSystemEntity { _FakeFileSystemEntity_7( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } /// A class which mocks [File]. /// /// See the documentation for Mockito's code generation for more information. class MockFile extends _i1.Mock implements _i2.File { MockFile() { _i1.throwOnMissingStub(this); } @override _i2.File get absolute => (super.noSuchMethod( Invocation.getter(#absolute), returnValue: _FakeFile_0( this, Invocation.getter(#absolute), ), ) as _i2.File); @override String get path => (super.noSuchMethod( Invocation.getter(#path), returnValue: '', ) as String); @override Uri get uri => (super.noSuchMethod( Invocation.getter(#uri), returnValue: _FakeUri_1( this, Invocation.getter(#uri), ), ) as Uri); @override bool get isAbsolute => (super.noSuchMethod( Invocation.getter(#isAbsolute), returnValue: false, ) as bool); @override _i2.Directory get parent => (super.noSuchMethod( Invocation.getter(#parent), returnValue: _FakeDirectory_2( this, Invocation.getter(#parent), ), ) as _i2.Directory); @override _i3.Future<_i2.File> create({ bool? recursive = false, bool? exclusive = false, }) => (super.noSuchMethod( Invocation.method( #create, [], { #recursive: recursive, #exclusive: exclusive, }, ), returnValue: _i3.Future<_i2.File>.value(_FakeFile_0( this, Invocation.method( #create, [], { #recursive: recursive, #exclusive: exclusive, }, ), )), ) as _i3.Future<_i2.File>); @override void createSync({ bool? recursive = false, bool? exclusive = false, }) => super.noSuchMethod( Invocation.method( #createSync, [], { #recursive: recursive, #exclusive: exclusive, }, ), returnValueForMissingStub: null, ); @override _i3.Future<_i2.File> rename(String? newPath) => (super.noSuchMethod( Invocation.method( #rename, [newPath], ), returnValue: _i3.Future<_i2.File>.value(_FakeFile_0( this, Invocation.method( #rename, [newPath], ), )), ) as _i3.Future<_i2.File>); @override _i2.File renameSync(String? newPath) => (super.noSuchMethod( Invocation.method( #renameSync, [newPath], ), returnValue: _FakeFile_0( this, Invocation.method( #renameSync, [newPath], ), ), ) as _i2.File); @override _i3.Future<_i2.File> copy(String? newPath) => (super.noSuchMethod( Invocation.method( #copy, [newPath], ), returnValue: _i3.Future<_i2.File>.value(_FakeFile_0( this, Invocation.method( #copy, [newPath], ), )), ) as _i3.Future<_i2.File>); @override _i2.File copySync(String? newPath) => (super.noSuchMethod( Invocation.method( #copySync, [newPath], ), returnValue: _FakeFile_0( this, Invocation.method( #copySync, [newPath], ), ), ) as _i2.File); @override _i3.Future<int> length() => (super.noSuchMethod( Invocation.method( #length, [], ), returnValue: _i3.Future<int>.value(0), ) as _i3.Future<int>); @override int lengthSync() => (super.noSuchMethod( Invocation.method( #lengthSync, [], ), returnValue: 0, ) as int); @override _i3.Future<DateTime> lastAccessed() => (super.noSuchMethod( Invocation.method( #lastAccessed, [], ), returnValue: _i3.Future<DateTime>.value(_FakeDateTime_3( this, Invocation.method( #lastAccessed, [], ), )), ) as _i3.Future<DateTime>); @override DateTime lastAccessedSync() => (super.noSuchMethod( Invocation.method( #lastAccessedSync, [], ), returnValue: _FakeDateTime_3( this, Invocation.method( #lastAccessedSync, [], ), ), ) as DateTime); @override _i3.Future<dynamic> setLastAccessed(DateTime? time) => (super.noSuchMethod( Invocation.method( #setLastAccessed, [time], ), returnValue: _i3.Future<dynamic>.value(), ) as _i3.Future<dynamic>); @override void setLastAccessedSync(DateTime? time) => super.noSuchMethod( Invocation.method( #setLastAccessedSync, [time], ), returnValueForMissingStub: null, ); @override _i3.Future<DateTime> lastModified() => (super.noSuchMethod( Invocation.method( #lastModified, [], ), returnValue: _i3.Future<DateTime>.value(_FakeDateTime_3( this, Invocation.method( #lastModified, [], ), )), ) as _i3.Future<DateTime>); @override DateTime lastModifiedSync() => (super.noSuchMethod( Invocation.method( #lastModifiedSync, [], ), returnValue: _FakeDateTime_3( this, Invocation.method( #lastModifiedSync, [], ), ), ) as DateTime); @override _i3.Future<dynamic> setLastModified(DateTime? time) => (super.noSuchMethod( Invocation.method( #setLastModified, [time], ), returnValue: _i3.Future<dynamic>.value(), ) as _i3.Future<dynamic>); @override void setLastModifiedSync(DateTime? time) => super.noSuchMethod( Invocation.method( #setLastModifiedSync, [time], ), returnValueForMissingStub: null, ); @override _i3.Future<_i2.RandomAccessFile> open( {_i2.FileMode? mode = _i2.FileMode.read}) => (super.noSuchMethod( Invocation.method( #open, [], {#mode: mode}, ), returnValue: _i3.Future<_i2.RandomAccessFile>.value(_FakeRandomAccessFile_4( this, Invocation.method( #open, [], {#mode: mode}, ), )), ) as _i3.Future<_i2.RandomAccessFile>); @override _i2.RandomAccessFile openSync({_i2.FileMode? mode = _i2.FileMode.read}) => (super.noSuchMethod( Invocation.method( #openSync, [], {#mode: mode}, ), returnValue: _FakeRandomAccessFile_4( this, Invocation.method( #openSync, [], {#mode: mode}, ), ), ) as _i2.RandomAccessFile); @override _i3.Stream<List<int>> openRead([ int? start, int? end, ]) => (super.noSuchMethod( Invocation.method( #openRead, [ start, end, ], ), returnValue: _i3.Stream<List<int>>.empty(), ) as _i3.Stream<List<int>>); @override _i2.IOSink openWrite({ _i2.FileMode? mode = _i2.FileMode.write, _i4.Encoding? encoding = const _i4.Utf8Codec(), }) => (super.noSuchMethod( Invocation.method( #openWrite, [], { #mode: mode, #encoding: encoding, }, ), returnValue: _FakeIOSink_5( this, Invocation.method( #openWrite, [], { #mode: mode, #encoding: encoding, }, ), ), ) as _i2.IOSink); @override _i3.Future<_i5.Uint8List> readAsBytes() => (super.noSuchMethod( Invocation.method( #readAsBytes, [], ), returnValue: _i3.Future<_i5.Uint8List>.value(_i5.Uint8List(0)), ) as _i3.Future<_i5.Uint8List>); @override _i5.Uint8List readAsBytesSync() => (super.noSuchMethod( Invocation.method( #readAsBytesSync, [], ), returnValue: _i5.Uint8List(0), ) as _i5.Uint8List); @override _i3.Future<String> readAsString( {_i4.Encoding? encoding = const _i4.Utf8Codec()}) => (super.noSuchMethod( Invocation.method( #readAsString, [], {#encoding: encoding}, ), returnValue: _i3.Future<String>.value(''), ) as _i3.Future<String>); @override String readAsStringSync({_i4.Encoding? encoding = const _i4.Utf8Codec()}) => (super.noSuchMethod( Invocation.method( #readAsStringSync, [], {#encoding: encoding}, ), returnValue: '', ) as String); @override _i3.Future<List<String>> readAsLines( {_i4.Encoding? encoding = const _i4.Utf8Codec()}) => (super.noSuchMethod( Invocation.method( #readAsLines, [], {#encoding: encoding}, ), returnValue: _i3.Future<List<String>>.value(<String>[]), ) as _i3.Future<List<String>>); @override List<String> readAsLinesSync( {_i4.Encoding? encoding = const _i4.Utf8Codec()}) => (super.noSuchMethod( Invocation.method( #readAsLinesSync, [], {#encoding: encoding}, ), returnValue: <String>[], ) as List<String>); @override _i3.Future<_i2.File> writeAsBytes( List<int>? bytes, { _i2.FileMode? mode = _i2.FileMode.write, bool? flush = false, }) => (super.noSuchMethod( Invocation.method( #writeAsBytes, [bytes], { #mode: mode, #flush: flush, }, ), returnValue: _i3.Future<_i2.File>.value(_FakeFile_0( this, Invocation.method( #writeAsBytes, [bytes], { #mode: mode, #flush: flush, }, ), )), ) as _i3.Future<_i2.File>); @override void writeAsBytesSync( List<int>? bytes, { _i2.FileMode? mode = _i2.FileMode.write, bool? flush = false, }) => super.noSuchMethod( Invocation.method( #writeAsBytesSync, [bytes], { #mode: mode, #flush: flush, }, ), returnValueForMissingStub: null, ); @override _i3.Future<_i2.File> writeAsString( String? contents, { _i2.FileMode? mode = _i2.FileMode.write, _i4.Encoding? encoding = const _i4.Utf8Codec(), bool? flush = false, }) => (super.noSuchMethod( Invocation.method( #writeAsString, [contents], { #mode: mode, #encoding: encoding, #flush: flush, }, ), returnValue: _i3.Future<_i2.File>.value(_FakeFile_0( this, Invocation.method( #writeAsString, [contents], { #mode: mode, #encoding: encoding, #flush: flush, }, ), )), ) as _i3.Future<_i2.File>); @override void writeAsStringSync( String? contents, { _i2.FileMode? mode = _i2.FileMode.write, _i4.Encoding? encoding = const _i4.Utf8Codec(), bool? flush = false, }) => super.noSuchMethod( Invocation.method( #writeAsStringSync, [contents], { #mode: mode, #encoding: encoding, #flush: flush, }, ), returnValueForMissingStub: null, ); @override _i3.Future<bool> exists() => (super.noSuchMethod( Invocation.method( #exists, [], ), returnValue: _i3.Future<bool>.value(false), ) as _i3.Future<bool>); @override bool existsSync() => (super.noSuchMethod( Invocation.method( #existsSync, [], ), returnValue: false, ) as bool); @override _i3.Future<String> resolveSymbolicLinks() => (super.noSuchMethod( Invocation.method( #resolveSymbolicLinks, [], ), returnValue: _i3.Future<String>.value(''), ) as _i3.Future<String>); @override String resolveSymbolicLinksSync() => (super.noSuchMethod( Invocation.method( #resolveSymbolicLinksSync, [], ), returnValue: '', ) as String); @override _i3.Future<_i2.FileStat> stat() => (super.noSuchMethod( Invocation.method( #stat, [], ), returnValue: _i3.Future<_i2.FileStat>.value(_FakeFileStat_6( this, Invocation.method( #stat, [], ), )), ) as _i3.Future<_i2.FileStat>); @override _i2.FileStat statSync() => (super.noSuchMethod( Invocation.method( #statSync, [], ), returnValue: _FakeFileStat_6( this, Invocation.method( #statSync, [], ), ), ) as _i2.FileStat); @override _i3.Future<_i2.FileSystemEntity> delete({bool? recursive = false}) => (super.noSuchMethod( Invocation.method( #delete, [], {#recursive: recursive}, ), returnValue: _i3.Future<_i2.FileSystemEntity>.value(_FakeFileSystemEntity_7( this, Invocation.method( #delete, [], {#recursive: recursive}, ), )), ) as _i3.Future<_i2.FileSystemEntity>); @override void deleteSync({bool? recursive = false}) => super.noSuchMethod( Invocation.method( #deleteSync, [], {#recursive: recursive}, ), returnValueForMissingStub: null, ); @override _i3.Stream<_i2.FileSystemEvent> watch({ int? events = 15, bool? recursive = false, }) => (super.noSuchMethod( Invocation.method( #watch, [], { #events: events, #recursive: recursive, }, ), returnValue: _i3.Stream<_i2.FileSystemEvent>.empty(), ) as _i3.Stream<_i2.FileSystemEvent>); }
0
mirrored_repositories/study_savvy_app/test
mirrored_repositories/study_savvy_app/test/class/file_test.dart
import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'package:study_savvy_app/models/files/model_files.dart'; import 'file_test.mocks.dart'; @GenerateMocks([File]) void main() { group('File', () { test('File object value test', () { const String testId= 'Test id'; const String testType = 'Test type'; const String testStatus = 'Test status'; const String testTime = 'Test time'; final file = File(testId,testType,testStatus,testTime); expect(file.id, testId); expect(file.type, testType); expect(file.status, testStatus); expect(file.time, testTime); }); }); group('Files', () { test('Files object value test (num of files 1000)', () { List<MockFile> mockFiles = List<MockFile>.generate(1000, (index) { var mockFile = MockFile(); when(mockFile.id).thenReturn('Test id $index'); when(mockFile.type).thenReturn('Test type $index'); when(mockFile.status).thenReturn('Test status $index'); when(mockFile.time).thenReturn('Test time $index'); return mockFile; }); const int testCurrentPage=2; const int testTotalPage=5; final files = Files(mockFiles,testCurrentPage,testTotalPage); for (int i = 0; i < mockFiles.length; i++) { expect(files.files[i].id, 'Test id $i'); expect(files.files[i].type, 'Test type $i'); expect(files.files[i].status, 'Test status $i'); expect(files.files[i].time, 'Test time $i'); } expect(files.currentPage, testCurrentPage); expect(files.totalPages, testTotalPage); }); test('Files object value test (num of files 10)', () { List<MockFile> mockFiles = List<MockFile>.generate(10, (index) { var mockFile = MockFile(); when(mockFile.id).thenReturn('Test id $index'); when(mockFile.type).thenReturn('Test type $index'); when(mockFile.status).thenReturn('Test status $index'); when(mockFile.time).thenReturn('Test time $index'); return mockFile; }); const int testCurrentPage=2; const int testTotalPage=5; final files = Files(mockFiles,testCurrentPage,testTotalPage); for (int i = 0; i < mockFiles.length; i++) { expect(files.files[i].id, 'Test id $i'); expect(files.files[i].type, 'Test type $i'); expect(files.files[i].status, 'Test status $i'); expect(files.files[i].time, 'Test time $i'); } expect(files.currentPage, testCurrentPage); expect(files.totalPages, testTotalPage); }); test('Files object value test (num of files 0)', () { List<MockFile> mockFiles = List<MockFile>.generate(0, (index) { var mockFile = MockFile(); when(mockFile.id).thenReturn('Test id $index'); when(mockFile.type).thenReturn('Test type $index'); when(mockFile.status).thenReturn('Test status $index'); when(mockFile.time).thenReturn('Test time $index'); return mockFile; }); const int testCurrentPage=2; const int testTotalPage=5; final files = Files(mockFiles,testCurrentPage,testTotalPage); for (int i = 0; i < mockFiles.length; i++) { expect(files.files[i].id, 'Test id $i'); expect(files.files[i].type, 'Test type $i'); expect(files.files[i].status, 'Test status $i'); expect(files.files[i].time, 'Test time $i'); } expect(files.currentPage, testCurrentPage); expect(files.totalPages, testTotalPage); }); test('Files object fromJson method test (num of files 10)', () { List<Map<String,String>> testFiles = List<Map<String,String>>.generate(10, (index) { var map={'file_id': 'Test id $index', 'file_type': 'Test type $index', 'status': 'Test status $index', 'file_time': 'Test time $index'}; return map; }); const int testCurrentPage=2; const int testTotalPage=5; var testJson={ 'datas':testFiles, 'current_page':testCurrentPage, 'total_pages': testTotalPage, }; final files = Files.fromJson(testJson); for (int i = 0; i < files.files.length; i++) { expect(files.files[i].id, 'Test id $i'); expect(files.files[i].type, 'Test type $i'); expect(files.files[i].status, 'Test status $i'); expect(files.files[i].time, 'Test time $i'); } expect(files.currentPage, testCurrentPage); expect(files.totalPages, testTotalPage); }); }); group('SpecificFile', () { test('SpecificFiles object value test (num of files 1000)', () { List<String> testDetails = List<String>.generate(1000, (index) { return "Test $index"; }); const String testContent="Test content"; const String testPrompt="Test prompt"; const String testSummarize="Test summarize"; final specificFile = SpecificFile(testContent,testPrompt,testSummarize,testDetails); for (int i = 0; i < specificFile.details.length; i++) { expect(specificFile.details[i], "Test $i"); } expect(specificFile.content,testContent); expect(specificFile.prompt,testPrompt); expect(specificFile.summarize,testSummarize); }); test('SpecificFiles object value test (num of files 10)', () { List<String> testDetails = List<String>.generate(10, (index) { return "Test $index"; }); const String testContent="Test content"; const String testPrompt="Test prompt"; const String testSummarize="Test summarize"; final specificFile = SpecificFile(testContent,testPrompt,testSummarize,testDetails); for (int i = 0; i < specificFile.details.length; i++) { expect(specificFile.details[i], "Test $i"); } expect(specificFile.content,testContent); expect(specificFile.prompt,testPrompt); expect(specificFile.summarize,testSummarize); }); test('SpecificFiles object value test (num of files 0)', () { List<String> testDetails = List<String>.generate(0, (index) { return "Test $index"; }); const String testContent="Test content"; const String testPrompt="Test prompt"; const String testSummarize="Test summarize"; final specificFile = SpecificFile(testContent,testPrompt,testSummarize,testDetails); for (int i = 0; i < specificFile.details.length; i++) { expect(specificFile.details[i], "Test $i"); } expect(specificFile.content,testContent); expect(specificFile.prompt,testPrompt); expect(specificFile.summarize,testSummarize); }); test('SpecificFiles object fromJson method test (num of files 10)', () { List<String> testDetails = List<String>.generate(10, (index) { return "Test $index"; }); const String testContent="Test content"; const String testPrompt="Test prompt"; const String testSummarize="Test summarize"; var testJson={ 'content': testContent, 'prompt': testPrompt, 'summarize': testSummarize, 'details': testDetails }; final specificFiles = SpecificFile.fromJson(testJson); for (int i = 0; i < specificFiles.details.length; i++) { expect(specificFiles.details[i], 'Test $i'); } expect(specificFiles.content, testContent); expect(specificFiles.prompt, testPrompt); expect(specificFiles.summarize, testSummarize); }); }); group('EditFile', () { test('EditFile object value test', () { const String testId="Test id"; const String testContent="Test content"; const String testPrompt="Test prompt"; final editFile = EditFile(testId, testPrompt, testContent); expect(editFile.id,testId); expect(editFile.content,testContent); expect(editFile.prompt,testPrompt); }); test('EditFile object formatJson method test', () { const String testId="Test id"; const String testContent="Test content"; const String testPrompt="Test prompt"; final editFile = EditFile(testId, testPrompt, testContent); expect(editFile.formatJson(), {'prompt': testPrompt, 'content': testContent}); }); }); }
0
mirrored_repositories/study_savvy_app/test
mirrored_repositories/study_savvy_app/test/class/file_test.mocks.dart
// Mocks generated by Mockito 5.4.2 from annotations // in study_savvy_app/test/class/file_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'package:mockito/mockito.dart' as _i1; import 'package:study_savvy_app/models/files/model_files.dart' as _i2; // 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 /// A class which mocks [File]. /// /// See the documentation for Mockito's code generation for more information. class MockFile extends _i1.Mock implements _i2.File { MockFile() { _i1.throwOnMissingStub(this); } @override String get id => (super.noSuchMethod( Invocation.getter(#id), returnValue: '', ) as String); @override String get time => (super.noSuchMethod( Invocation.getter(#time), returnValue: '', ) as String); @override String get status => (super.noSuchMethod( Invocation.getter(#status), returnValue: '', ) as String); @override String get type => (super.noSuchMethod( Invocation.getter(#type), returnValue: '', ) as String); }
0
mirrored_repositories/study_savvy_app/test
mirrored_repositories/study_savvy_app/test/class/article_improver_test.dart
import 'dart:io'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'package:study_savvy_app/models/article_improver/model_article_improver.dart'; import 'package:test/test.dart'; import 'article_improver_test.mocks.dart'; @GenerateMocks([File]) void main() { group('ArticleImage', () { test('ArticleImage object value test', () { final file = MockFile(); when(file.path).thenReturn('mocked_path'); File testImage = file; const String testPrompt = 'Test prompt'; final articleImage = ArticleImage(testImage, testPrompt); expect(articleImage.image, testImage); expect(articleImage.prompt, testPrompt); }); }); group('ArticleText', () { test('ArticleText object value test', () { const String testContent = 'Test content'; const String testPrompt = 'Test prompt'; final articleText = ArticleText(testContent,testPrompt); expect(articleText.content, testContent); expect(articleText.prompt, testPrompt); }); test('ArticleText object formatJson method test', () { const String testContent = 'Test content'; const String testPrompt = 'Test prompt'; final articleText = ArticleText(testContent,testPrompt); expect(articleText.formatJson(), {'content': testContent, 'prompt': testPrompt}); }); }); }
0
mirrored_repositories/study_savvy_app/test
mirrored_repositories/study_savvy_app/test/class/profile_test.dart
import 'package:flutter_test/flutter_test.dart'; import 'package:study_savvy_app/models/profile/model_profile.dart'; void main(){ group('Profile', () { test('Profile object value test', () { const String testName= 'Test name'; const String testMail = 'Test mail'; const String testGender = 'Test gender'; final profile = Profile(testName,testMail,testGender); expect(profile.name, testName); expect(profile.mail, testMail); expect(profile.gender, testGender); }); test('Profile object fromJson method test', () { const String testName= 'Test name'; const String testMail = 'Test mail'; const String testGender = 'Test gender'; var testJson={ "name":testName, "mail":testMail, "gender":testGender }; final profile = Profile.fromJson(testJson); expect(profile.name, testName); expect(profile.mail, testMail); expect(profile.gender, testGender); }); }); group('UpdateProfile', () { test('UpdateProfile object value test', () { const String testName= 'Test name'; const String testGender = 'Test gender'; final updateProfile = UpdateProfile(testName,testGender); expect(updateProfile.name, testName); expect(updateProfile.gender, testGender); }); }); group('UpdatePwd', () { test('UpdatePwd object value test', () { const String testOldPwd= 'Test oldPwd'; const String testNewPwd = 'Test newPwd'; final updatePwd = UpdatePwd(testOldPwd, testNewPwd); expect(updatePwd.currentPassword, testOldPwd); expect(updatePwd.EditPassword, testNewPwd); }); test('UpdatePwd object formatJson method test', () { const String testOldPwd= 'Test oldPwd'; const String testNewPwd = 'Test newPwd'; final updatePwd = UpdatePwd(testOldPwd, testNewPwd); expect(updatePwd.formatJson(),{"original_pwd":testOldPwd,"new_pwd":testNewPwd}); }); }); group('AIMethods', () { test('AIMethods object value test', () { const String testToken= 'Test token'; final updateProfile = AIMethods(testToken); expect(updateProfile.token,testToken); }); }); group('SecureData', () { test('SecureData object value test', () { const String testData= 'Test data'; const String testKey = 'Test key'; final secureData=SecureData(testData, testKey); expect(secureData.data,testData); expect(secureData.key,testKey); }); test('SecureData object formatAccessToken method test', () { const String testData= 'Test data'; const String testKey = 'Test key'; final secureData=SecureData(testData, testKey); expect(secureData.formatAccessToken(),{"AES_key":testKey,"access_token":testData}); }); test('SecureData object formatApiKey method test', () { const String testData= 'Test data'; const String testKey = 'Test key'; final secureData=SecureData(testData, testKey); expect(secureData.formatApiKey(),{"AES_key":testKey,"api_key":testData}); }); }); }
0
mirrored_repositories/study_savvy_app/test
mirrored_repositories/study_savvy_app/test/widget/failure_test.dart
import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:study_savvy_app/widgets/failure.dart'; void main(){ testWidgets('Failure-widget test', (WidgetTester tester) async{ const String errorString="Error test"; await tester.pumpWidget(const MaterialApp(home:Failure(error:errorString))); expect(find.byType(Failure), findsOneWidget); expect(find.text(errorString), findsOneWidget); }); }
0
mirrored_repositories/study_savvy_app/test
mirrored_repositories/study_savvy_app/test/widget/navigate_test.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:provider/provider.dart'; import 'package:study_savvy_app/blocs/profile/bloc_access_methods.dart'; import 'package:study_savvy_app/blocs/article_improver/bloc_article_improver.dart'; import 'package:study_savvy_app/blocs/files/bloc_files.dart'; import 'package:study_savvy_app/blocs/utils/bloc_jwt.dart'; import 'package:study_savvy_app/blocs/utils/bloc_navigator.dart'; import 'package:study_savvy_app/blocs/profile/bloc_online.dart'; import 'package:study_savvy_app/blocs/profile/bloc_password.dart'; import 'package:study_savvy_app/blocs/profile/bloc_profile.dart'; import 'package:study_savvy_app/blocs/files/bloc_specific_file.dart'; import 'package:study_savvy_app/blocs/provider/ocr_image_provider.dart'; import 'package:study_savvy_app/blocs/provider/theme_provider.dart'; import 'package:study_savvy_app/screens/article_improver/article_improver.dart'; import 'package:study_savvy_app/screens/files/files.dart'; import 'package:study_savvy_app/screens/home.dart'; import 'package:study_savvy_app/screens/profile/profile.dart'; import 'package:study_savvy_app/widgets/custom_navigate.dart'; void main(){ testWidgets('Bottom-navigator test', (WidgetTester tester) async { await tester.pumpWidget(MultiProvider( providers: [ ChangeNotifierProvider( create: (_) => ThemeProvider(), ), ChangeNotifierProvider( create: (_) => OCRImageProvider(), ), BlocProvider( create: (context) => PageBloc(), ), BlocProvider( create: (context) => JWTBloc(), ), BlocProvider( create: (context) => FileBloc(), ), BlocProvider( create: (context) => FilesBloc(), ), BlocProvider( create: (context) => ProfileBloc(), ), BlocProvider( create: (context) => AccessMethodBloc(), ), BlocProvider( create: (context) => ArticleBloc(), ), BlocProvider( create: (context) => PasswordBloc(), ), BlocProvider( create: (context) => OnlineBloc(), ) ], child: const MaterialApp( home:MenuHome() ), )); expect(find.byType(MenuHome),findsOneWidget); expect(find.byType(CustomNavigate),findsOneWidget); await tester.tap(find.byIcon(Icons.feed_outlined)); await tester.pump(); // Replace for audio page expect(find.byType(ArticleImproverPage),findsNothing); expect(find.byType(FilesPage),findsNothing); expect(find.byType(ProfilePage),findsNothing); await tester.tap(find.byIcon(Icons.mode_edit_outline_outlined)); await tester.pump(); // Replace for audio page expect(find.byType(ArticleImproverPage),findsOneWidget); expect(find.byType(FilesPage),findsNothing); expect(find.byType(ProfilePage),findsNothing); await tester.tap(find.byIcon(Icons.access_time)); await tester.pump(); // Replace for audio page expect(find.byType(ArticleImproverPage),findsNothing); expect(find.byType(FilesPage),findsOneWidget); expect(find.byType(ProfilePage),findsNothing); await tester.tap(find.byIcon(Icons.person)); await tester.pump(); // Replace for audio page expect(find.byType(ArticleImproverPage),findsNothing); expect(find.byType(FilesPage),findsNothing); expect(find.byType(ProfilePage),findsOneWidget); }); }
0
mirrored_repositories/study_savvy_app/test
mirrored_repositories/study_savvy_app/test/widget/loading_test.dart
import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:study_savvy_app/widgets/loading.dart'; void main(){ testWidgets('Loading-widget test', (WidgetTester tester) async{ await tester.pumpWidget(const MaterialApp(home:Loading())); expect(find.byType(Loading), findsOneWidget); }); }
0
mirrored_repositories/study_savvy_app/test
mirrored_repositories/study_savvy_app/test/widget/success_test.dart
import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:study_savvy_app/widgets/success.dart'; void main(){ testWidgets('Success-widget test', (WidgetTester tester) async{ const String successString="Success test"; await tester.pumpWidget(const MaterialApp(home:Success(message: successString,))); expect(find.byType(Success), findsOneWidget); expect(find.text(successString), findsOneWidget); }); }
0
mirrored_repositories/study_savvy_app/test/api
mirrored_repositories/study_savvy_app/test/api/put/set_access_token_test.mocks.dart
// Mocks generated by Mockito 5.4.2 from annotations // in study_savvy_app/test/api/put/set_access_token_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i4; import 'dart:convert' as _i5; import 'dart:typed_data' as _i6; import 'package:http/http.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; import 'package:study_savvy_app/services/utils/jwt_storage.dart' as _i3; // 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 _FakeResponse_0 extends _i1.SmartFake implements _i2.Response { _FakeResponse_0( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeStreamedResponse_1 extends _i1.SmartFake implements _i2.StreamedResponse { _FakeStreamedResponse_1( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } /// A class which mocks [JwtService]. /// /// See the documentation for Mockito's code generation for more information. class MockJwtService extends _i1.Mock implements _i3.JwtService { MockJwtService() { _i1.throwOnMissingStub(this); } @override _i4.Future<void> saveJwt(String? jwt) => (super.noSuchMethod( Invocation.method( #saveJwt, [jwt], ), returnValue: _i4.Future<void>.value(), returnValueForMissingStub: _i4.Future<void>.value(), ) as _i4.Future<void>); @override _i4.Future<String?> getJwt() => (super.noSuchMethod( Invocation.method( #getJwt, [], ), returnValue: _i4.Future<String?>.value(), ) as _i4.Future<String?>); @override _i4.Future<void> deleteJwt() => (super.noSuchMethod( Invocation.method( #deleteJwt, [], ), returnValue: _i4.Future<void>.value(), returnValueForMissingStub: _i4.Future<void>.value(), ) as _i4.Future<void>); @override _i4.Future<bool?> hasJwt() => (super.noSuchMethod( Invocation.method( #hasJwt, [], ), returnValue: _i4.Future<bool?>.value(), ) as _i4.Future<bool?>); } /// A class which mocks [Client]. /// /// See the documentation for Mockito's code generation for more information. class MockClient extends _i1.Mock implements _i2.Client { MockClient() { _i1.throwOnMissingStub(this); } @override _i4.Future<_i2.Response> head( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #head, [url], {#headers: headers}, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #head, [url], {#headers: headers}, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> get( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #get, [url], {#headers: headers}, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #get, [url], {#headers: headers}, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> post( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #post, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #post, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> put( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #put, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #put, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> patch( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #patch, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #patch, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> delete( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #delete, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #delete, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<String> read( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #read, [url], {#headers: headers}, ), returnValue: _i4.Future<String>.value(''), ) as _i4.Future<String>); @override _i4.Future<_i6.Uint8List> readBytes( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #readBytes, [url], {#headers: headers}, ), returnValue: _i4.Future<_i6.Uint8List>.value(_i6.Uint8List(0)), ) as _i4.Future<_i6.Uint8List>); @override _i4.Future<_i2.StreamedResponse> send(_i2.BaseRequest? request) => (super.noSuchMethod( Invocation.method( #send, [request], ), returnValue: _i4.Future<_i2.StreamedResponse>.value(_FakeStreamedResponse_1( this, Invocation.method( #send, [request], ), )), ) as _i4.Future<_i2.StreamedResponse>); @override void close() => super.noSuchMethod( Invocation.method( #close, [], ), returnValueForMissingStub: null, ); }
0
mirrored_repositories/study_savvy_app/test/api
mirrored_repositories/study_savvy_app/test/api/put/edit_specific_file_asr_test.dart
import 'dart:convert'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:http/http.dart' as http; import 'package:mockito/mockito.dart'; import 'package:study_savvy_app/models/files/model_files.dart'; import 'package:study_savvy_app/services/files/api_files.dart'; import 'package:study_savvy_app/services/api_routes.dart'; import 'package:study_savvy_app/services/utils/jwt_storage.dart'; import 'package:study_savvy_app/utils/exception.dart'; import 'edit_specific_file_asr_test.mocks.dart'; @GenerateMocks([JwtService, http.Client]) void main() { group('editSpecificFileASR', () { test('editSpecificFileASR', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testId="Test id"; const String testJwt="Test jwt"; const String testContent="Test content"; const String testPrompt="Test prompt"; final EditFile testEditFile=EditFile(testId, testPrompt, testContent); final url = Uri.parse("${ApiRoutes.fileNlpEditASRUrl}/$testId"); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testEditFile.formatJson()))).thenAnswer((_) async => http.Response('', 200),); final FilesService apiService = FilesService(jwtService: jwtService, httpClient: httpClient); await apiService.editSpecificFileASR(testEditFile); verify(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testEditFile.formatJson()))).called(1); }); test('editSpecificFileASR throws ClientException', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testId="Test id"; const String testJwt="Test jwt"; const String testContent="Test content"; const String testPrompt="Test prompt"; final EditFile testEditFile=EditFile(testId, testPrompt, testContent); final url = Uri.parse("${ApiRoutes.fileNlpEditASRUrl}/$testId"); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testEditFile.formatJson()))).thenAnswer((_) async => http.Response('', 400),); final FilesService apiService = FilesService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.editSpecificFileASR(testEditFile), throwsA(isA<ClientException>())); await untilCalled(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testEditFile.formatJson()))); verify(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testEditFile.formatJson()))).called(1); }); test('editSpecificFileASR throws ExistException', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testId="Test id"; const String testJwt="Test jwt"; const String testContent="Test content"; const String testPrompt="Test prompt"; final EditFile testEditFile=EditFile(testId, testPrompt, testContent); final url = Uri.parse("${ApiRoutes.fileNlpEditASRUrl}/$testId"); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testEditFile.formatJson()))).thenAnswer((_) async => http.Response('', 404),); final FilesService apiService = FilesService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.editSpecificFileASR(testEditFile), throwsA(isA<ExistException>())); await untilCalled(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testEditFile.formatJson()))); verify(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testEditFile.formatJson()))).called(1); }); test('editSpecificFileASR throws AuthException', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testId="Test id"; const String testJwt="Test jwt"; const String testContent="Test content"; const String testPrompt="Test prompt"; final EditFile testEditFile=EditFile(testId, testPrompt, testContent); final url = Uri.parse("${ApiRoutes.fileNlpEditASRUrl}/$testId"); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testEditFile.formatJson()))).thenAnswer((_) async => http.Response('', 422),); final FilesService apiService = FilesService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.editSpecificFileASR(testEditFile), throwsA(isA<AuthException>())); await untilCalled(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testEditFile.formatJson()))); verify(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testEditFile.formatJson()))).called(1); await untilCalled(jwtService.deleteJwt()); verify(jwtService.deleteJwt()).called(1); }); test('editSpecificFileASR throws ServerException', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testId="Test id"; const String testJwt="Test jwt"; const String testContent="Test content"; const String testPrompt="Test prompt"; final EditFile testEditFile=EditFile(testId, testPrompt, testContent); final url = Uri.parse("${ApiRoutes.fileNlpEditASRUrl}/$testId"); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testEditFile.formatJson()))).thenAnswer( (_) async => http.Response('', 500), ); final FilesService apiService = FilesService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.editSpecificFileASR(testEditFile), throwsA(isA<ServerException>())); await untilCalled(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testEditFile.formatJson()))); verify(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testEditFile.formatJson()))).called(1); }); test('editSpecificFileASR throws Other Exception', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testId="Test id"; const String testJwt="Test jwt"; const String testContent="Test content"; const String testPrompt="Test prompt"; final EditFile testEditFile=EditFile(testId, testPrompt, testContent); final url = Uri.parse("${ApiRoutes.fileNlpEditASRUrl}/$testId"); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testEditFile.formatJson()))).thenAnswer( (_) async => http.Response('', 555), ); final FilesService apiService = FilesService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.editSpecificFileASR(testEditFile), throwsA(isA<Exception>())); await untilCalled(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testEditFile.formatJson()))); verify(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testEditFile.formatJson()))).called(1); }); test('editSpecificFileASR throws AuthException(Jwt is null)', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testId="Test id"; const String testContent="Test content"; const String testPrompt="Test prompt"; final EditFile testEditFile=EditFile(testId, testPrompt, testContent); when(jwtService.getJwt()).thenAnswer((_) async => null); final FilesService apiService = FilesService(jwtService: jwtService, httpClient: httpClient); expect(apiService.editSpecificFileASR(testEditFile), throwsA(isA<AuthException>())); }); }); }
0
mirrored_repositories/study_savvy_app/test/api
mirrored_repositories/study_savvy_app/test/api/put/edit_specific_file_asr_test.mocks.dart
// Mocks generated by Mockito 5.4.2 from annotations // in study_savvy_app/test/api/put/edit_specific_file_asr_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i4; import 'dart:convert' as _i5; import 'dart:typed_data' as _i6; import 'package:http/http.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; import 'package:study_savvy_app/services/utils/jwt_storage.dart' as _i3; // 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 _FakeResponse_0 extends _i1.SmartFake implements _i2.Response { _FakeResponse_0( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeStreamedResponse_1 extends _i1.SmartFake implements _i2.StreamedResponse { _FakeStreamedResponse_1( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } /// A class which mocks [JwtService]. /// /// See the documentation for Mockito's code generation for more information. class MockJwtService extends _i1.Mock implements _i3.JwtService { MockJwtService() { _i1.throwOnMissingStub(this); } @override _i4.Future<void> saveJwt(String? jwt) => (super.noSuchMethod( Invocation.method( #saveJwt, [jwt], ), returnValue: _i4.Future<void>.value(), returnValueForMissingStub: _i4.Future<void>.value(), ) as _i4.Future<void>); @override _i4.Future<String?> getJwt() => (super.noSuchMethod( Invocation.method( #getJwt, [], ), returnValue: _i4.Future<String?>.value(), ) as _i4.Future<String?>); @override _i4.Future<void> deleteJwt() => (super.noSuchMethod( Invocation.method( #deleteJwt, [], ), returnValue: _i4.Future<void>.value(), returnValueForMissingStub: _i4.Future<void>.value(), ) as _i4.Future<void>); @override _i4.Future<bool?> hasJwt() => (super.noSuchMethod( Invocation.method( #hasJwt, [], ), returnValue: _i4.Future<bool?>.value(), ) as _i4.Future<bool?>); } /// A class which mocks [Client]. /// /// See the documentation for Mockito's code generation for more information. class MockClient extends _i1.Mock implements _i2.Client { MockClient() { _i1.throwOnMissingStub(this); } @override _i4.Future<_i2.Response> head( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #head, [url], {#headers: headers}, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #head, [url], {#headers: headers}, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> get( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #get, [url], {#headers: headers}, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #get, [url], {#headers: headers}, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> post( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #post, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #post, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> put( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #put, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #put, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> patch( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #patch, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #patch, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> delete( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #delete, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #delete, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<String> read( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #read, [url], {#headers: headers}, ), returnValue: _i4.Future<String>.value(''), ) as _i4.Future<String>); @override _i4.Future<_i6.Uint8List> readBytes( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #readBytes, [url], {#headers: headers}, ), returnValue: _i4.Future<_i6.Uint8List>.value(_i6.Uint8List(0)), ) as _i4.Future<_i6.Uint8List>); @override _i4.Future<_i2.StreamedResponse> send(_i2.BaseRequest? request) => (super.noSuchMethod( Invocation.method( #send, [request], ), returnValue: _i4.Future<_i2.StreamedResponse>.value(_FakeStreamedResponse_1( this, Invocation.method( #send, [request], ), )), ) as _i4.Future<_i2.StreamedResponse>); @override void close() => super.noSuchMethod( Invocation.method( #close, [], ), returnValueForMissingStub: null, ); }
0
mirrored_repositories/study_savvy_app/test/api
mirrored_repositories/study_savvy_app/test/api/put/set_api_key_test.mocks.dart
// Mocks generated by Mockito 5.4.2 from annotations // in study_savvy_app/test/api/put/set_api_key_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i4; import 'dart:convert' as _i5; import 'dart:typed_data' as _i6; import 'package:http/http.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; import 'package:study_savvy_app/services/utils/jwt_storage.dart' as _i3; // 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 _FakeResponse_0 extends _i1.SmartFake implements _i2.Response { _FakeResponse_0( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeStreamedResponse_1 extends _i1.SmartFake implements _i2.StreamedResponse { _FakeStreamedResponse_1( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } /// A class which mocks [JwtService]. /// /// See the documentation for Mockito's code generation for more information. class MockJwtService extends _i1.Mock implements _i3.JwtService { MockJwtService() { _i1.throwOnMissingStub(this); } @override _i4.Future<void> saveJwt(String? jwt) => (super.noSuchMethod( Invocation.method( #saveJwt, [jwt], ), returnValue: _i4.Future<void>.value(), returnValueForMissingStub: _i4.Future<void>.value(), ) as _i4.Future<void>); @override _i4.Future<String?> getJwt() => (super.noSuchMethod( Invocation.method( #getJwt, [], ), returnValue: _i4.Future<String?>.value(), ) as _i4.Future<String?>); @override _i4.Future<void> deleteJwt() => (super.noSuchMethod( Invocation.method( #deleteJwt, [], ), returnValue: _i4.Future<void>.value(), returnValueForMissingStub: _i4.Future<void>.value(), ) as _i4.Future<void>); @override _i4.Future<bool?> hasJwt() => (super.noSuchMethod( Invocation.method( #hasJwt, [], ), returnValue: _i4.Future<bool?>.value(), ) as _i4.Future<bool?>); } /// A class which mocks [Client]. /// /// See the documentation for Mockito's code generation for more information. class MockClient extends _i1.Mock implements _i2.Client { MockClient() { _i1.throwOnMissingStub(this); } @override _i4.Future<_i2.Response> head( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #head, [url], {#headers: headers}, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #head, [url], {#headers: headers}, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> get( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #get, [url], {#headers: headers}, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #get, [url], {#headers: headers}, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> post( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #post, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #post, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> put( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #put, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #put, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> patch( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #patch, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #patch, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> delete( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #delete, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #delete, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<String> read( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #read, [url], {#headers: headers}, ), returnValue: _i4.Future<String>.value(''), ) as _i4.Future<String>); @override _i4.Future<_i6.Uint8List> readBytes( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #readBytes, [url], {#headers: headers}, ), returnValue: _i4.Future<_i6.Uint8List>.value(_i6.Uint8List(0)), ) as _i4.Future<_i6.Uint8List>); @override _i4.Future<_i2.StreamedResponse> send(_i2.BaseRequest? request) => (super.noSuchMethod( Invocation.method( #send, [request], ), returnValue: _i4.Future<_i2.StreamedResponse>.value(_FakeStreamedResponse_1( this, Invocation.method( #send, [request], ), )), ) as _i4.Future<_i2.StreamedResponse>); @override void close() => super.noSuchMethod( Invocation.method( #close, [], ), returnValueForMissingStub: null, ); }
0
mirrored_repositories/study_savvy_app/test/api
mirrored_repositories/study_savvy_app/test/api/put/reset_password_test.dart
import 'dart:convert'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:http/http.dart' as http; import 'package:mockito/mockito.dart'; import 'package:study_savvy_app/models/profile/model_profile.dart'; import 'package:study_savvy_app/services/profile/api_profile.dart'; import 'package:study_savvy_app/services/api_routes.dart'; import 'package:study_savvy_app/services/utils/jwt_storage.dart'; import 'package:study_savvy_app/utils/exception.dart'; import 'reset_password_test.mocks.dart'; @GenerateMocks([JwtService, http.Client]) void main() { group('resetPassword', () { test('resetPassword', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testJwt="Test jwt"; const String testOldPwd="Test oldPwd"; const String testNewPwd="Test newPwd"; final UpdatePwd testUpdatePwd=UpdatePwd(testOldPwd,testNewPwd); final url = Uri.parse(ApiRoutes.passwordEditUrl); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testUpdatePwd.formatJson()))).thenAnswer((_) async => http.Response('', 200),); final ProfileService apiService = ProfileService(jwtService: jwtService, httpClient: httpClient); await apiService.resetPassword(testUpdatePwd); verify(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testUpdatePwd.formatJson()))).called(1); }); test('resetPassword throws ClientException', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testJwt="Test jwt"; const String testOldPwd="Test oldPwd"; const String testNewPwd="Test newPwd"; final UpdatePwd testUpdatePwd=UpdatePwd(testOldPwd,testNewPwd); final url = Uri.parse(ApiRoutes.passwordEditUrl); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testUpdatePwd.formatJson()))).thenAnswer((_) async => http.Response('', 400),); final ProfileService apiService = ProfileService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.resetPassword(testUpdatePwd), throwsA(isA<ClientException>())); await untilCalled(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testUpdatePwd.formatJson()))); verify(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testUpdatePwd.formatJson()))).called(1); }); test('resetPassword throws ExistException', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testJwt="Test jwt"; const String testOldPwd="Test oldPwd"; const String testNewPwd="Test newPwd"; final UpdatePwd testUpdatePwd=UpdatePwd(testOldPwd,testNewPwd); final url = Uri.parse(ApiRoutes.passwordEditUrl); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testUpdatePwd.formatJson()))).thenAnswer((_) async => http.Response('', 404),); final ProfileService apiService = ProfileService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.resetPassword(testUpdatePwd), throwsA(isA<ExistException>())); await untilCalled(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testUpdatePwd.formatJson()))); verify(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testUpdatePwd.formatJson()))).called(1); }); test('resetPassword throws AuthException', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testJwt="Test jwt"; const String testOldPwd="Test oldPwd"; const String testNewPwd="Test newPwd"; final UpdatePwd testUpdatePwd=UpdatePwd(testOldPwd,testNewPwd); final url = Uri.parse(ApiRoutes.passwordEditUrl); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testUpdatePwd.formatJson()))).thenAnswer((_) async => http.Response('', 422),); final ProfileService apiService = ProfileService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.resetPassword(testUpdatePwd), throwsA(isA<AuthException>())); await untilCalled(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testUpdatePwd.formatJson()))); verify(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testUpdatePwd.formatJson()))).called(1); await untilCalled(jwtService.deleteJwt()); verify(jwtService.deleteJwt()).called(1); }); test('resetPassword throws ServerException', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testJwt="Test jwt"; const String testOldPwd="Test oldPwd"; const String testNewPwd="Test newPwd"; final UpdatePwd testUpdatePwd=UpdatePwd(testOldPwd,testNewPwd); final url = Uri.parse(ApiRoutes.passwordEditUrl); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testUpdatePwd.formatJson()))).thenAnswer( (_) async => http.Response('', 500), ); final ProfileService apiService = ProfileService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.resetPassword(testUpdatePwd), throwsA(isA<ServerException>())); await untilCalled(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testUpdatePwd.formatJson()))); verify(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testUpdatePwd.formatJson()))).called(1); }); test('resetPassword throws Other Exception', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testJwt="Test jwt"; const String testOldPwd="Test oldPwd"; const String testNewPwd="Test newPwd"; final UpdatePwd testUpdatePwd=UpdatePwd(testOldPwd,testNewPwd); final url = Uri.parse(ApiRoutes.passwordEditUrl); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testUpdatePwd.formatJson()))).thenAnswer( (_) async => http.Response('', 555), ); final ProfileService apiService = ProfileService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.resetPassword(testUpdatePwd), throwsA(isA<Exception>())); await untilCalled(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testUpdatePwd.formatJson()))); verify(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testUpdatePwd.formatJson()))).called(1); }); test('resetPassword throws AuthException(Jwt is null)', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testOldPwd="Test oldPwd"; const String testNewPwd="Test newPwd"; final UpdatePwd testUpdatePwd=UpdatePwd(testOldPwd,testNewPwd); when(jwtService.getJwt()).thenAnswer((_) async => null); final ProfileService apiService = ProfileService(jwtService: jwtService, httpClient: httpClient); expect(apiService.resetPassword(testUpdatePwd), throwsA(isA<AuthException>())); }); }); }
0
mirrored_repositories/study_savvy_app/test/api
mirrored_repositories/study_savvy_app/test/api/put/edit_specific_file_ocr_test.dart
import 'dart:convert'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:http/http.dart' as http; import 'package:mockito/mockito.dart'; import 'package:study_savvy_app/models/files/model_files.dart'; import 'package:study_savvy_app/services/files/api_files.dart'; import 'package:study_savvy_app/services/api_routes.dart'; import 'package:study_savvy_app/services/utils/jwt_storage.dart'; import 'package:study_savvy_app/utils/exception.dart'; import 'edit_specific_file_OCR_test.mocks.dart'; @GenerateMocks([JwtService, http.Client]) void main() { group('editSpecificFileOCR', () { test('editSpecificFileOCR', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testId="Test id"; const String testJwt="Test jwt"; const String testContent="Test content"; const String testPrompt="Test prompt"; final EditFile testEditFile=EditFile(testId, testPrompt, testContent); final url = Uri.parse("${ApiRoutes.fileNlpEditOCRUrl}/$testId"); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testEditFile.formatJson()))).thenAnswer((_) async => http.Response('', 200),); final FilesService apiService = FilesService(jwtService: jwtService,httpClient: httpClient); await apiService.editSpecificFileOCR(testEditFile); verify(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testEditFile.formatJson()))).called(1); }); test('editSpecificFileOCR throws ClientException', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testId="Test id"; const String testJwt="Test jwt"; const String testContent="Test content"; const String testPrompt="Test prompt"; final EditFile testEditFile=EditFile(testId, testPrompt, testContent); final url = Uri.parse("${ApiRoutes.fileNlpEditOCRUrl}/$testId"); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testEditFile.formatJson()))).thenAnswer((_) async => http.Response('', 400),); final FilesService apiService = FilesService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.editSpecificFileOCR(testEditFile), throwsA(isA<ClientException>())); await untilCalled(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testEditFile.formatJson()))); verify(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testEditFile.formatJson()))).called(1); }); test('editSpecificFileOCR throws ExistException', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testId="Test id"; const String testJwt="Test jwt"; const String testContent="Test content"; const String testPrompt="Test prompt"; final EditFile testEditFile=EditFile(testId, testPrompt, testContent); final url = Uri.parse("${ApiRoutes.fileNlpEditOCRUrl}/$testId"); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testEditFile.formatJson()))).thenAnswer((_) async => http.Response('', 404),); final FilesService apiService = FilesService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.editSpecificFileOCR(testEditFile), throwsA(isA<ExistException>())); await untilCalled(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testEditFile.formatJson()))); verify(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testEditFile.formatJson()))).called(1); }); test('editSpecificFileOCR throws AuthException', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testId="Test id"; const String testJwt="Test jwt"; const String testContent="Test content"; const String testPrompt="Test prompt"; final EditFile testEditFile=EditFile(testId, testPrompt, testContent); final url = Uri.parse("${ApiRoutes.fileNlpEditOCRUrl}/$testId"); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testEditFile.formatJson()))).thenAnswer((_) async => http.Response('', 422),); final FilesService apiService = FilesService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.editSpecificFileOCR(testEditFile), throwsA(isA<AuthException>())); await untilCalled(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testEditFile.formatJson()))); verify(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testEditFile.formatJson()))).called(1); await untilCalled(jwtService.deleteJwt()); verify(jwtService.deleteJwt()).called(1); }); test('editSpecificFileOCR throws ServerException', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testId="Test id"; const String testJwt="Test jwt"; const String testContent="Test content"; const String testPrompt="Test prompt"; final EditFile testEditFile=EditFile(testId, testPrompt, testContent); final url = Uri.parse("${ApiRoutes.fileNlpEditOCRUrl}/$testId"); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testEditFile.formatJson()))).thenAnswer( (_) async => http.Response('', 500), ); final FilesService apiService = FilesService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.editSpecificFileOCR(testEditFile), throwsA(isA<ServerException>())); await untilCalled(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testEditFile.formatJson()))); verify(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testEditFile.formatJson()))).called(1); }); test('editSpecificFileOCR throws Other Exception', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testId="Test id"; const String testJwt="Test jwt"; const String testContent="Test content"; const String testPrompt="Test prompt"; final EditFile testEditFile=EditFile(testId, testPrompt, testContent); final url = Uri.parse("${ApiRoutes.fileNlpEditOCRUrl}/$testId"); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testEditFile.formatJson()))).thenAnswer( (_) async => http.Response('', 555), ); final FilesService apiService = FilesService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.editSpecificFileOCR(testEditFile), throwsA(isA<Exception>())); await untilCalled(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testEditFile.formatJson()))); verify(httpClient.put(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testEditFile.formatJson()))).called(1); }); test('editSpecificFileOCR throws AuthException(Jwt is null)', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testId="Test id"; const String testContent="Test content"; const String testPrompt="Test prompt"; final EditFile testEditFile=EditFile(testId, testPrompt, testContent); when(jwtService.getJwt()).thenAnswer((_) async => null); final FilesService apiService = FilesService(jwtService: jwtService, httpClient: httpClient); expect(apiService.editSpecificFileOCR(testEditFile), throwsA(isA<AuthException>())); }); }); }
0
mirrored_repositories/study_savvy_app/test/api
mirrored_repositories/study_savvy_app/test/api/put/edit_specific_file_ocr_test.mocks.dart
// Mocks generated by Mockito 5.4.2 from annotations // in study_savvy_app/test/api/put/edit_specific_file_ocr_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i4; import 'dart:convert' as _i5; import 'dart:typed_data' as _i6; import 'package:http/http.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; import 'package:study_savvy_app/services/utils/jwt_storage.dart' as _i3; // 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 _FakeResponse_0 extends _i1.SmartFake implements _i2.Response { _FakeResponse_0( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeStreamedResponse_1 extends _i1.SmartFake implements _i2.StreamedResponse { _FakeStreamedResponse_1( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } /// A class which mocks [JwtService]. /// /// See the documentation for Mockito's code generation for more information. class MockJwtService extends _i1.Mock implements _i3.JwtService { MockJwtService() { _i1.throwOnMissingStub(this); } @override _i4.Future<void> saveJwt(String? jwt) => (super.noSuchMethod( Invocation.method( #saveJwt, [jwt], ), returnValue: _i4.Future<void>.value(), returnValueForMissingStub: _i4.Future<void>.value(), ) as _i4.Future<void>); @override _i4.Future<String?> getJwt() => (super.noSuchMethod( Invocation.method( #getJwt, [], ), returnValue: _i4.Future<String?>.value(), ) as _i4.Future<String?>); @override _i4.Future<void> deleteJwt() => (super.noSuchMethod( Invocation.method( #deleteJwt, [], ), returnValue: _i4.Future<void>.value(), returnValueForMissingStub: _i4.Future<void>.value(), ) as _i4.Future<void>); @override _i4.Future<bool?> hasJwt() => (super.noSuchMethod( Invocation.method( #hasJwt, [], ), returnValue: _i4.Future<bool?>.value(), ) as _i4.Future<bool?>); } /// A class which mocks [Client]. /// /// See the documentation for Mockito's code generation for more information. class MockClient extends _i1.Mock implements _i2.Client { MockClient() { _i1.throwOnMissingStub(this); } @override _i4.Future<_i2.Response> head( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #head, [url], {#headers: headers}, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #head, [url], {#headers: headers}, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> get( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #get, [url], {#headers: headers}, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #get, [url], {#headers: headers}, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> post( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #post, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #post, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> put( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #put, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #put, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> patch( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #patch, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #patch, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> delete( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #delete, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #delete, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<String> read( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #read, [url], {#headers: headers}, ), returnValue: _i4.Future<String>.value(''), ) as _i4.Future<String>); @override _i4.Future<_i6.Uint8List> readBytes( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #readBytes, [url], {#headers: headers}, ), returnValue: _i4.Future<_i6.Uint8List>.value(_i6.Uint8List(0)), ) as _i4.Future<_i6.Uint8List>); @override _i4.Future<_i2.StreamedResponse> send(_i2.BaseRequest? request) => (super.noSuchMethod( Invocation.method( #send, [request], ), returnValue: _i4.Future<_i2.StreamedResponse>.value(_FakeStreamedResponse_1( this, Invocation.method( #send, [request], ), )), ) as _i4.Future<_i2.StreamedResponse>); @override void close() => super.noSuchMethod( Invocation.method( #close, [], ), returnValueForMissingStub: null, ); }
0
mirrored_repositories/study_savvy_app/test/api
mirrored_repositories/study_savvy_app/test/api/put/set_api_key_test.dart
import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:http/http.dart' as http; import 'package:mockito/mockito.dart'; import 'package:study_savvy_app/services/profile/api_profile.dart'; import 'package:study_savvy_app/services/utils/jwt_storage.dart'; import 'package:study_savvy_app/utils/exception.dart'; import 'set_api_key_test.mocks.dart'; @GenerateMocks([JwtService, http.Client]) void main() { WidgetsFlutterBinding.ensureInitialized(); test('set-api-key', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testJwt="Test jwt"; const String testAccessToken="Test api_key"; when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.put(any, headers: anyNamed('headers'), body: anyNamed('body'))) .thenAnswer((_) async => http.Response('',200)); final ProfileService apiService = ProfileService(jwtService: jwtService, httpClient: httpClient); await apiService.setApiKey(testAccessToken); verify(httpClient.put(any, headers: anyNamed('headers'), body: anyNamed('body'))).called(1); }); test('set-api-key throws ClientException', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testJwt="Test jwt"; const String testAccessToken="Test api_key"; when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.put(any, headers: anyNamed('headers'), body: anyNamed('body'))) .thenAnswer((_) async => http.Response('',400)); final ProfileService apiService = ProfileService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.setApiKey(testAccessToken), throwsA(isA<ClientException>())); await untilCalled(httpClient.put(any, headers: anyNamed('headers'), body: anyNamed('body'))); verify(httpClient.put(any, headers: anyNamed('headers'), body: anyNamed('body'))).called(1); }); test('set-api-key throws ExistException', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testJwt="Test jwt"; const String testAccessToken="Test api_key"; when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.put(any, headers: anyNamed('headers'), body: anyNamed('body'))) .thenAnswer((_) async => http.Response('',404)); final ProfileService apiService = ProfileService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.setApiKey(testAccessToken), throwsA(isA<ExistException>())); await untilCalled(httpClient.put(any, headers: anyNamed('headers'), body: anyNamed('body'))); verify(httpClient.put(any, headers: anyNamed('headers'), body: anyNamed('body'))).called(1); }); test('set-api-key throws AuthException', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testJwt="Test jwt"; const String testAccessToken="Test api_key"; when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.put(any, headers: anyNamed('headers'), body: anyNamed('body'))) .thenAnswer((_) async => http.Response('',422)); final ProfileService apiService = ProfileService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.setApiKey(testAccessToken), throwsA(isA<AuthException>())); await untilCalled(httpClient.put(any, headers: anyNamed('headers'), body: anyNamed('body'))); verify(httpClient.put(any, headers: anyNamed('headers'), body: anyNamed('body'))).called(1); await untilCalled(jwtService.deleteJwt()); verify(jwtService.deleteJwt()).called(1); }); test('set-api-key throws ServerException', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testJwt="Test jwt"; const String testAccessToken="Test api_key"; when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.put(any, headers: anyNamed('headers'), body: anyNamed('body'))) .thenAnswer((_) async => http.Response('',500)); final ProfileService apiService = ProfileService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.setApiKey(testAccessToken), throwsA(isA<ServerException>())); await untilCalled(httpClient.put(any, headers: anyNamed('headers'), body: anyNamed('body'))); verify(httpClient.put(any, headers: anyNamed('headers'), body: anyNamed('body'))).called(1); }); test('set-api-key throws Other Exception', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testJwt="Test jwt"; const String testAccessToken="Test api_key"; when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.put(any, headers: anyNamed('headers'), body: anyNamed('body'))) .thenAnswer((_) async => http.Response('',555)); final ProfileService apiService = ProfileService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.setApiKey(testAccessToken), throwsA(isA<Exception>())); await untilCalled(httpClient.put(any, headers: anyNamed('headers'), body: anyNamed('body'))); verify(httpClient.put(any, headers: anyNamed('headers'), body: anyNamed('body'))).called(1); }); test('set-api-key throws AuthException(Jwt is null)', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testAccessToken="Test api_key"; when(jwtService.getJwt()).thenAnswer((_) async => null); final ProfileService apiService = ProfileService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.setApiKey(testAccessToken), throwsA(isA<AuthException>())); }); }
0
mirrored_repositories/study_savvy_app/test/api
mirrored_repositories/study_savvy_app/test/api/put/reset_password_test.mocks.dart
// Mocks generated by Mockito 5.4.2 from annotations // in study_savvy_app/test/api/put/reset_password_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i4; import 'dart:convert' as _i5; import 'dart:typed_data' as _i6; import 'package:http/http.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; import 'package:study_savvy_app/services/utils/jwt_storage.dart' as _i3; // 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 _FakeResponse_0 extends _i1.SmartFake implements _i2.Response { _FakeResponse_0( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeStreamedResponse_1 extends _i1.SmartFake implements _i2.StreamedResponse { _FakeStreamedResponse_1( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } /// A class which mocks [JwtService]. /// /// See the documentation for Mockito's code generation for more information. class MockJwtService extends _i1.Mock implements _i3.JwtService { MockJwtService() { _i1.throwOnMissingStub(this); } @override _i4.Future<void> saveJwt(String? jwt) => (super.noSuchMethod( Invocation.method( #saveJwt, [jwt], ), returnValue: _i4.Future<void>.value(), returnValueForMissingStub: _i4.Future<void>.value(), ) as _i4.Future<void>); @override _i4.Future<String?> getJwt() => (super.noSuchMethod( Invocation.method( #getJwt, [], ), returnValue: _i4.Future<String?>.value(), ) as _i4.Future<String?>); @override _i4.Future<void> deleteJwt() => (super.noSuchMethod( Invocation.method( #deleteJwt, [], ), returnValue: _i4.Future<void>.value(), returnValueForMissingStub: _i4.Future<void>.value(), ) as _i4.Future<void>); @override _i4.Future<bool?> hasJwt() => (super.noSuchMethod( Invocation.method( #hasJwt, [], ), returnValue: _i4.Future<bool?>.value(), ) as _i4.Future<bool?>); } /// A class which mocks [Client]. /// /// See the documentation for Mockito's code generation for more information. class MockClient extends _i1.Mock implements _i2.Client { MockClient() { _i1.throwOnMissingStub(this); } @override _i4.Future<_i2.Response> head( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #head, [url], {#headers: headers}, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #head, [url], {#headers: headers}, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> get( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #get, [url], {#headers: headers}, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #get, [url], {#headers: headers}, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> post( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #post, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #post, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> put( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #put, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #put, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> patch( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #patch, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #patch, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> delete( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #delete, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #delete, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<String> read( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #read, [url], {#headers: headers}, ), returnValue: _i4.Future<String>.value(''), ) as _i4.Future<String>); @override _i4.Future<_i6.Uint8List> readBytes( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #readBytes, [url], {#headers: headers}, ), returnValue: _i4.Future<_i6.Uint8List>.value(_i6.Uint8List(0)), ) as _i4.Future<_i6.Uint8List>); @override _i4.Future<_i2.StreamedResponse> send(_i2.BaseRequest? request) => (super.noSuchMethod( Invocation.method( #send, [request], ), returnValue: _i4.Future<_i2.StreamedResponse>.value(_FakeStreamedResponse_1( this, Invocation.method( #send, [request], ), )), ) as _i4.Future<_i2.StreamedResponse>); @override void close() => super.noSuchMethod( Invocation.method( #close, [], ), returnValueForMissingStub: null, ); }
0
mirrored_repositories/study_savvy_app/test/api
mirrored_repositories/study_savvy_app/test/api/put/set_access_token_test.dart
import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:http/http.dart' as http; import 'package:mockito/mockito.dart'; import 'package:study_savvy_app/services/profile/api_profile.dart'; import 'package:study_savvy_app/services/utils/jwt_storage.dart'; import 'package:study_savvy_app/utils/exception.dart'; import 'set_access_token_test.mocks.dart'; @GenerateMocks([JwtService, http.Client]) void main() { WidgetsFlutterBinding.ensureInitialized(); test('set-access-token', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testJwt="Test jwt"; const String testAccessToken="Test access_token"; when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.put(any, headers: anyNamed('headers'), body: anyNamed('body'))) .thenAnswer((_) async => http.Response('',200)); final ProfileService apiService = ProfileService(jwtService: jwtService, httpClient: httpClient); await apiService.setAccessToken(testAccessToken); verify(httpClient.put(any, headers: anyNamed('headers'), body: anyNamed('body'))).called(1); }); test('set-access-token throws ClientException', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testJwt="Test jwt"; const String testAccessToken="Test access_token"; when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.put(any, headers: anyNamed('headers'), body: anyNamed('body'))) .thenAnswer((_) async => http.Response('',400)); final ProfileService apiService = ProfileService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.setAccessToken(testAccessToken), throwsA(isA<ClientException>())); await untilCalled(httpClient.put(any, headers: anyNamed('headers'), body: anyNamed('body'))); verify(httpClient.put(any, headers: anyNamed('headers'), body: anyNamed('body'))).called(1); }); test('set-access-token throws ExistException', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testJwt="Test jwt"; const String testAccessToken="Test access_token"; when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.put(any, headers: anyNamed('headers'), body: anyNamed('body'))) .thenAnswer((_) async => http.Response('',404)); final ProfileService apiService = ProfileService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.setAccessToken(testAccessToken), throwsA(isA<ExistException>())); await untilCalled(httpClient.put(any, headers: anyNamed('headers'), body: anyNamed('body'))); verify(httpClient.put(any, headers: anyNamed('headers'), body: anyNamed('body'))).called(1); }); test('set-access-token throws AuthException', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testJwt="Test jwt"; const String testAccessToken="Test access_token"; when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.put(any, headers: anyNamed('headers'), body: anyNamed('body'))) .thenAnswer((_) async => http.Response('',422)); final ProfileService apiService = ProfileService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.setAccessToken(testAccessToken), throwsA(isA<AuthException>())); await untilCalled(httpClient.put(any, headers: anyNamed('headers'), body: anyNamed('body'))); verify(httpClient.put(any, headers: anyNamed('headers'), body: anyNamed('body'))).called(1); await untilCalled(jwtService.deleteJwt()); verify(jwtService.deleteJwt()).called(1); }); test('set-access-token throws ServerException', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testJwt="Test jwt"; const String testAccessToken="Test access_token"; when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.put(any, headers: anyNamed('headers'), body: anyNamed('body'))) .thenAnswer((_) async => http.Response('',500)); final ProfileService apiService = ProfileService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.setAccessToken(testAccessToken), throwsA(isA<ServerException>())); await untilCalled(httpClient.put(any, headers: anyNamed('headers'), body: anyNamed('body'))); verify(httpClient.put(any, headers: anyNamed('headers'), body: anyNamed('body'))).called(1); }); test('set-access-token throws Other Exception', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testJwt="Test jwt"; const String testAccessToken="Test access_token"; when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.put(any, headers: anyNamed('headers'), body: anyNamed('body'))) .thenAnswer((_) async => http.Response('',555)); final ProfileService apiService = ProfileService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.setAccessToken(testAccessToken), throwsA(isA<Exception>())); await untilCalled(httpClient.put(any, headers: anyNamed('headers'), body: anyNamed('body'))); verify(httpClient.put(any, headers: anyNamed('headers'), body: anyNamed('body'))).called(1); }); test('set-access-token throws AuthException(Jwt is null)', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testAccessToken="Test access_token"; when(jwtService.getJwt()).thenAnswer((_) async => null); final ProfileService apiService = ProfileService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.setAccessToken(testAccessToken), throwsA(isA<AuthException>())); }); }
0
mirrored_repositories/study_savvy_app/test/api
mirrored_repositories/study_savvy_app/test/api/post/predict_ocr_text_test.dart
import 'dart:convert'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:http/http.dart' as http; import 'package:mockito/mockito.dart'; import 'package:study_savvy_app/models/article_improver/model_article_improver.dart'; import 'package:study_savvy_app/services/article_improver/api_article_improver.dart'; import 'package:study_savvy_app/services/api_routes.dart'; import 'package:study_savvy_app/services/utils/jwt_storage.dart'; import 'package:study_savvy_app/utils/exception.dart'; import 'predict_ocr_text_test.mocks.dart'; @GenerateMocks([JwtService, http.Client]) void main() { group('predictOcrText', () { test('predictOcrText', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testJwt="Test jwt"; const String testContent="Test content"; const String testPrompt="Test prompt"; final ArticleText testArticleText=ArticleText(testContent,testPrompt); final url = Uri.parse(ApiRoutes.articleImproverTextUrl); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.post(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testArticleText.formatJson()))).thenAnswer((_) async => http.Response('', 200),); final ArticleImproverService apiService = ArticleImproverService(jwtService: jwtService, httpClient: httpClient); await apiService.predictOcrText(testArticleText); verify(httpClient.post(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testArticleText.formatJson()))).called(1); }); test('predictOcrText throws ClientException', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testJwt="Test jwt"; const String testContent="Test content"; const String testPrompt="Test prompt"; final ArticleText testArticleText=ArticleText(testContent,testPrompt); final url = Uri.parse(ApiRoutes.articleImproverTextUrl); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.post(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testArticleText.formatJson()))).thenAnswer((_) async => http.Response('', 400),); final ArticleImproverService apiService = ArticleImproverService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.predictOcrText(testArticleText), throwsA(isA<ClientException>())); await untilCalled(httpClient.post(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testArticleText.formatJson()))); verify(httpClient.post(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testArticleText.formatJson()))).called(1); }); test('predictOcrText throws ExistException', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testJwt="Test jwt"; const String testContent="Test content"; const String testPrompt="Test prompt"; final ArticleText testArticleText=ArticleText( testContent,testPrompt); final url = Uri.parse(ApiRoutes.articleImproverTextUrl); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.post(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testArticleText.formatJson()))).thenAnswer((_) async => http.Response('', 404),); final ArticleImproverService apiService = ArticleImproverService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.predictOcrText(testArticleText), throwsA(isA<ExistException>())); await untilCalled(httpClient.post(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testArticleText.formatJson()))); verify(httpClient.post(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testArticleText.formatJson()))).called(1); }); test('predictOcrText throws AuthException', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testJwt="Test jwt"; const String testContent="Test content"; const String testPrompt="Test prompt"; final ArticleText testArticleText=ArticleText( testContent,testPrompt); final url = Uri.parse(ApiRoutes.articleImproverTextUrl); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.post(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testArticleText.formatJson()))).thenAnswer((_) async => http.Response('', 422),); final ArticleImproverService apiService = ArticleImproverService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.predictOcrText(testArticleText), throwsA(isA<AuthException>())); await untilCalled(httpClient.post(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testArticleText.formatJson()))); verify(httpClient.post(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testArticleText.formatJson()))).called(1); await untilCalled(jwtService.deleteJwt()); verify(jwtService.deleteJwt()).called(1); }); test('predictOcrText throws ServerException', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testJwt="Test jwt"; const String testContent="Test content"; const String testPrompt="Test prompt"; final ArticleText testArticleText=ArticleText( testContent,testPrompt); final url = Uri.parse(ApiRoutes.articleImproverTextUrl); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.post(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testArticleText.formatJson()))).thenAnswer( (_) async => http.Response('', 500), ); final ArticleImproverService apiService = ArticleImproverService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.predictOcrText(testArticleText), throwsA(isA<ServerException>())); await untilCalled(httpClient.post(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testArticleText.formatJson()))); verify(httpClient.post(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testArticleText.formatJson()))).called(1); }); test('predictOcrText throws Other Exception', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testJwt="Test jwt"; const String testContent="Test content"; const String testPrompt="Test prompt"; final ArticleText testArticleText=ArticleText( testContent,testPrompt); final url = Uri.parse(ApiRoutes.articleImproverTextUrl); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.post(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testArticleText.formatJson()))).thenAnswer( (_) async => http.Response('', 555), ); final ArticleImproverService apiService = ArticleImproverService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.predictOcrText(testArticleText), throwsA(isA<Exception>())); await untilCalled(httpClient.post(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testArticleText.formatJson()))); verify(httpClient.post(url, headers: {"Content-Type": "application/json",'Authorization': 'Bearer $testJwt'},body: jsonEncode(testArticleText.formatJson()))).called(1); }); test('predictOcrText throws AuthException(Jwt is null)', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testContent="Test content"; const String testPrompt="Test prompt"; final ArticleText testArticleText=ArticleText( testContent,testPrompt); when(jwtService.getJwt()).thenAnswer((_) async => null); final ArticleImproverService apiService = ArticleImproverService(jwtService: jwtService, httpClient: httpClient); expect(apiService.predictOcrText(testArticleText), throwsA(isA<AuthException>())); }); }); }
0
mirrored_repositories/study_savvy_app/test/api
mirrored_repositories/study_savvy_app/test/api/post/predict_ocr_graph_test.mocks.dart
// Mocks generated by Mockito 5.4.2 from annotations // in study_savvy_app/test/api/post/predict_ocr_graph_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i5; import 'dart:convert' as _i6; import 'dart:io' as _i3; import 'dart:typed_data' as _i7; import 'package:http/http.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; import 'package:study_savvy_app/services/utils/jwt_storage.dart' as _i4; // 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 _FakeResponse_0 extends _i1.SmartFake implements _i2.Response { _FakeResponse_0( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeStreamedResponse_1 extends _i1.SmartFake implements _i2.StreamedResponse { _FakeStreamedResponse_1( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeFile_2 extends _i1.SmartFake implements _i3.File { _FakeFile_2( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeUri_3 extends _i1.SmartFake implements Uri { _FakeUri_3( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeDirectory_4 extends _i1.SmartFake implements _i3.Directory { _FakeDirectory_4( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeDateTime_5 extends _i1.SmartFake implements DateTime { _FakeDateTime_5( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeRandomAccessFile_6 extends _i1.SmartFake implements _i3.RandomAccessFile { _FakeRandomAccessFile_6( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeIOSink_7 extends _i1.SmartFake implements _i3.IOSink { _FakeIOSink_7( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeFileStat_8 extends _i1.SmartFake implements _i3.FileStat { _FakeFileStat_8( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeFileSystemEntity_9 extends _i1.SmartFake implements _i3.FileSystemEntity { _FakeFileSystemEntity_9( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } /// A class which mocks [JwtService]. /// /// See the documentation for Mockito's code generation for more information. class MockJwtService extends _i1.Mock implements _i4.JwtService { MockJwtService() { _i1.throwOnMissingStub(this); } @override _i5.Future<void> saveJwt(String? jwt) => (super.noSuchMethod( Invocation.method( #saveJwt, [jwt], ), returnValue: _i5.Future<void>.value(), returnValueForMissingStub: _i5.Future<void>.value(), ) as _i5.Future<void>); @override _i5.Future<String?> getJwt() => (super.noSuchMethod( Invocation.method( #getJwt, [], ), returnValue: _i5.Future<String?>.value(), ) as _i5.Future<String?>); @override _i5.Future<void> deleteJwt() => (super.noSuchMethod( Invocation.method( #deleteJwt, [], ), returnValue: _i5.Future<void>.value(), returnValueForMissingStub: _i5.Future<void>.value(), ) as _i5.Future<void>); @override _i5.Future<bool?> hasJwt() => (super.noSuchMethod( Invocation.method( #hasJwt, [], ), returnValue: _i5.Future<bool?>.value(), ) as _i5.Future<bool?>); } /// A class which mocks [Client]. /// /// See the documentation for Mockito's code generation for more information. class MockClient extends _i1.Mock implements _i2.Client { MockClient() { _i1.throwOnMissingStub(this); } @override _i5.Future<_i2.Response> head( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #head, [url], {#headers: headers}, ), returnValue: _i5.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #head, [url], {#headers: headers}, ), )), ) as _i5.Future<_i2.Response>); @override _i5.Future<_i2.Response> get( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #get, [url], {#headers: headers}, ), returnValue: _i5.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #get, [url], {#headers: headers}, ), )), ) as _i5.Future<_i2.Response>); @override _i5.Future<_i2.Response> post( Uri? url, { Map<String, String>? headers, Object? body, _i6.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #post, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i5.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #post, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i5.Future<_i2.Response>); @override _i5.Future<_i2.Response> put( Uri? url, { Map<String, String>? headers, Object? body, _i6.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #put, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i5.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #put, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i5.Future<_i2.Response>); @override _i5.Future<_i2.Response> patch( Uri? url, { Map<String, String>? headers, Object? body, _i6.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #patch, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i5.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #patch, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i5.Future<_i2.Response>); @override _i5.Future<_i2.Response> delete( Uri? url, { Map<String, String>? headers, Object? body, _i6.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #delete, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i5.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #delete, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i5.Future<_i2.Response>); @override _i5.Future<String> read( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #read, [url], {#headers: headers}, ), returnValue: _i5.Future<String>.value(''), ) as _i5.Future<String>); @override _i5.Future<_i7.Uint8List> readBytes( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #readBytes, [url], {#headers: headers}, ), returnValue: _i5.Future<_i7.Uint8List>.value(_i7.Uint8List(0)), ) as _i5.Future<_i7.Uint8List>); @override _i5.Future<_i2.StreamedResponse> send(_i2.BaseRequest? request) => (super.noSuchMethod( Invocation.method( #send, [request], ), returnValue: _i5.Future<_i2.StreamedResponse>.value(_FakeStreamedResponse_1( this, Invocation.method( #send, [request], ), )), ) as _i5.Future<_i2.StreamedResponse>); @override void close() => super.noSuchMethod( Invocation.method( #close, [], ), returnValueForMissingStub: null, ); } /// A class which mocks [File]. /// /// See the documentation for Mockito's code generation for more information. class MockFile extends _i1.Mock implements _i3.File { MockFile() { _i1.throwOnMissingStub(this); } @override _i3.File get absolute => (super.noSuchMethod( Invocation.getter(#absolute), returnValue: _FakeFile_2( this, Invocation.getter(#absolute), ), ) as _i3.File); @override String get path => (super.noSuchMethod( Invocation.getter(#path), returnValue: '', ) as String); @override Uri get uri => (super.noSuchMethod( Invocation.getter(#uri), returnValue: _FakeUri_3( this, Invocation.getter(#uri), ), ) as Uri); @override bool get isAbsolute => (super.noSuchMethod( Invocation.getter(#isAbsolute), returnValue: false, ) as bool); @override _i3.Directory get parent => (super.noSuchMethod( Invocation.getter(#parent), returnValue: _FakeDirectory_4( this, Invocation.getter(#parent), ), ) as _i3.Directory); @override _i5.Future<_i3.File> create({ bool? recursive = false, bool? exclusive = false, }) => (super.noSuchMethod( Invocation.method( #create, [], { #recursive: recursive, #exclusive: exclusive, }, ), returnValue: _i5.Future<_i3.File>.value(_FakeFile_2( this, Invocation.method( #create, [], { #recursive: recursive, #exclusive: exclusive, }, ), )), ) as _i5.Future<_i3.File>); @override void createSync({ bool? recursive = false, bool? exclusive = false, }) => super.noSuchMethod( Invocation.method( #createSync, [], { #recursive: recursive, #exclusive: exclusive, }, ), returnValueForMissingStub: null, ); @override _i5.Future<_i3.File> rename(String? newPath) => (super.noSuchMethod( Invocation.method( #rename, [newPath], ), returnValue: _i5.Future<_i3.File>.value(_FakeFile_2( this, Invocation.method( #rename, [newPath], ), )), ) as _i5.Future<_i3.File>); @override _i3.File renameSync(String? newPath) => (super.noSuchMethod( Invocation.method( #renameSync, [newPath], ), returnValue: _FakeFile_2( this, Invocation.method( #renameSync, [newPath], ), ), ) as _i3.File); @override _i5.Future<_i3.File> copy(String? newPath) => (super.noSuchMethod( Invocation.method( #copy, [newPath], ), returnValue: _i5.Future<_i3.File>.value(_FakeFile_2( this, Invocation.method( #copy, [newPath], ), )), ) as _i5.Future<_i3.File>); @override _i3.File copySync(String? newPath) => (super.noSuchMethod( Invocation.method( #copySync, [newPath], ), returnValue: _FakeFile_2( this, Invocation.method( #copySync, [newPath], ), ), ) as _i3.File); @override _i5.Future<int> length() => (super.noSuchMethod( Invocation.method( #length, [], ), returnValue: _i5.Future<int>.value(0), ) as _i5.Future<int>); @override int lengthSync() => (super.noSuchMethod( Invocation.method( #lengthSync, [], ), returnValue: 0, ) as int); @override _i5.Future<DateTime> lastAccessed() => (super.noSuchMethod( Invocation.method( #lastAccessed, [], ), returnValue: _i5.Future<DateTime>.value(_FakeDateTime_5( this, Invocation.method( #lastAccessed, [], ), )), ) as _i5.Future<DateTime>); @override DateTime lastAccessedSync() => (super.noSuchMethod( Invocation.method( #lastAccessedSync, [], ), returnValue: _FakeDateTime_5( this, Invocation.method( #lastAccessedSync, [], ), ), ) as DateTime); @override _i5.Future<dynamic> setLastAccessed(DateTime? time) => (super.noSuchMethod( Invocation.method( #setLastAccessed, [time], ), returnValue: _i5.Future<dynamic>.value(), ) as _i5.Future<dynamic>); @override void setLastAccessedSync(DateTime? time) => super.noSuchMethod( Invocation.method( #setLastAccessedSync, [time], ), returnValueForMissingStub: null, ); @override _i5.Future<DateTime> lastModified() => (super.noSuchMethod( Invocation.method( #lastModified, [], ), returnValue: _i5.Future<DateTime>.value(_FakeDateTime_5( this, Invocation.method( #lastModified, [], ), )), ) as _i5.Future<DateTime>); @override DateTime lastModifiedSync() => (super.noSuchMethod( Invocation.method( #lastModifiedSync, [], ), returnValue: _FakeDateTime_5( this, Invocation.method( #lastModifiedSync, [], ), ), ) as DateTime); @override _i5.Future<dynamic> setLastModified(DateTime? time) => (super.noSuchMethod( Invocation.method( #setLastModified, [time], ), returnValue: _i5.Future<dynamic>.value(), ) as _i5.Future<dynamic>); @override void setLastModifiedSync(DateTime? time) => super.noSuchMethod( Invocation.method( #setLastModifiedSync, [time], ), returnValueForMissingStub: null, ); @override _i5.Future<_i3.RandomAccessFile> open( {_i3.FileMode? mode = _i3.FileMode.read}) => (super.noSuchMethod( Invocation.method( #open, [], {#mode: mode}, ), returnValue: _i5.Future<_i3.RandomAccessFile>.value(_FakeRandomAccessFile_6( this, Invocation.method( #open, [], {#mode: mode}, ), )), ) as _i5.Future<_i3.RandomAccessFile>); @override _i3.RandomAccessFile openSync({_i3.FileMode? mode = _i3.FileMode.read}) => (super.noSuchMethod( Invocation.method( #openSync, [], {#mode: mode}, ), returnValue: _FakeRandomAccessFile_6( this, Invocation.method( #openSync, [], {#mode: mode}, ), ), ) as _i3.RandomAccessFile); @override _i5.Stream<List<int>> openRead([ int? start, int? end, ]) => (super.noSuchMethod( Invocation.method( #openRead, [ start, end, ], ), returnValue: _i5.Stream<List<int>>.empty(), ) as _i5.Stream<List<int>>); @override _i3.IOSink openWrite({ _i3.FileMode? mode = _i3.FileMode.write, _i6.Encoding? encoding = const _i6.Utf8Codec(), }) => (super.noSuchMethod( Invocation.method( #openWrite, [], { #mode: mode, #encoding: encoding, }, ), returnValue: _FakeIOSink_7( this, Invocation.method( #openWrite, [], { #mode: mode, #encoding: encoding, }, ), ), ) as _i3.IOSink); @override _i5.Future<_i7.Uint8List> readAsBytes() => (super.noSuchMethod( Invocation.method( #readAsBytes, [], ), returnValue: _i5.Future<_i7.Uint8List>.value(_i7.Uint8List(0)), ) as _i5.Future<_i7.Uint8List>); @override _i7.Uint8List readAsBytesSync() => (super.noSuchMethod( Invocation.method( #readAsBytesSync, [], ), returnValue: _i7.Uint8List(0), ) as _i7.Uint8List); @override _i5.Future<String> readAsString( {_i6.Encoding? encoding = const _i6.Utf8Codec()}) => (super.noSuchMethod( Invocation.method( #readAsString, [], {#encoding: encoding}, ), returnValue: _i5.Future<String>.value(''), ) as _i5.Future<String>); @override String readAsStringSync({_i6.Encoding? encoding = const _i6.Utf8Codec()}) => (super.noSuchMethod( Invocation.method( #readAsStringSync, [], {#encoding: encoding}, ), returnValue: '', ) as String); @override _i5.Future<List<String>> readAsLines( {_i6.Encoding? encoding = const _i6.Utf8Codec()}) => (super.noSuchMethod( Invocation.method( #readAsLines, [], {#encoding: encoding}, ), returnValue: _i5.Future<List<String>>.value(<String>[]), ) as _i5.Future<List<String>>); @override List<String> readAsLinesSync( {_i6.Encoding? encoding = const _i6.Utf8Codec()}) => (super.noSuchMethod( Invocation.method( #readAsLinesSync, [], {#encoding: encoding}, ), returnValue: <String>[], ) as List<String>); @override _i5.Future<_i3.File> writeAsBytes( List<int>? bytes, { _i3.FileMode? mode = _i3.FileMode.write, bool? flush = false, }) => (super.noSuchMethod( Invocation.method( #writeAsBytes, [bytes], { #mode: mode, #flush: flush, }, ), returnValue: _i5.Future<_i3.File>.value(_FakeFile_2( this, Invocation.method( #writeAsBytes, [bytes], { #mode: mode, #flush: flush, }, ), )), ) as _i5.Future<_i3.File>); @override void writeAsBytesSync( List<int>? bytes, { _i3.FileMode? mode = _i3.FileMode.write, bool? flush = false, }) => super.noSuchMethod( Invocation.method( #writeAsBytesSync, [bytes], { #mode: mode, #flush: flush, }, ), returnValueForMissingStub: null, ); @override _i5.Future<_i3.File> writeAsString( String? contents, { _i3.FileMode? mode = _i3.FileMode.write, _i6.Encoding? encoding = const _i6.Utf8Codec(), bool? flush = false, }) => (super.noSuchMethod( Invocation.method( #writeAsString, [contents], { #mode: mode, #encoding: encoding, #flush: flush, }, ), returnValue: _i5.Future<_i3.File>.value(_FakeFile_2( this, Invocation.method( #writeAsString, [contents], { #mode: mode, #encoding: encoding, #flush: flush, }, ), )), ) as _i5.Future<_i3.File>); @override void writeAsStringSync( String? contents, { _i3.FileMode? mode = _i3.FileMode.write, _i6.Encoding? encoding = const _i6.Utf8Codec(), bool? flush = false, }) => super.noSuchMethod( Invocation.method( #writeAsStringSync, [contents], { #mode: mode, #encoding: encoding, #flush: flush, }, ), returnValueForMissingStub: null, ); @override _i5.Future<bool> exists() => (super.noSuchMethod( Invocation.method( #exists, [], ), returnValue: _i5.Future<bool>.value(false), ) as _i5.Future<bool>); @override bool existsSync() => (super.noSuchMethod( Invocation.method( #existsSync, [], ), returnValue: false, ) as bool); @override _i5.Future<String> resolveSymbolicLinks() => (super.noSuchMethod( Invocation.method( #resolveSymbolicLinks, [], ), returnValue: _i5.Future<String>.value(''), ) as _i5.Future<String>); @override String resolveSymbolicLinksSync() => (super.noSuchMethod( Invocation.method( #resolveSymbolicLinksSync, [], ), returnValue: '', ) as String); @override _i5.Future<_i3.FileStat> stat() => (super.noSuchMethod( Invocation.method( #stat, [], ), returnValue: _i5.Future<_i3.FileStat>.value(_FakeFileStat_8( this, Invocation.method( #stat, [], ), )), ) as _i5.Future<_i3.FileStat>); @override _i3.FileStat statSync() => (super.noSuchMethod( Invocation.method( #statSync, [], ), returnValue: _FakeFileStat_8( this, Invocation.method( #statSync, [], ), ), ) as _i3.FileStat); @override _i5.Future<_i3.FileSystemEntity> delete({bool? recursive = false}) => (super.noSuchMethod( Invocation.method( #delete, [], {#recursive: recursive}, ), returnValue: _i5.Future<_i3.FileSystemEntity>.value(_FakeFileSystemEntity_9( this, Invocation.method( #delete, [], {#recursive: recursive}, ), )), ) as _i5.Future<_i3.FileSystemEntity>); @override void deleteSync({bool? recursive = false}) => super.noSuchMethod( Invocation.method( #deleteSync, [], {#recursive: recursive}, ), returnValueForMissingStub: null, ); @override _i5.Stream<_i3.FileSystemEvent> watch({ int? events = 15, bool? recursive = false, }) => (super.noSuchMethod( Invocation.method( #watch, [], { #events: events, #recursive: recursive, }, ), returnValue: _i5.Stream<_i3.FileSystemEvent>.empty(), ) as _i5.Stream<_i3.FileSystemEvent>); }
0
mirrored_repositories/study_savvy_app/test/api
mirrored_repositories/study_savvy_app/test/api/post/predict_ocr_text_test.mocks.dart
// Mocks generated by Mockito 5.4.2 from annotations // in study_savvy_app/test/api/post/predict_ocr_text_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i4; import 'dart:convert' as _i5; import 'dart:typed_data' as _i6; import 'package:http/http.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; import 'package:study_savvy_app/services/utils/jwt_storage.dart' as _i3; // 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 _FakeResponse_0 extends _i1.SmartFake implements _i2.Response { _FakeResponse_0( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeStreamedResponse_1 extends _i1.SmartFake implements _i2.StreamedResponse { _FakeStreamedResponse_1( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } /// A class which mocks [JwtService]. /// /// See the documentation for Mockito's code generation for more information. class MockJwtService extends _i1.Mock implements _i3.JwtService { MockJwtService() { _i1.throwOnMissingStub(this); } @override _i4.Future<void> saveJwt(String? jwt) => (super.noSuchMethod( Invocation.method( #saveJwt, [jwt], ), returnValue: _i4.Future<void>.value(), returnValueForMissingStub: _i4.Future<void>.value(), ) as _i4.Future<void>); @override _i4.Future<String?> getJwt() => (super.noSuchMethod( Invocation.method( #getJwt, [], ), returnValue: _i4.Future<String?>.value(), ) as _i4.Future<String?>); @override _i4.Future<void> deleteJwt() => (super.noSuchMethod( Invocation.method( #deleteJwt, [], ), returnValue: _i4.Future<void>.value(), returnValueForMissingStub: _i4.Future<void>.value(), ) as _i4.Future<void>); @override _i4.Future<bool?> hasJwt() => (super.noSuchMethod( Invocation.method( #hasJwt, [], ), returnValue: _i4.Future<bool?>.value(), ) as _i4.Future<bool?>); } /// A class which mocks [Client]. /// /// See the documentation for Mockito's code generation for more information. class MockClient extends _i1.Mock implements _i2.Client { MockClient() { _i1.throwOnMissingStub(this); } @override _i4.Future<_i2.Response> head( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #head, [url], {#headers: headers}, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #head, [url], {#headers: headers}, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> get( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #get, [url], {#headers: headers}, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #get, [url], {#headers: headers}, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> post( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #post, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #post, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> put( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #put, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #put, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> patch( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #patch, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #patch, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> delete( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #delete, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #delete, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<String> read( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #read, [url], {#headers: headers}, ), returnValue: _i4.Future<String>.value(''), ) as _i4.Future<String>); @override _i4.Future<_i6.Uint8List> readBytes( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #readBytes, [url], {#headers: headers}, ), returnValue: _i4.Future<_i6.Uint8List>.value(_i6.Uint8List(0)), ) as _i4.Future<_i6.Uint8List>); @override _i4.Future<_i2.StreamedResponse> send(_i2.BaseRequest? request) => (super.noSuchMethod( Invocation.method( #send, [request], ), returnValue: _i4.Future<_i2.StreamedResponse>.value(_FakeStreamedResponse_1( this, Invocation.method( #send, [request], ), )), ) as _i4.Future<_i2.StreamedResponse>); @override void close() => super.noSuchMethod( Invocation.method( #close, [], ), returnValueForMissingStub: null, ); }
0
mirrored_repositories/study_savvy_app/test/api
mirrored_repositories/study_savvy_app/test/api/post/predict_ocr_graph_test.dart
import 'dart:io'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:http/http.dart' as http; import 'package:mockito/mockito.dart'; import 'package:study_savvy_app/models/article_improver/model_article_improver.dart'; import 'package:study_savvy_app/services/article_improver/api_article_improver.dart'; import 'package:study_savvy_app/services/utils/jwt_storage.dart'; import 'package:study_savvy_app/utils/exception.dart'; import 'predict_ocr_graph_test.mocks.dart'; @GenerateMocks([JwtService, http.Client,File]) void main() { group('predictOcrGraph', () { test('predictOcrGraph', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testJwt="Test jwt"; File testFile = File('${Directory.systemTemp.path}/test.jpg'); await testFile.writeAsBytes(List<int>.generate(10, (index) => index%256)); const String testPrompt="Test prompt"; final ArticleImage testArticleImage=ArticleImage(testFile,testPrompt); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.send(any)).thenAnswer((_) async => http.StreamedResponse(const Stream.empty(),200),); final ArticleImproverService apiService = ArticleImproverService(jwtService: jwtService, httpClient: httpClient); await apiService.predictOcrGraph(testArticleImage); verify(httpClient.send(any)).called(1); await testFile.delete(); }); test('predictOcrGraph throws ClientException', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testJwt="Test jwt"; File testFile = File('${Directory.systemTemp.path}/test.jpg'); await testFile.writeAsBytes(List<int>.generate(10, (index) => index%256)); const String testPrompt="Test prompt"; final ArticleImage testArticleImage=ArticleImage(testFile,testPrompt); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.send(any)).thenAnswer((_) async => http.StreamedResponse(const Stream.empty(), 400),); final ArticleImproverService apiService = ArticleImproverService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.predictOcrGraph(testArticleImage), throwsA(isA<ClientException>())); await untilCalled(httpClient.send(any)); verify(httpClient.send(any)).called(1); await testFile.delete(); }); test('predictOcrGraph throws ExistException', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testJwt="Test jwt"; File testFile = File('${Directory.systemTemp.path}/test.jpg'); await testFile.writeAsBytes(List<int>.generate(10, (index) => index%256)); const String testPrompt="Test prompt"; final ArticleImage testArticleImage=ArticleImage( testFile,testPrompt); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.send(any)).thenAnswer((_) async => http.StreamedResponse(const Stream.empty(), 404),); final ArticleImproverService apiService = ArticleImproverService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.predictOcrGraph(testArticleImage), throwsA(isA<ExistException>())); await untilCalled(httpClient.send(any)); verify(httpClient.send(any)).called(1); await testFile.delete(); }); test('predictOcrGraph throws AuthException', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testJwt="Test jwt"; File testFile = File('${Directory.systemTemp.path}/test.jpg'); await testFile.writeAsBytes(List<int>.generate(10, (index) => index%256)); const String testPrompt="Test prompt"; final ArticleImage testArticleImage=ArticleImage( testFile,testPrompt); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.send(any)).thenAnswer((_) async => http.StreamedResponse(const Stream.empty(), 422),); final ArticleImproverService apiService = ArticleImproverService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.predictOcrGraph(testArticleImage), throwsA(isA<AuthException>())); await untilCalled(httpClient.send(any)); verify(httpClient.send(any)).called(1); await untilCalled(jwtService.deleteJwt()); verify(jwtService.deleteJwt()).called(1); await testFile.delete(); }); test('predictOcrGraph throws ServerException', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testJwt="Test jwt"; File testFile = File('${Directory.systemTemp.path}/test.jpg'); await testFile.writeAsBytes(List<int>.generate(10, (index) => index%256)); const String testPrompt="Test prompt"; final ArticleImage testArticleImage=ArticleImage( testFile,testPrompt); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.send(any)).thenAnswer( (_) async => http.StreamedResponse(const Stream.empty(), 500), ); final ArticleImproverService apiService = ArticleImproverService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.predictOcrGraph(testArticleImage), throwsA(isA<ServerException>())); await untilCalled(httpClient.send(any)); verify(httpClient.send(any)).called(1); await testFile.delete(); }); test('predictOcrGraph throws Other Exception', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testJwt="Test jwt"; File testFile = File('${Directory.systemTemp.path}/test.jpg'); await testFile.writeAsBytes(List<int>.generate(10, (index) => index%256)); const String testPrompt="Test prompt"; final ArticleImage testArticleImage=ArticleImage( testFile,testPrompt); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.send(any)).thenAnswer( (_) async => http.StreamedResponse(const Stream.empty(), 555), ); final ArticleImproverService apiService = ArticleImproverService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.predictOcrGraph(testArticleImage), throwsA(isA<Exception>())); await untilCalled(httpClient.send(any)); verify(httpClient.send(any)).called(1); await testFile.delete(); }); test('predictOcrGraph throws AuthException(Jwt is null)', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); File testFile = File('${Directory.systemTemp.path}/test.jpg'); await testFile.writeAsBytes(List<int>.generate(10, (index) => index%256)); const String testPrompt="Test prompt"; final ArticleImage testArticleImage=ArticleImage( testFile,testPrompt); when(jwtService.getJwt()).thenAnswer((_) async => null); final ArticleImproverService apiService = ArticleImproverService(jwtService: jwtService, httpClient: httpClient); expect(apiService.predictOcrGraph(testArticleImage), throwsA(isA<AuthException>())); await testFile.delete(); }); }); }
0
mirrored_repositories/study_savvy_app/test/api
mirrored_repositories/study_savvy_app/test/api/delete/delete_specific_file_test.dart
import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'package:study_savvy_app/services/files/api_files.dart'; import 'package:study_savvy_app/services/api_routes.dart'; import 'package:study_savvy_app/services/utils/jwt_storage.dart'; import 'package:study_savvy_app/utils/exception.dart'; import 'package:http/http.dart' as http; import 'delete_specific_file_test.mocks.dart'; @GenerateMocks([JwtService, http.Client]) void main() { group("Delete method of deleteSpecificFile", () { test('deleteSpecificFile', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testId="Test id"; const String testJwt="Test jwt"; final url = Uri.parse("${ApiRoutes.fileUrl}/$testId"); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.delete(url, headers: {'Authorization': 'Bearer $testJwt'})).thenAnswer((_) async => http.Response('', 201),); final FilesService apiService = FilesService(jwtService: jwtService, httpClient: httpClient); await apiService.deleteSpecificFile(testId); verify(httpClient.delete(url, headers: {'Authorization': 'Bearer $testJwt'})).called(1); }); test('deleteSpecificFile throws ClientException', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testId="Test id"; const String testJwt="Test jwt"; final url = Uri.parse("${ApiRoutes.fileUrl}/$testId"); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.delete(url, headers: {'Authorization': 'Bearer $testJwt'})).thenAnswer((_) async => http.Response('', 400),); final FilesService apiService = FilesService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.deleteSpecificFile(testId), throwsA(isA<ClientException>())); await untilCalled(httpClient.delete(url, headers: {'Authorization': 'Bearer $testJwt'})); verify(httpClient.delete(url, headers: {'Authorization': 'Bearer $testJwt'})).called(1); }); test('deleteSpecificFile throws ExistException', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testId="Test id"; const String testJwt="Test jwt"; final url = Uri.parse("${ApiRoutes.fileUrl}/$testId"); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.delete(url, headers: {'Authorization': 'Bearer $testJwt'})).thenAnswer((_) async => http.Response('', 404),); final FilesService apiService = FilesService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.deleteSpecificFile(testId), throwsA(isA<ExistException>())); await untilCalled(httpClient.delete(url, headers: {'Authorization': 'Bearer $testJwt'})); verify(httpClient.delete(url, headers: {'Authorization': 'Bearer $testJwt'})).called(1); }); test('deleteSpecificFile throws AuthException', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testId="Test id"; const String testJwt="Test jwt"; final url = Uri.parse("${ApiRoutes.fileUrl}/$testId"); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.delete(url, headers: {'Authorization': 'Bearer $testJwt'})).thenAnswer((_) async => http.Response('', 422),); final FilesService apiService = FilesService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.deleteSpecificFile(testId), throwsA(isA<AuthException>())); await untilCalled(httpClient.delete(url, headers: {'Authorization': 'Bearer $testJwt'})); verify(httpClient.delete(url, headers: {'Authorization': 'Bearer $testJwt'})).called(1); await untilCalled(jwtService.deleteJwt()); verify(jwtService.deleteJwt()).called(1); }); test('deleteSpecificFile throws ServerException', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testId="Test id"; const String testJwt="Test jwt"; final url = Uri.parse("${ApiRoutes.fileUrl}/$testId"); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.delete(url, headers: {'Authorization': 'Bearer $testJwt'})).thenAnswer( (_) async => http.Response('', 500), ); final FilesService apiService = FilesService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.deleteSpecificFile(testId), throwsA(isA<ServerException>())); await untilCalled(httpClient.delete(url, headers: {'Authorization': 'Bearer $testJwt'})); verify(httpClient.delete(url, headers: {'Authorization': 'Bearer $testJwt'})).called(1); }); test('deleteSpecificFile throws Other Exception', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testId="Test id"; const String testJwt="Test jwt"; final url = Uri.parse("${ApiRoutes.fileUrl}/$testId"); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.delete(url, headers: {'Authorization': 'Bearer $testJwt'})).thenAnswer( (_) async => http.Response('', 555), ); final FilesService apiService = FilesService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.deleteSpecificFile(testId), throwsA(isA<Exception>())); await untilCalled(httpClient.delete(url, headers: {'Authorization': 'Bearer $testJwt'})); verify(httpClient.delete(url, headers: {'Authorization': 'Bearer $testJwt'})).called(1); }); test('deleteSpecificFile throws AuthException(Jwt is null)', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testId="Test id"; when(jwtService.getJwt()).thenAnswer((_) async => null); final FilesService apiService = FilesService(jwtService: jwtService, httpClient: httpClient); expect(apiService.deleteSpecificFile(testId), throwsA(isA<AuthException>())); }); }); }
0
mirrored_repositories/study_savvy_app/test/api
mirrored_repositories/study_savvy_app/test/api/delete/delete_specific_file_test.mocks.dart
// Mocks generated by Mockito 5.4.2 from annotations // in study_savvy_app/test/api/delete/delete_specific_file_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i4; import 'dart:convert' as _i5; import 'dart:typed_data' as _i6; import 'package:http/http.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; import 'package:study_savvy_app/services/utils/jwt_storage.dart' as _i3; // 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 _FakeResponse_0 extends _i1.SmartFake implements _i2.Response { _FakeResponse_0( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeStreamedResponse_1 extends _i1.SmartFake implements _i2.StreamedResponse { _FakeStreamedResponse_1( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } /// A class which mocks [JwtService]. /// /// See the documentation for Mockito's code generation for more information. class MockJwtService extends _i1.Mock implements _i3.JwtService { MockJwtService() { _i1.throwOnMissingStub(this); } @override _i4.Future<void> saveJwt(String? jwt) => (super.noSuchMethod( Invocation.method( #saveJwt, [jwt], ), returnValue: _i4.Future<void>.value(), returnValueForMissingStub: _i4.Future<void>.value(), ) as _i4.Future<void>); @override _i4.Future<String?> getJwt() => (super.noSuchMethod( Invocation.method( #getJwt, [], ), returnValue: _i4.Future<String?>.value(), ) as _i4.Future<String?>); @override _i4.Future<void> deleteJwt() => (super.noSuchMethod( Invocation.method( #deleteJwt, [], ), returnValue: _i4.Future<void>.value(), returnValueForMissingStub: _i4.Future<void>.value(), ) as _i4.Future<void>); @override _i4.Future<bool?> hasJwt() => (super.noSuchMethod( Invocation.method( #hasJwt, [], ), returnValue: _i4.Future<bool?>.value(), ) as _i4.Future<bool?>); } /// A class which mocks [Client]. /// /// See the documentation for Mockito's code generation for more information. class MockClient extends _i1.Mock implements _i2.Client { MockClient() { _i1.throwOnMissingStub(this); } @override _i4.Future<_i2.Response> head( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #head, [url], {#headers: headers}, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #head, [url], {#headers: headers}, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> get( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #get, [url], {#headers: headers}, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #get, [url], {#headers: headers}, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> post( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #post, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #post, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> put( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #put, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #put, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> patch( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #patch, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #patch, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> delete( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #delete, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #delete, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<String> read( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #read, [url], {#headers: headers}, ), returnValue: _i4.Future<String>.value(''), ) as _i4.Future<String>); @override _i4.Future<_i6.Uint8List> readBytes( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #readBytes, [url], {#headers: headers}, ), returnValue: _i4.Future<_i6.Uint8List>.value(_i6.Uint8List(0)), ) as _i4.Future<_i6.Uint8List>); @override _i4.Future<_i2.StreamedResponse> send(_i2.BaseRequest? request) => (super.noSuchMethod( Invocation.method( #send, [request], ), returnValue: _i4.Future<_i2.StreamedResponse>.value(_FakeStreamedResponse_1( this, Invocation.method( #send, [request], ), )), ) as _i4.Future<_i2.StreamedResponse>); @override void close() => super.noSuchMethod( Invocation.method( #close, [], ), returnValueForMissingStub: null, ); }
0
mirrored_repositories/study_savvy_app/test/api
mirrored_repositories/study_savvy_app/test/api/delete/logout_test.mocks.dart
// Mocks generated by Mockito 5.4.2 from annotations // in study_savvy_app/test/api/delete/logout_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i4; import 'dart:convert' as _i5; import 'dart:typed_data' as _i6; import 'package:http/http.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; import 'package:study_savvy_app/services/utils/jwt_storage.dart' as _i3; // 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 _FakeResponse_0 extends _i1.SmartFake implements _i2.Response { _FakeResponse_0( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeStreamedResponse_1 extends _i1.SmartFake implements _i2.StreamedResponse { _FakeStreamedResponse_1( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } /// A class which mocks [JwtService]. /// /// See the documentation for Mockito's code generation for more information. class MockJwtService extends _i1.Mock implements _i3.JwtService { MockJwtService() { _i1.throwOnMissingStub(this); } @override _i4.Future<void> saveJwt(String? jwt) => (super.noSuchMethod( Invocation.method( #saveJwt, [jwt], ), returnValue: _i4.Future<void>.value(), returnValueForMissingStub: _i4.Future<void>.value(), ) as _i4.Future<void>); @override _i4.Future<String?> getJwt() => (super.noSuchMethod( Invocation.method( #getJwt, [], ), returnValue: _i4.Future<String?>.value(), ) as _i4.Future<String?>); @override _i4.Future<void> deleteJwt() => (super.noSuchMethod( Invocation.method( #deleteJwt, [], ), returnValue: _i4.Future<void>.value(), returnValueForMissingStub: _i4.Future<void>.value(), ) as _i4.Future<void>); @override _i4.Future<bool?> hasJwt() => (super.noSuchMethod( Invocation.method( #hasJwt, [], ), returnValue: _i4.Future<bool?>.value(), ) as _i4.Future<bool?>); } /// A class which mocks [Client]. /// /// See the documentation for Mockito's code generation for more information. class MockClient extends _i1.Mock implements _i2.Client { MockClient() { _i1.throwOnMissingStub(this); } @override _i4.Future<_i2.Response> head( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #head, [url], {#headers: headers}, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #head, [url], {#headers: headers}, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> get( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #get, [url], {#headers: headers}, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #get, [url], {#headers: headers}, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> post( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #post, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #post, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> put( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #put, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #put, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> patch( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #patch, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #patch, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> delete( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #delete, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #delete, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<String> read( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #read, [url], {#headers: headers}, ), returnValue: _i4.Future<String>.value(''), ) as _i4.Future<String>); @override _i4.Future<_i6.Uint8List> readBytes( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #readBytes, [url], {#headers: headers}, ), returnValue: _i4.Future<_i6.Uint8List>.value(_i6.Uint8List(0)), ) as _i4.Future<_i6.Uint8List>); @override _i4.Future<_i2.StreamedResponse> send(_i2.BaseRequest? request) => (super.noSuchMethod( Invocation.method( #send, [request], ), returnValue: _i4.Future<_i2.StreamedResponse>.value(_FakeStreamedResponse_1( this, Invocation.method( #send, [request], ), )), ) as _i4.Future<_i2.StreamedResponse>); @override void close() => super.noSuchMethod( Invocation.method( #close, [], ), returnValueForMissingStub: null, ); }
0
mirrored_repositories/study_savvy_app/test/api
mirrored_repositories/study_savvy_app/test/api/delete/logout_test.dart
import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:http/http.dart' as http; import 'package:mockito/mockito.dart'; import 'package:study_savvy_app/services/profile/api_profile.dart'; import 'package:study_savvy_app/services/api_routes.dart'; import 'package:study_savvy_app/services/utils/jwt_storage.dart'; import 'package:study_savvy_app/utils/exception.dart'; import 'logout_test.mocks.dart'; @GenerateMocks([JwtService, http.Client]) void main() { group("Delete method of logout", () { test('logout', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testJwt="Test jwt"; final url = Uri.parse(ApiRoutes.logoutUrl); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.delete(url, headers: {'Authorization': 'Bearer $testJwt'})).thenAnswer((_) async => http.Response('', 201),); final ProfileService apiService = ProfileService(jwtService: jwtService, httpClient: httpClient); await apiService.logout(); verify(httpClient.delete(url, headers: {'Authorization': 'Bearer $testJwt'})).called(1); }); test('logout throws ClientException', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testJwt="Test jwt"; final url = Uri.parse(ApiRoutes.logoutUrl); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.delete(url, headers: {'Authorization': 'Bearer $testJwt'})).thenAnswer((_) async => http.Response('', 400),); final ProfileService apiService = ProfileService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.logout(), throwsA(isA<ClientException>())); await untilCalled(httpClient.delete(url, headers: {'Authorization': 'Bearer $testJwt'})); verify(httpClient.delete(url, headers: {'Authorization': 'Bearer $testJwt'})).called(1); }); test('logout throws ExistException', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testJwt="Test jwt"; final url = Uri.parse(ApiRoutes.logoutUrl); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.delete(url, headers: {'Authorization': 'Bearer $testJwt'})).thenAnswer((_) async => http.Response('', 404),); final ProfileService apiService = ProfileService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.logout(), throwsA(isA<ExistException>())); await untilCalled(httpClient.delete(url, headers: {'Authorization': 'Bearer $testJwt'})); verify(httpClient.delete(url, headers: {'Authorization': 'Bearer $testJwt'})).called(1); }); test('logout throws AuthException', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testJwt="Test jwt"; final url = Uri.parse(ApiRoutes.logoutUrl); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.delete(url, headers: {'Authorization': 'Bearer $testJwt'})).thenAnswer((_) async => http.Response('', 422),); final ProfileService apiService = ProfileService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.logout(), throwsA(isA<AuthException>())); await untilCalled(httpClient.delete(url, headers: {'Authorization': 'Bearer $testJwt'})); verify(httpClient.delete(url, headers: {'Authorization': 'Bearer $testJwt'})).called(1); await untilCalled(jwtService.deleteJwt()); verify(jwtService.deleteJwt()).called(1); }); test('logout throws ServerException', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testJwt="Test jwt"; final url = Uri.parse(ApiRoutes.logoutUrl); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.delete(url, headers: {'Authorization': 'Bearer $testJwt'})).thenAnswer( (_) async => http.Response('', 500), ); final ProfileService apiService = ProfileService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.logout(), throwsA(isA<ServerException>())); await untilCalled(httpClient.delete(url, headers: {'Authorization': 'Bearer $testJwt'})); verify(httpClient.delete(url, headers: {'Authorization': 'Bearer $testJwt'})).called(1); }); test('logout throws Other Exception', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testJwt="Test jwt"; final url = Uri.parse(ApiRoutes.logoutUrl); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.delete(url, headers: {'Authorization': 'Bearer $testJwt'})).thenAnswer( (_) async => http.Response('', 555), ); final ProfileService apiService = ProfileService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.logout(), throwsA(isA<Exception>())); await untilCalled(httpClient.delete(url, headers: {'Authorization': 'Bearer $testJwt'})); verify(httpClient.delete(url, headers: {'Authorization': 'Bearer $testJwt'})).called(1); }); test('logout throws AuthException(Jwt is null)', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); when(jwtService.getJwt()).thenAnswer((_) async => null); final ProfileService apiService = ProfileService(jwtService: jwtService, httpClient: httpClient); expect(apiService.logout(), throwsA(isA<AuthException>())); }); }); }
0
mirrored_repositories/study_savvy_app/test/api
mirrored_repositories/study_savvy_app/test/api/get/get_profile_test.mocks.dart
// Mocks generated by Mockito 5.4.2 from annotations // in study_savvy_app/test/api/get/get_profile_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i4; import 'dart:convert' as _i5; import 'dart:typed_data' as _i6; import 'package:http/http.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; import 'package:study_savvy_app/services/utils/jwt_storage.dart' as _i3; // 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 _FakeResponse_0 extends _i1.SmartFake implements _i2.Response { _FakeResponse_0( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeStreamedResponse_1 extends _i1.SmartFake implements _i2.StreamedResponse { _FakeStreamedResponse_1( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } /// A class which mocks [JwtService]. /// /// See the documentation for Mockito's code generation for more information. class MockJwtService extends _i1.Mock implements _i3.JwtService { MockJwtService() { _i1.throwOnMissingStub(this); } @override _i4.Future<void> saveJwt(String? jwt) => (super.noSuchMethod( Invocation.method( #saveJwt, [jwt], ), returnValue: _i4.Future<void>.value(), returnValueForMissingStub: _i4.Future<void>.value(), ) as _i4.Future<void>); @override _i4.Future<String?> getJwt() => (super.noSuchMethod( Invocation.method( #getJwt, [], ), returnValue: _i4.Future<String?>.value(), ) as _i4.Future<String?>); @override _i4.Future<void> deleteJwt() => (super.noSuchMethod( Invocation.method( #deleteJwt, [], ), returnValue: _i4.Future<void>.value(), returnValueForMissingStub: _i4.Future<void>.value(), ) as _i4.Future<void>); @override _i4.Future<bool?> hasJwt() => (super.noSuchMethod( Invocation.method( #hasJwt, [], ), returnValue: _i4.Future<bool?>.value(), ) as _i4.Future<bool?>); } /// A class which mocks [Client]. /// /// See the documentation for Mockito's code generation for more information. class MockClient extends _i1.Mock implements _i2.Client { MockClient() { _i1.throwOnMissingStub(this); } @override _i4.Future<_i2.Response> head( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #head, [url], {#headers: headers}, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #head, [url], {#headers: headers}, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> get( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #get, [url], {#headers: headers}, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #get, [url], {#headers: headers}, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> post( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #post, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #post, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> put( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #put, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #put, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> patch( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #patch, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #patch, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> delete( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #delete, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #delete, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<String> read( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #read, [url], {#headers: headers}, ), returnValue: _i4.Future<String>.value(''), ) as _i4.Future<String>); @override _i4.Future<_i6.Uint8List> readBytes( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #readBytes, [url], {#headers: headers}, ), returnValue: _i4.Future<_i6.Uint8List>.value(_i6.Uint8List(0)), ) as _i4.Future<_i6.Uint8List>); @override _i4.Future<_i2.StreamedResponse> send(_i2.BaseRequest? request) => (super.noSuchMethod( Invocation.method( #send, [request], ), returnValue: _i4.Future<_i2.StreamedResponse>.value(_FakeStreamedResponse_1( this, Invocation.method( #send, [request], ), )), ) as _i4.Future<_i2.StreamedResponse>); @override void close() => super.noSuchMethod( Invocation.method( #close, [], ), returnValueForMissingStub: null, ); }
0
mirrored_repositories/study_savvy_app/test/api
mirrored_repositories/study_savvy_app/test/api/get/get_image_test.dart
import 'package:mockito/annotations.dart'; import 'package:http/http.dart' as http; import 'package:study_savvy_app/services/utils/jwt_storage.dart'; @GenerateMocks([JwtService, http.Client]) void main() {}
0
mirrored_repositories/study_savvy_app/test/api
mirrored_repositories/study_savvy_app/test/api/get/get_files_test.dart
import 'package:mockito/annotations.dart'; import 'package:http/http.dart' as http; import 'package:study_savvy_app/models/files/model_files.dart'; import 'package:study_savvy_app/services/utils/jwt_storage.dart'; @GenerateMocks([JwtService, http.Client,File]) void main() {}
0
mirrored_repositories/study_savvy_app/test/api
mirrored_repositories/study_savvy_app/test/api/get/get_audio_test.dart
import 'dart:typed_data'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:http/http.dart' as http; import 'package:mockito/mockito.dart'; import 'package:study_savvy_app/services/files/api_files.dart'; import 'package:study_savvy_app/services/api_routes.dart'; import 'package:study_savvy_app/services/utils/jwt_storage.dart'; import 'package:study_savvy_app/utils/exception.dart'; import 'get_audio_test.mocks.dart'; @GenerateMocks([JwtService, http.Client]) void main() { group("Get method of getAudio", (){ test('getAudio(Length of audio is 1000)', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testId="Test id"; const String testJwt="Test jwt"; final Uint8List testResult= Uint8List.fromList(List<int>.generate(1000, (index) => index)); final url = Uri.parse("${ApiRoutes.fileAudioUrl}/$testId"); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.get(url, headers: {'Authorization': 'Bearer $testJwt'})).thenAnswer((_) async => http.Response.bytes(testResult, 200)); final FilesService apiService = FilesService(jwtService: jwtService, httpClient: httpClient); final Uint8List result=await apiService.getAudio(testId); verify(httpClient.get(url, headers: {'Authorization': 'Bearer $testJwt'})).called(1); expect(result, equals(testResult)); expect(result, isA<Uint8List>()); }); test('getAudio(Length of audio is 10)', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testId="Test id"; const String testJwt="Test jwt"; final Uint8List testResult= Uint8List.fromList(List<int>.generate(10, (index) => index)); final url = Uri.parse("${ApiRoutes.fileAudioUrl}/$testId"); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.get(url, headers: {'Authorization': 'Bearer $testJwt'})).thenAnswer((_) async => http.Response.bytes(testResult, 200)); final FilesService apiService = FilesService(jwtService: jwtService, httpClient: httpClient); final Uint8List result=await apiService.getAudio(testId); verify(httpClient.get(url, headers: {'Authorization': 'Bearer $testJwt'})).called(1); expect(result, equals(testResult)); expect(result, isA<Uint8List>()); }); test('getAudio(Length of audio is 0)', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testId="Test id"; const String testJwt="Test jwt"; final Uint8List testResult= Uint8List.fromList(List<int>.generate(0, (index) => index)); final url = Uri.parse("${ApiRoutes.fileAudioUrl}/$testId"); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.get(url, headers: {'Authorization': 'Bearer $testJwt'})).thenAnswer((_) async => http.Response.bytes(testResult, 200)); final FilesService apiService = FilesService(jwtService: jwtService, httpClient: httpClient); final Uint8List result=await apiService.getAudio(testId); verify(httpClient.get(url, headers: {'Authorization': 'Bearer $testJwt'})).called(1); expect(result, equals(testResult)); expect(result, isA<Uint8List>()); }); test('getAudio throws ClientException', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testId="Test id"; const String testJwt="Test jwt"; final url = Uri.parse("${ApiRoutes.fileAudioUrl}/$testId"); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.get(url, headers: {'Authorization': 'Bearer $testJwt'})).thenAnswer((_) async => http.Response('', 400),); final FilesService apiService = FilesService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.getAudio(testId), throwsA(isA<ClientException>())); await untilCalled(httpClient.get(url, headers: {'Authorization': 'Bearer $testJwt'})); verify(httpClient.get(url, headers: {'Authorization': 'Bearer $testJwt'})).called(1); }); test('getAudio throws ExistException', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testId="Test id"; const String testJwt="Test jwt"; final url = Uri.parse("${ApiRoutes.fileAudioUrl}/$testId"); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.get(url, headers: {'Authorization': 'Bearer $testJwt'})).thenAnswer((_) async => http.Response('', 404),); final FilesService apiService = FilesService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.getAudio(testId), throwsA(isA<ExistException>())); await untilCalled(httpClient.get(url, headers: {'Authorization': 'Bearer $testJwt'})); verify(httpClient.get(url, headers: {'Authorization': 'Bearer $testJwt'})).called(1); }); test('getAudio throws AuthException', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testId="Test id"; const String testJwt="Test jwt"; final url = Uri.parse("${ApiRoutes.fileAudioUrl}/$testId"); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.get(url, headers: {'Authorization': 'Bearer $testJwt'})).thenAnswer((_) async => http.Response('', 422),); final FilesService apiService = FilesService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.getAudio(testId), throwsA(isA<AuthException>())); await untilCalled(httpClient.get(url, headers: {'Authorization': 'Bearer $testJwt'})); verify(httpClient.get(url, headers: {'Authorization': 'Bearer $testJwt'})).called(1); await untilCalled(jwtService.getJwt()); verify(jwtService.getJwt()).called(1); }); test('getAudio throws ServerException', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testId="Test id"; const String testJwt="Test jwt"; final url = Uri.parse("${ApiRoutes.fileAudioUrl}/$testId"); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.get(url, headers: {'Authorization': 'Bearer $testJwt'})).thenAnswer( (_) async => http.Response('', 500), ); final FilesService apiService = FilesService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.getAudio(testId), throwsA(isA<ServerException>())); await untilCalled(httpClient.get(url, headers: {'Authorization': 'Bearer $testJwt'})); verify(httpClient.get(url, headers: {'Authorization': 'Bearer $testJwt'})).called(1); }); test('getAudio throws Other Exception', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testId="Test id"; const String testJwt="Test jwt"; final url = Uri.parse("${ApiRoutes.fileAudioUrl}/$testId"); when(jwtService.getJwt()).thenAnswer((_) async => testJwt); when(httpClient.get(url, headers: {'Authorization': 'Bearer $testJwt'})).thenAnswer( (_) async => http.Response('', 555), ); final FilesService apiService = FilesService(jwtService: jwtService, httpClient: httpClient); expectLater(apiService.getAudio(testId), throwsA(isA<Exception>())); await untilCalled(httpClient.get(url, headers: {'Authorization': 'Bearer $testJwt'})); verify(httpClient.get(url, headers: {'Authorization': 'Bearer $testJwt'})).called(1); }); test('getAudio throws AuthException(Jwt is null)', () async { final jwtService = MockJwtService(); final httpClient = MockClient(); const String testId="Test id"; when(jwtService.getJwt()).thenAnswer((_) async => null); final FilesService apiService = FilesService(jwtService: jwtService, httpClient: httpClient); expect(apiService.getAudio(testId), throwsA(isA<AuthException>())); }); }); }
0
mirrored_repositories/study_savvy_app/test/api
mirrored_repositories/study_savvy_app/test/api/get/get_specific_file_test.dart
import 'package:mockito/annotations.dart'; import 'package:http/http.dart' as http; import 'package:study_savvy_app/services/utils/jwt_storage.dart'; @GenerateMocks([JwtService, http.Client]) void main() {}
0
mirrored_repositories/study_savvy_app/test/api
mirrored_repositories/study_savvy_app/test/api/get/get_files_test.mocks.dart
// Mocks generated by Mockito 5.4.2 from annotations // in study_savvy_app/test/api/get/get_files_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i4; import 'dart:convert' as _i5; import 'dart:typed_data' as _i6; import 'package:http/http.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; import 'package:study_savvy_app/models/files/model_files.dart' as _i7; import 'package:study_savvy_app/services/utils/jwt_storage.dart' as _i3; // 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 _FakeResponse_0 extends _i1.SmartFake implements _i2.Response { _FakeResponse_0( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeStreamedResponse_1 extends _i1.SmartFake implements _i2.StreamedResponse { _FakeStreamedResponse_1( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } /// A class which mocks [JwtService]. /// /// See the documentation for Mockito's code generation for more information. class MockJwtService extends _i1.Mock implements _i3.JwtService { MockJwtService() { _i1.throwOnMissingStub(this); } @override _i4.Future<void> saveJwt(String? jwt) => (super.noSuchMethod( Invocation.method( #saveJwt, [jwt], ), returnValue: _i4.Future<void>.value(), returnValueForMissingStub: _i4.Future<void>.value(), ) as _i4.Future<void>); @override _i4.Future<String?> getJwt() => (super.noSuchMethod( Invocation.method( #getJwt, [], ), returnValue: _i4.Future<String?>.value(), ) as _i4.Future<String?>); @override _i4.Future<void> deleteJwt() => (super.noSuchMethod( Invocation.method( #deleteJwt, [], ), returnValue: _i4.Future<void>.value(), returnValueForMissingStub: _i4.Future<void>.value(), ) as _i4.Future<void>); @override _i4.Future<bool?> hasJwt() => (super.noSuchMethod( Invocation.method( #hasJwt, [], ), returnValue: _i4.Future<bool?>.value(), ) as _i4.Future<bool?>); } /// A class which mocks [Client]. /// /// See the documentation for Mockito's code generation for more information. class MockClient extends _i1.Mock implements _i2.Client { MockClient() { _i1.throwOnMissingStub(this); } @override _i4.Future<_i2.Response> head( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #head, [url], {#headers: headers}, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #head, [url], {#headers: headers}, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> get( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #get, [url], {#headers: headers}, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #get, [url], {#headers: headers}, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> post( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #post, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #post, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> put( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #put, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #put, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> patch( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #patch, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #patch, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> delete( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #delete, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #delete, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<String> read( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #read, [url], {#headers: headers}, ), returnValue: _i4.Future<String>.value(''), ) as _i4.Future<String>); @override _i4.Future<_i6.Uint8List> readBytes( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #readBytes, [url], {#headers: headers}, ), returnValue: _i4.Future<_i6.Uint8List>.value(_i6.Uint8List(0)), ) as _i4.Future<_i6.Uint8List>); @override _i4.Future<_i2.StreamedResponse> send(_i2.BaseRequest? request) => (super.noSuchMethod( Invocation.method( #send, [request], ), returnValue: _i4.Future<_i2.StreamedResponse>.value(_FakeStreamedResponse_1( this, Invocation.method( #send, [request], ), )), ) as _i4.Future<_i2.StreamedResponse>); @override void close() => super.noSuchMethod( Invocation.method( #close, [], ), returnValueForMissingStub: null, ); } /// A class which mocks [File]. /// /// See the documentation for Mockito's code generation for more information. class MockFile extends _i1.Mock implements _i7.File { MockFile() { _i1.throwOnMissingStub(this); } @override String get id => (super.noSuchMethod( Invocation.getter(#id), returnValue: '', ) as String); @override String get time => (super.noSuchMethod( Invocation.getter(#time), returnValue: '', ) as String); @override String get status => (super.noSuchMethod( Invocation.getter(#status), returnValue: '', ) as String); @override String get type => (super.noSuchMethod( Invocation.getter(#type), returnValue: '', ) as String); }
0
mirrored_repositories/study_savvy_app/test/api
mirrored_repositories/study_savvy_app/test/api/get/get_audio_test.mocks.dart
// Mocks generated by Mockito 5.4.2 from annotations // in study_savvy_app/test/api/get/get_audio_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i4; import 'dart:convert' as _i5; import 'dart:typed_data' as _i6; import 'package:http/http.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; import 'package:study_savvy_app/services/utils/jwt_storage.dart' as _i3; // 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 _FakeResponse_0 extends _i1.SmartFake implements _i2.Response { _FakeResponse_0( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeStreamedResponse_1 extends _i1.SmartFake implements _i2.StreamedResponse { _FakeStreamedResponse_1( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } /// A class which mocks [JwtService]. /// /// See the documentation for Mockito's code generation for more information. class MockJwtService extends _i1.Mock implements _i3.JwtService { MockJwtService() { _i1.throwOnMissingStub(this); } @override _i4.Future<void> saveJwt(String? jwt) => (super.noSuchMethod( Invocation.method( #saveJwt, [jwt], ), returnValue: _i4.Future<void>.value(), returnValueForMissingStub: _i4.Future<void>.value(), ) as _i4.Future<void>); @override _i4.Future<String?> getJwt() => (super.noSuchMethod( Invocation.method( #getJwt, [], ), returnValue: _i4.Future<String?>.value(), ) as _i4.Future<String?>); @override _i4.Future<void> deleteJwt() => (super.noSuchMethod( Invocation.method( #deleteJwt, [], ), returnValue: _i4.Future<void>.value(), returnValueForMissingStub: _i4.Future<void>.value(), ) as _i4.Future<void>); @override _i4.Future<bool?> hasJwt() => (super.noSuchMethod( Invocation.method( #hasJwt, [], ), returnValue: _i4.Future<bool?>.value(), ) as _i4.Future<bool?>); } /// A class which mocks [Client]. /// /// See the documentation for Mockito's code generation for more information. class MockClient extends _i1.Mock implements _i2.Client { MockClient() { _i1.throwOnMissingStub(this); } @override _i4.Future<_i2.Response> head( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #head, [url], {#headers: headers}, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #head, [url], {#headers: headers}, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> get( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #get, [url], {#headers: headers}, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #get, [url], {#headers: headers}, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> post( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #post, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #post, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> put( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #put, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #put, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> patch( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #patch, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #patch, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> delete( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #delete, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #delete, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<String> read( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #read, [url], {#headers: headers}, ), returnValue: _i4.Future<String>.value(''), ) as _i4.Future<String>); @override _i4.Future<_i6.Uint8List> readBytes( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #readBytes, [url], {#headers: headers}, ), returnValue: _i4.Future<_i6.Uint8List>.value(_i6.Uint8List(0)), ) as _i4.Future<_i6.Uint8List>); @override _i4.Future<_i2.StreamedResponse> send(_i2.BaseRequest? request) => (super.noSuchMethod( Invocation.method( #send, [request], ), returnValue: _i4.Future<_i2.StreamedResponse>.value(_FakeStreamedResponse_1( this, Invocation.method( #send, [request], ), )), ) as _i4.Future<_i2.StreamedResponse>); @override void close() => super.noSuchMethod( Invocation.method( #close, [], ), returnValueForMissingStub: null, ); }
0
mirrored_repositories/study_savvy_app/test/api
mirrored_repositories/study_savvy_app/test/api/get/get_image_test.mocks.dart
// Mocks generated by Mockito 5.4.2 from annotations // in study_savvy_app/test/api/get/get_image_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i4; import 'dart:convert' as _i5; import 'dart:typed_data' as _i6; import 'package:http/http.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; import 'package:study_savvy_app/services/utils/jwt_storage.dart' as _i3; // 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 _FakeResponse_0 extends _i1.SmartFake implements _i2.Response { _FakeResponse_0( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeStreamedResponse_1 extends _i1.SmartFake implements _i2.StreamedResponse { _FakeStreamedResponse_1( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } /// A class which mocks [JwtService]. /// /// See the documentation for Mockito's code generation for more information. class MockJwtService extends _i1.Mock implements _i3.JwtService { MockJwtService() { _i1.throwOnMissingStub(this); } @override _i4.Future<void> saveJwt(String? jwt) => (super.noSuchMethod( Invocation.method( #saveJwt, [jwt], ), returnValue: _i4.Future<void>.value(), returnValueForMissingStub: _i4.Future<void>.value(), ) as _i4.Future<void>); @override _i4.Future<String?> getJwt() => (super.noSuchMethod( Invocation.method( #getJwt, [], ), returnValue: _i4.Future<String?>.value(), ) as _i4.Future<String?>); @override _i4.Future<void> deleteJwt() => (super.noSuchMethod( Invocation.method( #deleteJwt, [], ), returnValue: _i4.Future<void>.value(), returnValueForMissingStub: _i4.Future<void>.value(), ) as _i4.Future<void>); @override _i4.Future<bool?> hasJwt() => (super.noSuchMethod( Invocation.method( #hasJwt, [], ), returnValue: _i4.Future<bool?>.value(), ) as _i4.Future<bool?>); } /// A class which mocks [Client]. /// /// See the documentation for Mockito's code generation for more information. class MockClient extends _i1.Mock implements _i2.Client { MockClient() { _i1.throwOnMissingStub(this); } @override _i4.Future<_i2.Response> head( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #head, [url], {#headers: headers}, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #head, [url], {#headers: headers}, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> get( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #get, [url], {#headers: headers}, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #get, [url], {#headers: headers}, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> post( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #post, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #post, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> put( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #put, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #put, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> patch( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #patch, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #patch, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> delete( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #delete, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #delete, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<String> read( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #read, [url], {#headers: headers}, ), returnValue: _i4.Future<String>.value(''), ) as _i4.Future<String>); @override _i4.Future<_i6.Uint8List> readBytes( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #readBytes, [url], {#headers: headers}, ), returnValue: _i4.Future<_i6.Uint8List>.value(_i6.Uint8List(0)), ) as _i4.Future<_i6.Uint8List>); @override _i4.Future<_i2.StreamedResponse> send(_i2.BaseRequest? request) => (super.noSuchMethod( Invocation.method( #send, [request], ), returnValue: _i4.Future<_i2.StreamedResponse>.value(_FakeStreamedResponse_1( this, Invocation.method( #send, [request], ), )), ) as _i4.Future<_i2.StreamedResponse>); @override void close() => super.noSuchMethod( Invocation.method( #close, [], ), returnValueForMissingStub: null, ); }
0
mirrored_repositories/study_savvy_app/test/api
mirrored_repositories/study_savvy_app/test/api/get/get_specific_file_test.mocks.dart
// Mocks generated by Mockito 5.4.2 from annotations // in study_savvy_app/test/api/get/get_specific_file_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i4; import 'dart:convert' as _i5; import 'dart:typed_data' as _i6; import 'package:http/http.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; import 'package:study_savvy_app/services/utils/jwt_storage.dart' as _i3; // 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 _FakeResponse_0 extends _i1.SmartFake implements _i2.Response { _FakeResponse_0( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeStreamedResponse_1 extends _i1.SmartFake implements _i2.StreamedResponse { _FakeStreamedResponse_1( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } /// A class which mocks [JwtService]. /// /// See the documentation for Mockito's code generation for more information. class MockJwtService extends _i1.Mock implements _i3.JwtService { MockJwtService() { _i1.throwOnMissingStub(this); } @override _i4.Future<void> saveJwt(String? jwt) => (super.noSuchMethod( Invocation.method( #saveJwt, [jwt], ), returnValue: _i4.Future<void>.value(), returnValueForMissingStub: _i4.Future<void>.value(), ) as _i4.Future<void>); @override _i4.Future<String?> getJwt() => (super.noSuchMethod( Invocation.method( #getJwt, [], ), returnValue: _i4.Future<String?>.value(), ) as _i4.Future<String?>); @override _i4.Future<void> deleteJwt() => (super.noSuchMethod( Invocation.method( #deleteJwt, [], ), returnValue: _i4.Future<void>.value(), returnValueForMissingStub: _i4.Future<void>.value(), ) as _i4.Future<void>); @override _i4.Future<bool?> hasJwt() => (super.noSuchMethod( Invocation.method( #hasJwt, [], ), returnValue: _i4.Future<bool?>.value(), ) as _i4.Future<bool?>); } /// A class which mocks [Client]. /// /// See the documentation for Mockito's code generation for more information. class MockClient extends _i1.Mock implements _i2.Client { MockClient() { _i1.throwOnMissingStub(this); } @override _i4.Future<_i2.Response> head( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #head, [url], {#headers: headers}, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #head, [url], {#headers: headers}, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> get( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #get, [url], {#headers: headers}, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #get, [url], {#headers: headers}, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> post( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #post, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #post, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> put( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #put, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #put, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> patch( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #patch, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #patch, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<_i2.Response> delete( Uri? url, { Map<String, String>? headers, Object? body, _i5.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #delete, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i4.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #delete, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i4.Future<_i2.Response>); @override _i4.Future<String> read( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #read, [url], {#headers: headers}, ), returnValue: _i4.Future<String>.value(''), ) as _i4.Future<String>); @override _i4.Future<_i6.Uint8List> readBytes( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #readBytes, [url], {#headers: headers}, ), returnValue: _i4.Future<_i6.Uint8List>.value(_i6.Uint8List(0)), ) as _i4.Future<_i6.Uint8List>); @override _i4.Future<_i2.StreamedResponse> send(_i2.BaseRequest? request) => (super.noSuchMethod( Invocation.method( #send, [request], ), returnValue: _i4.Future<_i2.StreamedResponse>.value(_FakeStreamedResponse_1( this, Invocation.method( #send, [request], ), )), ) as _i4.Future<_i2.StreamedResponse>); @override void close() => super.noSuchMethod( Invocation.method( #close, [], ), returnValueForMissingStub: null, ); }
0
mirrored_repositories/study_savvy_app/test/api
mirrored_repositories/study_savvy_app/test/api/get/get_profile_test.dart
import 'package:mockito/annotations.dart'; import 'package:http/http.dart' as http; import 'package:study_savvy_app/services/utils/jwt_storage.dart'; @GenerateMocks([JwtService, http.Client]) void main() {}
0
mirrored_repositories/study_savvy_app/test
mirrored_repositories/study_savvy_app/test/provider/ocr_image_provider_test.dart
import 'dart:io'; import 'dart:typed_data'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'package:study_savvy_app/blocs/provider/ocr_image_provider.dart'; import 'ocr_image_provider_test.mocks.dart'; @GenerateMocks([File]) void main(){ group('OCRImageProvider Test', () { test('Initial state is null', () { final ocrImageProvider = OCRImageProvider(); expect(ocrImageProvider.image, null); expect(ocrImageProvider.path, null); expect(ocrImageProvider.file, null); expect(ocrImageProvider.isNull(), true); }); test('Set method sets image, path, file and calls notifyListeners(Length of Image is 1000)', () async { final testFile = MockFile(); const String testPath= "Test path"; final testImage = Uint8List.fromList(List<int>.generate(1000, (index) => index % 256)); when(testFile.path).thenReturn(testPath); when(testFile.readAsBytes()).thenAnswer((_) async => testImage); final ocrImageProvider = OCRImageProvider(); await ocrImageProvider.set(testFile); expect(ocrImageProvider.image, testImage); expect(ocrImageProvider.path, testPath); expect(ocrImageProvider.file, testFile); expect(ocrImageProvider.isNull(), false); }); test('Set method sets image, path, file and calls notifyListeners(Length of Image is 10)', () async { final testFile = MockFile(); const String testPath= "Test path"; final testImage = Uint8List.fromList(List<int>.generate(10, (index) => index % 256)); when(testFile.path).thenReturn(testPath); when(testFile.readAsBytes()).thenAnswer((_) async => testImage); final ocrImageProvider = OCRImageProvider(); await ocrImageProvider.set(testFile); expect(ocrImageProvider.image, testImage); expect(ocrImageProvider.path, testPath); expect(ocrImageProvider.file, testFile); expect(ocrImageProvider.isNull(), false); }); test('Set method sets image, path, file and calls notifyListeners(Length of Image is 0)', () async { final testFile = MockFile(); const String testPath= "Test path"; final testImage = Uint8List.fromList(List<int>.generate(0, (index) => index % 256)); when(testFile.path).thenReturn(testPath); when(testFile.readAsBytes()).thenAnswer((_) async => testImage); final ocrImageProvider = OCRImageProvider(); await ocrImageProvider.set(testFile); expect(ocrImageProvider.image, testImage); expect(ocrImageProvider.path, testPath); expect(ocrImageProvider.file, testFile); expect(ocrImageProvider.isNull(), false); }); test('Clear method clear image, path, file and calls notifyListeners(Length of Image is 10)', () async { final testFile = MockFile(); const String testPath= "Test path"; final testImage = Uint8List.fromList(List<int>.generate(10, (index) => index % 256)); when(testFile.path).thenReturn(testPath); when(testFile.readAsBytes()).thenAnswer((_) async => testImage); final ocrImageProvider = OCRImageProvider(); await ocrImageProvider.set(testFile); expect(ocrImageProvider.image, testImage); expect(ocrImageProvider.path, testPath); expect(ocrImageProvider.file, testFile); expect(ocrImageProvider.isNull(), false); ocrImageProvider.clear(); expect(ocrImageProvider.image,null); expect(ocrImageProvider.path, null); expect(ocrImageProvider.file, null); expect(ocrImageProvider.isNull(), true); }); }); }
0
mirrored_repositories/study_savvy_app/test
mirrored_repositories/study_savvy_app/test/provider/theme_provider_test.dart
import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:study_savvy_app/blocs/provider/theme_provider.dart'; void main() { group('ThemeProvider Test', () { test('Initial themeMode is system', () { final themeProvider = ThemeProvider(); expect(themeProvider.themeMode, ThemeMode.system); }); test('Setting themeMode changes themeMode', () { final themeProvider = ThemeProvider(); themeProvider.themeMode = ThemeMode.light; expect(themeProvider.themeMode, ThemeMode.light); }); test('Toggle theme changes themeMode from light to dark', () { final themeProvider = ThemeProvider(); themeProvider.themeMode = ThemeMode.light; themeProvider.toggleTheme(); expect(themeProvider.themeMode, ThemeMode.dark); }); test('Toggle theme changes themeMode from dark to light', () { final themeProvider = ThemeProvider(); themeProvider.themeMode = ThemeMode.dark; themeProvider.toggleTheme(); expect(themeProvider.themeMode, ThemeMode.light); }); test('Toggle theme changes themeMode from system to light', () { final themeProvider = ThemeProvider(); themeProvider.themeMode = ThemeMode.system; themeProvider.toggleTheme(); expect(themeProvider.themeMode, ThemeMode.light); }); }); }
0
mirrored_repositories/study_savvy_app/test
mirrored_repositories/study_savvy_app/test/provider/ocr_image_provider_test.mocks.dart
// Mocks generated by Mockito 5.4.2 from annotations // in study_savvy_app/test/provider/ocr_image_provider_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i3; import 'dart:convert' as _i4; import 'dart:io' as _i2; import 'dart:typed_data' as _i5; 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 _FakeFile_0 extends _i1.SmartFake implements _i2.File { _FakeFile_0( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeUri_1 extends _i1.SmartFake implements Uri { _FakeUri_1( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeDirectory_2 extends _i1.SmartFake implements _i2.Directory { _FakeDirectory_2( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeDateTime_3 extends _i1.SmartFake implements DateTime { _FakeDateTime_3( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeRandomAccessFile_4 extends _i1.SmartFake implements _i2.RandomAccessFile { _FakeRandomAccessFile_4( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeIOSink_5 extends _i1.SmartFake implements _i2.IOSink { _FakeIOSink_5( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeFileStat_6 extends _i1.SmartFake implements _i2.FileStat { _FakeFileStat_6( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeFileSystemEntity_7 extends _i1.SmartFake implements _i2.FileSystemEntity { _FakeFileSystemEntity_7( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } /// A class which mocks [File]. /// /// See the documentation for Mockito's code generation for more information. class MockFile extends _i1.Mock implements _i2.File { MockFile() { _i1.throwOnMissingStub(this); } @override _i2.File get absolute => (super.noSuchMethod( Invocation.getter(#absolute), returnValue: _FakeFile_0( this, Invocation.getter(#absolute), ), ) as _i2.File); @override String get path => (super.noSuchMethod( Invocation.getter(#path), returnValue: '', ) as String); @override Uri get uri => (super.noSuchMethod( Invocation.getter(#uri), returnValue: _FakeUri_1( this, Invocation.getter(#uri), ), ) as Uri); @override bool get isAbsolute => (super.noSuchMethod( Invocation.getter(#isAbsolute), returnValue: false, ) as bool); @override _i2.Directory get parent => (super.noSuchMethod( Invocation.getter(#parent), returnValue: _FakeDirectory_2( this, Invocation.getter(#parent), ), ) as _i2.Directory); @override _i3.Future<_i2.File> create({ bool? recursive = false, bool? exclusive = false, }) => (super.noSuchMethod( Invocation.method( #create, [], { #recursive: recursive, #exclusive: exclusive, }, ), returnValue: _i3.Future<_i2.File>.value(_FakeFile_0( this, Invocation.method( #create, [], { #recursive: recursive, #exclusive: exclusive, }, ), )), ) as _i3.Future<_i2.File>); @override void createSync({ bool? recursive = false, bool? exclusive = false, }) => super.noSuchMethod( Invocation.method( #createSync, [], { #recursive: recursive, #exclusive: exclusive, }, ), returnValueForMissingStub: null, ); @override _i3.Future<_i2.File> rename(String? newPath) => (super.noSuchMethod( Invocation.method( #rename, [newPath], ), returnValue: _i3.Future<_i2.File>.value(_FakeFile_0( this, Invocation.method( #rename, [newPath], ), )), ) as _i3.Future<_i2.File>); @override _i2.File renameSync(String? newPath) => (super.noSuchMethod( Invocation.method( #renameSync, [newPath], ), returnValue: _FakeFile_0( this, Invocation.method( #renameSync, [newPath], ), ), ) as _i2.File); @override _i3.Future<_i2.File> copy(String? newPath) => (super.noSuchMethod( Invocation.method( #copy, [newPath], ), returnValue: _i3.Future<_i2.File>.value(_FakeFile_0( this, Invocation.method( #copy, [newPath], ), )), ) as _i3.Future<_i2.File>); @override _i2.File copySync(String? newPath) => (super.noSuchMethod( Invocation.method( #copySync, [newPath], ), returnValue: _FakeFile_0( this, Invocation.method( #copySync, [newPath], ), ), ) as _i2.File); @override _i3.Future<int> length() => (super.noSuchMethod( Invocation.method( #length, [], ), returnValue: _i3.Future<int>.value(0), ) as _i3.Future<int>); @override int lengthSync() => (super.noSuchMethod( Invocation.method( #lengthSync, [], ), returnValue: 0, ) as int); @override _i3.Future<DateTime> lastAccessed() => (super.noSuchMethod( Invocation.method( #lastAccessed, [], ), returnValue: _i3.Future<DateTime>.value(_FakeDateTime_3( this, Invocation.method( #lastAccessed, [], ), )), ) as _i3.Future<DateTime>); @override DateTime lastAccessedSync() => (super.noSuchMethod( Invocation.method( #lastAccessedSync, [], ), returnValue: _FakeDateTime_3( this, Invocation.method( #lastAccessedSync, [], ), ), ) as DateTime); @override _i3.Future<dynamic> setLastAccessed(DateTime? time) => (super.noSuchMethod( Invocation.method( #setLastAccessed, [time], ), returnValue: _i3.Future<dynamic>.value(), ) as _i3.Future<dynamic>); @override void setLastAccessedSync(DateTime? time) => super.noSuchMethod( Invocation.method( #setLastAccessedSync, [time], ), returnValueForMissingStub: null, ); @override _i3.Future<DateTime> lastModified() => (super.noSuchMethod( Invocation.method( #lastModified, [], ), returnValue: _i3.Future<DateTime>.value(_FakeDateTime_3( this, Invocation.method( #lastModified, [], ), )), ) as _i3.Future<DateTime>); @override DateTime lastModifiedSync() => (super.noSuchMethod( Invocation.method( #lastModifiedSync, [], ), returnValue: _FakeDateTime_3( this, Invocation.method( #lastModifiedSync, [], ), ), ) as DateTime); @override _i3.Future<dynamic> setLastModified(DateTime? time) => (super.noSuchMethod( Invocation.method( #setLastModified, [time], ), returnValue: _i3.Future<dynamic>.value(), ) as _i3.Future<dynamic>); @override void setLastModifiedSync(DateTime? time) => super.noSuchMethod( Invocation.method( #setLastModifiedSync, [time], ), returnValueForMissingStub: null, ); @override _i3.Future<_i2.RandomAccessFile> open( {_i2.FileMode? mode = _i2.FileMode.read}) => (super.noSuchMethod( Invocation.method( #open, [], {#mode: mode}, ), returnValue: _i3.Future<_i2.RandomAccessFile>.value(_FakeRandomAccessFile_4( this, Invocation.method( #open, [], {#mode: mode}, ), )), ) as _i3.Future<_i2.RandomAccessFile>); @override _i2.RandomAccessFile openSync({_i2.FileMode? mode = _i2.FileMode.read}) => (super.noSuchMethod( Invocation.method( #openSync, [], {#mode: mode}, ), returnValue: _FakeRandomAccessFile_4( this, Invocation.method( #openSync, [], {#mode: mode}, ), ), ) as _i2.RandomAccessFile); @override _i3.Stream<List<int>> openRead([ int? start, int? end, ]) => (super.noSuchMethod( Invocation.method( #openRead, [ start, end, ], ), returnValue: _i3.Stream<List<int>>.empty(), ) as _i3.Stream<List<int>>); @override _i2.IOSink openWrite({ _i2.FileMode? mode = _i2.FileMode.write, _i4.Encoding? encoding = const _i4.Utf8Codec(), }) => (super.noSuchMethod( Invocation.method( #openWrite, [], { #mode: mode, #encoding: encoding, }, ), returnValue: _FakeIOSink_5( this, Invocation.method( #openWrite, [], { #mode: mode, #encoding: encoding, }, ), ), ) as _i2.IOSink); @override _i3.Future<_i5.Uint8List> readAsBytes() => (super.noSuchMethod( Invocation.method( #readAsBytes, [], ), returnValue: _i3.Future<_i5.Uint8List>.value(_i5.Uint8List(0)), ) as _i3.Future<_i5.Uint8List>); @override _i5.Uint8List readAsBytesSync() => (super.noSuchMethod( Invocation.method( #readAsBytesSync, [], ), returnValue: _i5.Uint8List(0), ) as _i5.Uint8List); @override _i3.Future<String> readAsString( {_i4.Encoding? encoding = const _i4.Utf8Codec()}) => (super.noSuchMethod( Invocation.method( #readAsString, [], {#encoding: encoding}, ), returnValue: _i3.Future<String>.value(''), ) as _i3.Future<String>); @override String readAsStringSync({_i4.Encoding? encoding = const _i4.Utf8Codec()}) => (super.noSuchMethod( Invocation.method( #readAsStringSync, [], {#encoding: encoding}, ), returnValue: '', ) as String); @override _i3.Future<List<String>> readAsLines( {_i4.Encoding? encoding = const _i4.Utf8Codec()}) => (super.noSuchMethod( Invocation.method( #readAsLines, [], {#encoding: encoding}, ), returnValue: _i3.Future<List<String>>.value(<String>[]), ) as _i3.Future<List<String>>); @override List<String> readAsLinesSync( {_i4.Encoding? encoding = const _i4.Utf8Codec()}) => (super.noSuchMethod( Invocation.method( #readAsLinesSync, [], {#encoding: encoding}, ), returnValue: <String>[], ) as List<String>); @override _i3.Future<_i2.File> writeAsBytes( List<int>? bytes, { _i2.FileMode? mode = _i2.FileMode.write, bool? flush = false, }) => (super.noSuchMethod( Invocation.method( #writeAsBytes, [bytes], { #mode: mode, #flush: flush, }, ), returnValue: _i3.Future<_i2.File>.value(_FakeFile_0( this, Invocation.method( #writeAsBytes, [bytes], { #mode: mode, #flush: flush, }, ), )), ) as _i3.Future<_i2.File>); @override void writeAsBytesSync( List<int>? bytes, { _i2.FileMode? mode = _i2.FileMode.write, bool? flush = false, }) => super.noSuchMethod( Invocation.method( #writeAsBytesSync, [bytes], { #mode: mode, #flush: flush, }, ), returnValueForMissingStub: null, ); @override _i3.Future<_i2.File> writeAsString( String? contents, { _i2.FileMode? mode = _i2.FileMode.write, _i4.Encoding? encoding = const _i4.Utf8Codec(), bool? flush = false, }) => (super.noSuchMethod( Invocation.method( #writeAsString, [contents], { #mode: mode, #encoding: encoding, #flush: flush, }, ), returnValue: _i3.Future<_i2.File>.value(_FakeFile_0( this, Invocation.method( #writeAsString, [contents], { #mode: mode, #encoding: encoding, #flush: flush, }, ), )), ) as _i3.Future<_i2.File>); @override void writeAsStringSync( String? contents, { _i2.FileMode? mode = _i2.FileMode.write, _i4.Encoding? encoding = const _i4.Utf8Codec(), bool? flush = false, }) => super.noSuchMethod( Invocation.method( #writeAsStringSync, [contents], { #mode: mode, #encoding: encoding, #flush: flush, }, ), returnValueForMissingStub: null, ); @override _i3.Future<bool> exists() => (super.noSuchMethod( Invocation.method( #exists, [], ), returnValue: _i3.Future<bool>.value(false), ) as _i3.Future<bool>); @override bool existsSync() => (super.noSuchMethod( Invocation.method( #existsSync, [], ), returnValue: false, ) as bool); @override _i3.Future<String> resolveSymbolicLinks() => (super.noSuchMethod( Invocation.method( #resolveSymbolicLinks, [], ), returnValue: _i3.Future<String>.value(''), ) as _i3.Future<String>); @override String resolveSymbolicLinksSync() => (super.noSuchMethod( Invocation.method( #resolveSymbolicLinksSync, [], ), returnValue: '', ) as String); @override _i3.Future<_i2.FileStat> stat() => (super.noSuchMethod( Invocation.method( #stat, [], ), returnValue: _i3.Future<_i2.FileStat>.value(_FakeFileStat_6( this, Invocation.method( #stat, [], ), )), ) as _i3.Future<_i2.FileStat>); @override _i2.FileStat statSync() => (super.noSuchMethod( Invocation.method( #statSync, [], ), returnValue: _FakeFileStat_6( this, Invocation.method( #statSync, [], ), ), ) as _i2.FileStat); @override _i3.Future<_i2.FileSystemEntity> delete({bool? recursive = false}) => (super.noSuchMethod( Invocation.method( #delete, [], {#recursive: recursive}, ), returnValue: _i3.Future<_i2.FileSystemEntity>.value(_FakeFileSystemEntity_7( this, Invocation.method( #delete, [], {#recursive: recursive}, ), )), ) as _i3.Future<_i2.FileSystemEntity>); @override void deleteSync({bool? recursive = false}) => super.noSuchMethod( Invocation.method( #deleteSync, [], {#recursive: recursive}, ), returnValueForMissingStub: null, ); @override _i3.Stream<_i2.FileSystemEvent> watch({ int? events = 15, bool? recursive = false, }) => (super.noSuchMethod( Invocation.method( #watch, [], { #events: events, #recursive: recursive, }, ), returnValue: _i3.Stream<_i2.FileSystemEvent>.empty(), ) as _i3.Stream<_i2.FileSystemEvent>); }
0
mirrored_repositories/hodler
mirrored_repositories/hodler/lib/main.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:hodler/Application/Presentation/HomePage/home_page.dart'; import 'package:hodler/Data/crypto_api_local.dart'; import 'package:hodler/Data/my_db.dart'; import 'package:sqflite_common_ffi/sqflite_ffi.dart'; import 'Application/BusinessLogic/bloc/cryptoList/crypto_list_bloc.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); sqfliteFfiInit(); runApp(MultiBlocProvider( providers: [ BlocProvider(create: (_) => CryptoListBloc(CryptoAPILocal(), MyDB())), ], child: const MyApp(), )); } class MyApp extends StatefulWidget { const MyApp({super.key}); @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { @override void initState() { BlocProvider.of<CryptoListBloc>(context).add(CryptoListEventInit()); super.initState(); } @override Widget build(BuildContext context) { return MaterialApp( title: 'Hodler', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), useMaterial3: true, ), home: const HomePage()); } }
0
mirrored_repositories/hodler/lib/Domain
mirrored_repositories/hodler/lib/Domain/Repository/crypto_repository_data.dart
import 'package:hodler/Data/model/crypto.dart'; abstract class CryptoRepositoryData { Future<List<Crypto>> getAllCrypto(); Future<List<Crypto>> updateCrypto(); Future<num> getCurrentValueCrypto({required String idCrypto}); }
0
mirrored_repositories/hodler/lib/Domain
mirrored_repositories/hodler/lib/Domain/Repository/hodler_repository_db.dart
import '../../Data/model/deposit_cypto.dart'; abstract class HolderRepositoryDB { static const String nameDB = "holder.db"; static const String nameTableDB = "hodlerDeposit"; static const String fieldId = "id"; static const String fieldAcronym = "acronym"; static const String fieldDate = "date"; static const String fieldImport = "import"; static const String fieldValueWhenBuy = "valueBuy"; static const String fieldIdCrypto = "idCrypto"; Future<void> initDb(); Future<List<DepositCrypto>> getAllDepositCrypto(); Future<bool> addDeposit(DepositCrypto newDeposit); Future<bool> removeDeposit(String idDeposit); Future<List<DepositCrypto>> getDepositByCrypto(String cryptoNameOrAcronym); }
0
mirrored_repositories/hodler/lib
mirrored_repositories/hodler/lib/Data/crypto_api_local.dart
import 'dart:convert'; import 'package:flutter/services.dart'; import 'package:hodler/Data/crypto_api.dart'; import 'package:hodler/Data/model/crypto.dart'; import 'package:hodler/Domain/Repository/crypto_repository_data.dart'; class CryptoAPILocal implements CryptoRepositoryData { final String fieldId = "id"; final String fieldName = "name"; final String fieldSymbol = "symbol"; final String fieldImage = "image"; final String fieldPrice = "current_price"; final String fieldHigth24 = "high_24h"; final String fieldLow24 = "low_24h"; final String fieldChangePrecent24 = "price_change_percentage_24h_in_currency"; final String fieldChangePrecent7Days = "price_change_percentage_7d_in_currency"; @override Future<List<Crypto>> getAllCrypto() async { final String response = await rootBundle.loadString('assets/data.json'); List<dynamic> listDirty = await jsonDecode(response); return listDirty.map((element) { Crypto el = Crypto( id: element[fieldId], name: element[fieldName], acronym: element[fieldSymbol], price: element[fieldPrice], higth24: element[fieldHigth24], low24: element[fieldLow24], urlImage: element[fieldImage], changePrecent24: element[fieldChangePrecent24], changePrecent7Days: element[fieldChangePrecent7Days]); return el; }).toList(); } @override Future<List<Crypto>> updateCrypto() { return getAllCrypto(); } static Future<Crypto?> getCryptoByAcronym(String id) async { final String response = await rootBundle.loadString('assets/data.json'); List<Map<String, dynamic>> listDirty = await jsonDecode(response); Map<String, dynamic> elfind = listDirty.where((element) => element[CryptoAPI().fieldId] == id).first; if (elfind.isNotEmpty) { return Crypto( id: elfind[CryptoAPI().fieldId], name: elfind[CryptoAPI().fieldName], acronym: elfind[CryptoAPI().fieldSymbol], price: elfind[CryptoAPI().fieldPrice], higth24: elfind[CryptoAPI().fieldHigth24], low24: elfind[CryptoAPI().fieldLow24], urlImage: elfind[CryptoAPI().fieldImage], changePrecent24: elfind[CryptoAPI().fieldChangePrecent24], changePrecent7Days: elfind[CryptoAPI().fieldChangePrecent7Days]); } return null; } @override Future<num> getCurrentValueCrypto({required String idCrypto}) async { final String response = await rootBundle.loadString('assets/data.json'); List<dynamic> listDirty = await jsonDecode(response); Map<String, dynamic> elfind = listDirty .where((element) => element[CryptoAPI().fieldId] == idCrypto) .first; return elfind[fieldPrice]; } }
0
mirrored_repositories/hodler/lib
mirrored_repositories/hodler/lib/Data/my_db.dart
import 'package:hodler/Domain/Repository/hodler_repository_db.dart'; import 'package:path/path.dart'; import 'package:sqflite_common_ffi/sqflite_ffi.dart'; import 'model/deposit_cypto.dart'; class MyDB implements HolderRepositoryDB { late final Database db; @override Future<void> initDb() async { var databaseFactory = databaseFactoryFfi; db = await databaseFactory.openDatabase( join(await databaseFactoryFfi.getDatabasesPath(), HolderRepositoryDB.nameDB), options: OpenDatabaseOptions( version: 1, onCreate: (Database db, int version) async { await db.execute( """ CREATE TABLE ${HolderRepositoryDB.nameTableDB}( ${HolderRepositoryDB.fieldId} TEXT PRIMARY KEY, ${HolderRepositoryDB.fieldIdCrypto} TEXT NOT NULL, ${HolderRepositoryDB.fieldImport} REAL NOT NULL, ${HolderRepositoryDB.fieldValueWhenBuy} REAL NOT NULL, ${HolderRepositoryDB.fieldDate} INTEGER NOT NULL ) """, ); }), ); } @override Future<bool> addDeposit(DepositCrypto newDeposit) async { final result = await db.insert(HolderRepositoryDB.nameTableDB, newDeposit.toJson()); return result != 0; } @override Future<List<DepositCrypto>> getAllDepositCrypto() async { final List<Map<String, dynamic>> result = await db.query(HolderRepositoryDB.nameTableDB); List<DepositCrypto> out = []; for (var element in result) { out.add(DepositCrypto.fromJson(element)); } return out; } @override Future<List<DepositCrypto>> getDepositByCrypto(String cryptoAcronym) async { final List<Map<String, dynamic>> result = await db.query( HolderRepositoryDB.nameTableDB, where: "${HolderRepositoryDB.fieldAcronym}= ?", whereArgs: [cryptoAcronym]); return result.map((e) => DepositCrypto.fromJson(e)).toList(); } @override Future<bool> removeDeposit(String idDeposit) async { final int result = await db.delete(HolderRepositoryDB.nameTableDB, where: "${HolderRepositoryDB.fieldId}= ?", whereArgs: [idDeposit]); return result == 1; } }
0
mirrored_repositories/hodler/lib
mirrored_repositories/hodler/lib/Data/crypto_api.dart
import 'dart:convert'; import 'dart:developer'; import 'package:hodler/Data/model/crypto.dart'; import 'package:hodler/Domain/Repository/crypto_repository_data.dart'; import 'package:http/http.dart' as http; class CryptoAPI implements CryptoRepositoryData { final String fieldId = "id"; final String fieldName = "name"; final String fieldSymbol = "symbol"; final String fieldImage = "image"; final String fieldPrice = "current_price"; final String fieldHigth24 = "high_24h"; final String fieldLow24 = "low_24h"; final String fieldChangePrecent24 = "price_change_percentage_24h_in_currency"; final String fieldChangePrecent7Days = "price_change_percentage_7d_in_currency"; @override Future<List<Crypto>> getAllCrypto() async { try { Uri url = Uri.https("api.coingecko.com", '/api/v3/coins/markets', { 'vs_currency': 'usd', 'order': 'market_cap_desc', 'per_page': "100", 'page': "1", 'sparkline': "false", 'price_change_percentage': '24h,7d', 'locale': "en", 'precision': '3' }); final response = await http.get(url); if (response.statusCode == 200) { List<dynamic> listDirty = await jsonDecode(response.body); List<Crypto> out = []; for (var e in listDirty) { out.add(Crypto( id: e[fieldId], name: e[fieldName], acronym: e[fieldSymbol], price: e[fieldPrice], higth24: e[fieldHigth24], low24: e[fieldLow24], urlImage: e[fieldImage], changePrecent24: e[fieldChangePrecent24], changePrecent7Days: e[fieldChangePrecent7Days])); } return out; } else { log("eroor getAllCrypto code:${response.statusCode.toString()}\n ${response.headers.toString()}"); } } catch (e) { log("error getAllCrypto ${e.toString()}"); } return []; } @override Future<List<Crypto>> updateCrypto() { return getAllCrypto(); } static Future<Crypto?> getCryptoByAcronym(String id) async { try { Uri url = Uri.https("api.coingecko.com", '/api/v3/coins/$id'); final response = await http.get(url); if (response.statusCode == 200) { Map<String, dynamic> jsonElement = await jsonDecode(response.body); Crypto el = Crypto( id: jsonElement["id"], name: jsonElement["name"], acronym: jsonElement["symbol"], price: jsonElement["current_price"]["usd"], higth24: jsonElement["high_24h"]["usd"], low24: jsonElement["low_24h"]["usd"], urlImage: jsonElement["image"]["small"], changePrecent24: jsonElement["price_change_percentage_24h"], changePrecent7Days: jsonElement["price_change_percentage_7d"]); return el; } } catch (e) { log("error getCryptoByAcronym ${e.toString()}"); } return null; } @override Future<num> getCurrentValueCrypto({required String idCrypto}) async { try { Uri url = Uri.https("api.coingecko.com", '/api/v3/coins/$idCrypto', { 'localization': 'false', 'tickers': 'false', 'market_data': 'true', 'community_data': 'false', 'developer_data': 'false', 'sparkline': 'false', }); final response = await http.get(url); if (response.statusCode == 200) { Map<String, dynamic> jsonElement = await jsonDecode(response.body); return jsonElement["market_data"]["current_price"]["usd"]; } } catch (e) { log("error getCryptoByAcronym ${e.toString()}"); } return -1; } }
0
mirrored_repositories/hodler/lib/Data
mirrored_repositories/hodler/lib/Data/model/crypto.dart
import 'package:flutter/widgets.dart'; import 'package:hodler/Data/model/deposit_cypto.dart'; @immutable class Crypto { final String id; final String acronym; final num price; final num? higth24; final num? low24; final String urlImage; final double changePrecent24; final double changePrecent7Days; final String name; final List<DepositCrypto> deposit; final num analiticsInvestiment; final num analiticsReturn; const Crypto({ required this.id, required this.name, required this.acronym, required this.price, required this.higth24, required this.low24, required this.urlImage, required this.changePrecent24, required this.changePrecent7Days, this.deposit = const [], this.analiticsInvestiment = 0, this.analiticsReturn = 0, }); Crypto copyWith( {String? id, String? acronym, num? price, num? higth24, num? low24, String? urlImage, double? changePrecent24, double? changePrecent7Days, String? name, List<DepositCrypto>? deposit, num? analiticsInvestiment, num? analiticsReturn}) => Crypto( id: id ?? this.id, name: name ?? this.name, acronym: acronym ?? this.acronym, price: price ?? this.price, higth24: higth24, low24: low24, urlImage: urlImage ?? this.urlImage, changePrecent24: changePrecent24 ?? this.changePrecent24, changePrecent7Days: changePrecent7Days ?? this.changePrecent7Days, deposit: deposit ?? this.deposit, analiticsInvestiment: analiticsInvestiment ?? this.analiticsInvestiment, analiticsReturn: analiticsReturn ?? this.analiticsReturn); @override String toString() { StringBuffer buffer = StringBuffer() ..writeln("\t info Crypto") ..writeln("id: $id") ..writeln("name: $name") ..writeln("acronym: $acronym") ..writeln("price: ${price.toString()}") ..writeln("H24: ${higth24.toString()}") ..writeln("L24: ${low24.toString()}") ..writeln("url image: $urlImage") ..writeln("change%24: ${changePrecent24.toString()}") ..writeln("change%7d: ${changePrecent7Days.toString()}") ..writeln("deposit: ${deposit.toString()}") ..writeln("analitcs return: ${analiticsReturn.toString()}") ..writeln("analitics invest: ${analiticsInvestiment.toString()} "); return buffer.toString(); } }
0
mirrored_repositories/hodler/lib/Data
mirrored_repositories/hodler/lib/Data/model/deposit_cypto.dart
import '../../Domain/Repository/hodler_repository_db.dart'; class DepositCrypto { final String idDeposit; final String idCrypto; final double importDeposit; final num costCrypto; DepositCrypto( {required this.idDeposit, required this.idCrypto, required this.importDeposit, required this.costCrypto}); DepositCrypto copyWith( {String? idDeposit, String? idCrypto, double? importDeposit, num? costCrypto}) => DepositCrypto( idDeposit: idDeposit ?? this.idDeposit, idCrypto: idCrypto ?? this.idCrypto, importDeposit: importDeposit ?? this.importDeposit, costCrypto: costCrypto ?? this.costCrypto); factory DepositCrypto.fromJson(Map<String, dynamic> json) => DepositCrypto( idDeposit: json[HolderRepositoryDB.fieldId], idCrypto: json[HolderRepositoryDB.fieldIdCrypto], importDeposit: json[HolderRepositoryDB.fieldImport], costCrypto: json[HolderRepositoryDB.fieldValueWhenBuy]); Map<String, dynamic> toJson() => { HolderRepositoryDB.fieldId: idDeposit, HolderRepositoryDB.fieldIdCrypto: idCrypto, HolderRepositoryDB.fieldImport: importDeposit, HolderRepositoryDB.fieldValueWhenBuy: costCrypto, HolderRepositoryDB.fieldDate: DateTime.now().millisecondsSinceEpoch }; @override String toString() { StringBuffer stringBuffer = StringBuffer() ..writeln("\t Deposit crypto") ..writeln("id: $idDeposit") ..writeln("idCrypto: $idCrypto") ..writeln("importDeposit: $importDeposit") ..writeln("costBut: $costCrypto"); return stringBuffer.toString(); } }
0
mirrored_repositories/hodler/lib
mirrored_repositories/hodler/lib/core/utility.dart
import 'package:hodler/Data/model/deposit_cypto.dart'; import 'package:hodler/Domain/Repository/crypto_repository_data.dart'; class Utility { static CryptoRepositoryData? cryptoRepo; /// formula: (Initial Investment — Investment Fee) * ( Sell Price / Buy price) — Initial Investment — Exit Fee /// credits fomula: https://coincodex.com/profit-calculator/ num getGrainDeposit(DepositCrypto deposit, num valueCrypto) { return (deposit.importDeposit) * (valueCrypto / deposit.costCrypto) - deposit.importDeposit; } static Future<num> calulateReturnInvestiment( {required List<DepositCrypto> deposit}) async { num returnInvestiemnt = 0; for (DepositCrypto dp in deposit) { final currentValue = await Utility.cryptoRepo! .getCurrentValueCrypto(idCrypto: dp.idCrypto); returnInvestiemnt += Utility().getGrainDeposit(dp, currentValue); } return returnInvestiemnt; } static Future<num> calculateTotalImport( {required List<DepositCrypto> deposit}) async { num totalIvestiment = 0; for (DepositCrypto dp in deposit) { totalIvestiment += dp.importDeposit; } return totalIvestiment; } }
0
mirrored_repositories/hodler/lib/Application/Presentation
mirrored_repositories/hodler/lib/Application/Presentation/HomePage/home_page.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:hodler/Application/BusinessLogic/bloc/cryptoList/crypto_list_bloc.dart'; import 'package:hodler/Application/Presentation/HomePage/components/crypto_card_view.dart'; import '../../../Data/model/crypto.dart'; class HomePage extends StatefulWidget { const HomePage({super.key}); @override State<HomePage> createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { late TextEditingController _searchController; @override void initState() { _searchController = TextEditingController(); super.initState(); } @override void dispose() { _searchController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Colors.transparent, elevation: 2, titleSpacing: 20, centerTitle: true, title: _searchBar(), ), body: BlocBuilder<CryptoListBloc, CryptoListState>( builder: (context, state) { if (state is CryptoListLoaded) { List<Crypto> listCrypto = state.listCrypto; return GridView.builder( gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent( maxCrossAxisExtent: 300, crossAxisSpacing: 10, mainAxisSpacing: 10), itemBuilder: (context, index) => CriptoCardView(crypto: listCrypto[index]), itemCount: listCrypto.length); } return const Center(child: CircularProgressIndicator()); }), bottomNavigationBar: _getFooter()); } Widget _searchBar() => SearchBar( constraints: BoxConstraints.tight( Size(MediaQuery.of(context).size.width * 0.5, 45)), controller: _searchController, hintText: "search crypto", leading: const Icon(Icons.search), hintStyle: const MaterialStatePropertyAll(TextStyle(fontSize: 15)), onChanged: (value) => _updateList(), ); void _updateList() => BlocProvider.of<CryptoListBloc>(context) .add(CryptoListEventSearch(_searchController.text.trim())); Widget _getFooter() => Column( mainAxisSize: MainAxisSize.min, children: [ BlocBuilder<CryptoListBloc, CryptoListState>( builder: (context, state) { if (state is CryptoListLoaded) { return _getElementFooter( title: "controll Line", analiticsInvestiment: state.totalInvestiment.floorToDouble(), analiticsReturn: state.totalReturn.ceilToDouble()); } return const Center(child: Text("notFound")); }), ], ); Widget _getElementFooter( {required String title, required double analiticsInvestiment, required double analiticsReturn}) => Container( color: Colors.grey.shade300, child: ListTile( dense: true, contentPadding: const EdgeInsets.only(left: 10, right: 10), title: Text( title.toUpperCase(), ), trailing: Row( mainAxisSize: MainAxisSize.min, children: [ _getAnalitics( titleAnalistics: "investiment", importAnalitics: analiticsInvestiment, colorTextImport: Colors.red), const VerticalDivider(width: 20), _getAnalitics( titleAnalistics: "return", importAnalitics: analiticsReturn, colorTextImport: Colors.green) ], )), ); Widget _getAnalitics( {required String titleAnalistics, required num importAnalitics, required Color? colorTextImport}) => Column(mainAxisAlignment: MainAxisAlignment.center, children: [ Text(titleAnalistics.toUpperCase()), Text("${importAnalitics.toStringAsFixed(3)} \$", style: TextStyle(fontSize: 15, color: colorTextImport)), ]); }
0
mirrored_repositories/hodler/lib/Application/Presentation/HomePage
mirrored_repositories/hodler/lib/Application/Presentation/HomePage/components/insert_deposit_ui.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:hodler/Application/BusinessLogic/bloc/cryptoList/crypto_list_bloc.dart'; import 'package:hodler/Data/model/crypto.dart'; import 'package:hodler/Data/model/deposit_cypto.dart'; import 'package:uuid/uuid.dart'; class InsertDepositUI extends StatefulWidget { final Crypto crypto; const InsertDepositUI({super.key, required this.crypto}); @override State<InsertDepositUI> createState() => _InsertDepositUIState(); } class _InsertDepositUIState extends State<InsertDepositUI> { late TextEditingController _importController; late TextEditingController _costCryptoController; late GlobalKey<FormState> _globalKey; @override void initState() { _importController = TextEditingController(); _costCryptoController = TextEditingController(); _globalKey = GlobalKey<FormState>(); super.initState(); } @override void dispose() { _importController.dispose(); _costCryptoController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Dialog( insetPadding: const EdgeInsets.all(20), child: Column(mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Form( key: _globalKey, child: Column(children: [ SizedBox( width: 300, child: ListTile( title: Text("Add Deposit", style: Theme.of(context) .textTheme .titleLarge! .copyWith(fontWeight: FontWeight.bold)), subtitle: Row( children: [ Text(widget.crypto.name), CircleAvatar( radius: 10, child: Image.network(widget.crypto.urlImage), ), ], ), ), ), const SizedBox(height: 50), _getInputImportField(), _getInputImportCostField() ])), ElevatedButton( onPressed: () => _addDeposit(), child: const Text("add deposit")), const SizedBox(height: 100), _getDepositSection() ]), ); } Widget _getDepositSection() => Expanded( child: SizedBox( width: 300, child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ Text("List Deposit", style: Theme.of(context).textTheme.titleLarge), const Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Text("import deposit"), SizedBox(width: 20), Text("cost crypto") ], ), Expanded( child: widget.crypto.deposit.isNotEmpty ? _getDepositListView(deposit: widget.crypto.deposit) : const Center( child: Text("not deposit"), )) ], )), ); void _addDeposit() { if (_globalKey.currentState!.validate()) { DepositCrypto deposit = DepositCrypto( idDeposit: const Uuid().v4(), idCrypto: widget.crypto.id, importDeposit: double.parse(_importController.text), costCrypto: double.parse(_costCryptoController.text)); BlocProvider.of<CryptoListBloc>(context) .add(CryptoListEventAddDeposit(deposit: deposit)); _costCryptoController.clear(); _importController.clear(); } } String? _validator(value) { if (value == null || value.isEmpty) return "insert import"; if (double.tryParse(value) == null || double.parse(value) <= 0) { return "import not vaid"; } return null; } void _deleteDeposit({required DepositCrypto deposit}) => BlocProvider.of<CryptoListBloc>(context) .add(CryptoListEventRemoveDeposit(deposit: deposit)); Widget _getDepositListView({required List<DepositCrypto> deposit}) => ListView.separated( itemBuilder: (context, index) { DepositCrypto dp = deposit[index]; return Dismissible( key: Key(dp.idDeposit), onDismissed: (direction) => _deleteDeposit(deposit: deposit[index]), background: Container( color: Colors.red, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [_getIconTrash(), _getIconTrash()])), child: ListTile( title: Text("${dp.importDeposit.toStringAsFixed(2)}\$"), trailing: Text("${dp.costCrypto.toStringAsFixed(4)}\$")), ); }, itemCount: deposit.length, separatorBuilder: (_, __) => const Divider(), ); Icon _getIconTrash() => const Icon(FontAwesomeIcons.solidTrashCan, color: Colors.white); _getInputImportField() => IntrinsicWidth( child: TextFormField( keyboardType: TextInputType.number, controller: _importController, validator: (value) => _validator(value), style: const TextStyle(fontSize: 30), decoration: const InputDecoration( border: InputBorder.none, prefixIcon: Icon(FontAwesomeIcons.dollarSign), hintText: "Investiment"), ), ); _getInputImportCostField() => IntrinsicWidth( child: TextFormField( controller: _costCryptoController, keyboardType: TextInputType.number, validator: (value) => _validator(value), style: const TextStyle(fontSize: 30), decoration: const InputDecoration( border: InputBorder.none, prefixIcon: Icon(FontAwesomeIcons.dollarSign), hintText: "cost cyrpto"), ), ); }
0
mirrored_repositories/hodler/lib/Application/Presentation/HomePage
mirrored_repositories/hodler/lib/Application/Presentation/HomePage/components/crypto_card_view.dart
import 'dart:developer'; import 'package:auto_size_text/auto_size_text.dart'; import 'package:flutter/material.dart'; import 'package:hodler/Data/model/crypto.dart'; import 'insert_deposit_ui.dart'; class CriptoCardView extends StatefulWidget { final Crypto crypto; const CriptoCardView({super.key, required this.crypto}); @override State<CriptoCardView> createState() => _CriptoCardViewState(); } class _CriptoCardViewState extends State<CriptoCardView> { @override Widget build(BuildContext context) { return InkWell( onTap: () => _addDepositCrypto(), borderRadius: BorderRadius.circular(20), child: Card( child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: CrossAxisAlignment.center, children: [ _getTitleCard(), _getPriceCard(), _getAnalitics(), widget.crypto.deposit.isNotEmpty ? _getDepositAnalitics() : Container() ]))); } Widget _getAnalitics() => IntrinsicHeight( child: Row( mainAxisAlignment: MainAxisAlignment.center, mainAxisSize: MainAxisSize.min, children: [ Column(children: [ _getLabelAnaliticsValuePercent( value: widget.crypto.changePrecent24), _getLabelAnaliticsValue(text: "today"), ]), _getVerticalDivider(), Column(children: [ _getLabelAnaliticsValuePercent( value: widget.crypto.changePrecent7Days), _getLabelAnaliticsValue(text: "week") ]), ]), ); _addDepositCrypto() => showDialog<String>( context: context, builder: (BuildContext context) => InsertDepositUI( crypto: widget.crypto, )); Widget _getTitleCard() => Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ CircleAvatar( backgroundColor: Colors.transparent, child: Image.network( widget.crypto.urlImage, errorBuilder: (context, error, stackTrace) { log("CryptoCardView error load image ", error: error); return const Placeholder(); }, ), ), Column( children: [ AutoSizeText("${widget.crypto.name} "), AutoSizeText( widget.crypto.acronym.toUpperCase(), style: TextStyle(color: Theme.of(context).dividerColor), ) ], ) ], ); Widget _getPriceCard() => ListTile( title: AutoSizeText( "\$ ${widget.crypto.price.toString()}", style: const TextStyle(fontSize: 25), textAlign: TextAlign.center, ), ); Widget _getLabelAnaliticsValuePercent({required double value}) => Text( "${value.toStringAsPrecision(2)}%", style: TextStyle(color: value > 0 ? Colors.green : Colors.red), ); Widget _getLabelAnaliticsValue({required String text}) => Text( "Today".toUpperCase(), style: TextStyle( fontSize: 12, fontWeight: FontWeight.bold, color: Theme.of(context).hintColor), ); Widget _getVerticalDivider() => const VerticalDivider( thickness: 1, width: 20, ); Widget _getDepositAnalitics() => IntrinsicHeight( child: Column( children: [ const Divider(), Row( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.center, children: [ Text( "${widget.crypto.analiticsInvestiment.toStringAsFixed(2)}\$"), _getVerticalDivider(), Text("${widget.crypto.analiticsReturn.toStringAsFixed(2)} \$", style: TextStyle( color: widget.crypto.analiticsReturn > 0 ? Colors.green : Colors.red)) ], ), ], ), ); }
0
mirrored_repositories/hodler/lib/Application/BusinessLogic/bloc
mirrored_repositories/hodler/lib/Application/BusinessLogic/bloc/cryptoList/crypto_list_event.dart
part of 'crypto_list_bloc.dart'; @immutable abstract class CryptoListEvent {} class CryptoListEventInit extends CryptoListEvent {} class CryptoListEventRefresh extends CryptoListEvent {} class CryptoListEventSearch extends CryptoListEvent { final String text; CryptoListEventSearch(this.text); } class CryptoListEventAddDeposit extends CryptoListEvent { final DepositCrypto deposit; CryptoListEventAddDeposit({required this.deposit}); } class CryptoListEventRemoveDeposit extends CryptoListEvent { final DepositCrypto deposit; CryptoListEventRemoveDeposit({required this.deposit}); }
0
mirrored_repositories/hodler/lib/Application/BusinessLogic/bloc
mirrored_repositories/hodler/lib/Application/BusinessLogic/bloc/cryptoList/crypto_list_bloc.dart
import 'dart:async'; import 'package:bloc/bloc.dart'; import 'package:flutter/material.dart'; import 'package:hodler/Data/model/crypto.dart'; import 'package:hodler/Data/model/deposit_cypto.dart'; import 'package:hodler/Domain/Repository/crypto_repository_data.dart'; import 'package:hodler/Domain/Repository/hodler_repository_db.dart'; import 'package:hodler/core/utility.dart'; part 'crypto_list_event.dart'; part 'crypto_list_state.dart'; class CryptoListBloc extends Bloc<CryptoListEvent, CryptoListState> { List<Crypto> allList = []; final CryptoRepositoryData storage; final HolderRepositoryDB db; CryptoListBloc(this.storage, this.db) : super(CryptoListInitial()) { on<CryptoListEventInit>(_initAction); on<CryptoListEventRefresh>((event, emit) => emit(CryptoListInitial())); on<CryptoListEventSearch>(_searchAction); on<CryptoListEventAddDeposit>(_addDepositAction); on<CryptoListEventRemoveDeposit>(_removeDepositAction); } FutureOr<void> _initAction( CryptoListEventInit event, Emitter<CryptoListState> emit) async { await db.initDb(); Utility.cryptoRepo = storage; allList = await storage.getAllCrypto(); final List<DepositCrypto> listAllDeposit = await db.getAllDepositCrypto(); final List<String> listIdCryptoDeposit = listAllDeposit.map((e) => e.idCrypto).toSet().toList(); for (String i in listIdCryptoDeposit) { int indexCrypto = allList.indexWhere((element) => element.id == i); Crypto el = allList.elementAt(indexCrypto); List<DepositCrypto> listDeposit = listAllDeposit.where((element) => element.idCrypto == i).toList(); num returnInvestiemnt = await Utility.calulateReturnInvestiment(deposit: listDeposit); num importInvestiment = await Utility.calculateTotalImport(deposit: listDeposit); allList.replaceRange(indexCrypto, indexCrypto + 1, [ el.copyWith( deposit: listDeposit, analiticsInvestiment: importInvestiment, analiticsReturn: returnInvestiemnt) ]); } _emitCryptoListLoaded(emit, null); } FutureOr<void> _searchAction( CryptoListEventSearch event, Emitter<CryptoListState> emit) { final List<Crypto> filterList = allList .where((element) => element.name.toUpperCase().contains(event.text.toUpperCase()) || element.acronym.toUpperCase().contains(event.text.toUpperCase())) .toList(); _emitCryptoListLoaded(emit, filterList); } FutureOr<void> _addDepositAction( CryptoListEventAddDeposit event, Emitter<CryptoListState> emit) async { int indexCrypto = allList.indexWhere((element) => element.id == event.deposit.idCrypto); db.addDeposit(event.deposit); Crypto crypto = allList.elementAt(indexCrypto); List<DepositCrypto> work = crypto.deposit; work.add(event.deposit); Crypto nCrypto = crypto.copyWith( deposit: work, analiticsInvestiment: await Utility.calculateTotalImport(deposit: work), analiticsReturn: await Utility.calulateReturnInvestiment(deposit: work)); allList.replaceRange(indexCrypto, indexCrypto + 1, [nCrypto]); _emitCryptoListLoaded(emit, null); } FutureOr<void> _removeDepositAction( CryptoListEventRemoveDeposit event, Emitter<CryptoListState> emit) async { int indexCrypto = allList.indexWhere((element) => element.id == event.deposit.idCrypto); db.removeDeposit(event.deposit.idDeposit); Crypto crypto = allList.elementAt(indexCrypto); List<DepositCrypto> work = crypto.deposit; work.remove(event.deposit); Crypto nCrypto = crypto.copyWith( deposit: work, analiticsInvestiment: await Utility.calculateTotalImport(deposit: work), analiticsReturn: await Utility.calulateReturnInvestiment(deposit: work)); allList.replaceRange(indexCrypto, indexCrypto + 1, [nCrypto]); _emitCryptoListLoaded(emit, null); } void _emitCryptoListLoaded( Emitter<CryptoListState> emit, List<Crypto>? list) { num totalImport = (list ?? allList).fold( 0.0, ((previousValue, element) => previousValue + element.analiticsInvestiment)); num totalReturn = allList.fold(0.0, ((previousValue, element) => previousValue + element.analiticsReturn)); emit(CryptoListLoaded( listCrypto: (list ?? allList), totalReturn: totalReturn, totalInvestiment: totalImport)); } }
0
mirrored_repositories/hodler/lib/Application/BusinessLogic/bloc
mirrored_repositories/hodler/lib/Application/BusinessLogic/bloc/cryptoList/crypto_list_state.dart
part of 'crypto_list_bloc.dart'; @immutable abstract class CryptoListState {} class CryptoListInitial extends CryptoListState {} class CryptoListLoaded extends CryptoListState { final List<Crypto> listCrypto; final num totalInvestiment; final num totalReturn; CryptoListLoaded( {required this.listCrypto, required this.totalInvestiment, required this.totalReturn}); }
0