import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:prediqo_mobile/core/config/app_config.dart'; import 'package:prediqo_mobile/core/di/injection.dart'; import 'package:prediqo_mobile/core/theme/app_theme.dart'; import 'package:prediqo_mobile/data/repositories/auth_repository_impl.dart'; import 'package:prediqo_mobile/domain/repositories/repositories.dart'; import 'package:prediqo_mobile/features/wallet/presentation/profile_edit_screen.dart'; import 'package:prediqo_mobile/l10n/locale_controller.dart'; import 'package:prediqo_mobile/shared/widgets/pred_skeleton.dart'; import 'package:prediqo_mobile/shared/widgets/section_error.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'support/e2e_fixtures.dart'; class _ControllableAuth implements AuthRepository { Completer? profileHold; Completer>? countriesHold; UserProfile? cachedProfile; List? cachedCountries; var getProfileCalls = 0; var getCountriesCalls = 0; Object? profileFail; Object? countriesFail; _ControllableAuth({this.cachedProfile, this.cachedCountries}); @override UserProfile? peekLastProfile() => cachedProfile; @override void invalidateProfile() => cachedProfile = null; @override Future getProfile({bool force = false}) async { getProfileCalls++; if (profileFail != null) throw profileFail!; if (profileHold != null) return profileHold!.future; return cachedProfile ?? const UserProfile( firstName: 'Ada', lastName: 'Lovelace', email: 'ada@prediqo.test', countryOfResidence: 'FR', gender: 'female', ); } @override List? peekLastCountries() => cachedCountries; @override void invalidateCountries() => cachedCountries = null; @override Future> getCountries({bool force = false}) async { getCountriesCalls++; if (countriesFail != null) throw countriesFail!; if (countriesHold != null) return countriesHold!.future; return cachedCountries ?? const [ CountryOption(code: 'FR', name: 'France'), CountryOption(code: 'US', name: 'United States'), ]; } @override Future login( String email, String password, { String? totpCode, String? captchaToken, }) async => throw UnimplementedError(); @override Future register(RegisterRequest request) async => throw UnimplementedError(); @override Future<({bool valid, String? reason})> validateReferralCode(String code) async => (valid: true, reason: null); @override Future resendVerificationEmail(String email) async {} @override Future logout() async {} @override Future isLoggedIn() async => true; @override Future<({String? userId, String? role})> getStoredUser() async => (userId: 'u1', role: 'user'); @override Future> setup2FA({String? password, String? totpCode}) async => {}; @override Future> enable2FA(String code) async => const []; @override Future disable2FA({required String password, required String code}) async {} @override Future> regenerateRecoveryCodes(String totpCode) async => const []; @override Future updateProfile({ String? firstName, String? middleName, String? lastName, String? dateOfBirth, required String email, String? phone, required String countryOfResidence, String? nationality, required String gender, }) async {} @override Future changePassword({ required String currentPassword, required String newPassword, }) async {} @override Future forgotPassword(String email) async {} } Future _boot(AuthRepository auth) async { configureE2eTestEnvironment(); if (sl.isRegistered()) await sl.reset(); sl.registerSingleton( const AppConfig(apiBaseUrl: 'http://localhost', isProduction: false, wsEnabled: false), ); final locale = LocaleController(); SharedPreferences.setMockInitialValues({'app_locale': 'en'}); await locale.load(); sl.registerSingleton(locale); sl.registerLazySingleton(() => auth); } void _tallSurface(WidgetTester tester) { tester.view.physicalSize = const Size(400, 2400); tester.view.devicePixelRatio = 1.0; addTearDown(tester.view.resetPhysicalSize); addTearDown(tester.view.resetDevicePixelRatio); } Widget _wrap(AuthRepository auth) { return RepositoryProvider.value( value: auth, child: MaterialApp( theme: AppTheme.dark, home: const ProfileEditScreen(), ), ); } void main() { tearDown(() async { if (sl.isRegistered()) await sl.reset(); }); testWidgets('Profile paints fields from cache while countries still loading', (tester) async { _tallSurface(tester); final countriesHold = Completer>(); final auth = _ControllableAuth( cachedProfile: const UserProfile( firstName: 'Ada', lastName: 'Lovelace', email: 'ada@prediqo.test', countryOfResidence: 'FR', gender: 'female', ), )..countriesHold = countriesHold; await _boot(auth); await tester.pumpWidget(_wrap(auth)); await tester.pump(); await tester.pump(const Duration(milliseconds: 50)); expect(find.text('Ada'), findsOneWidget); expect(find.text('ada@prediqo.test'), findsOneWidget); expect(find.byType(PredSkeletonCard), findsWidgets); countriesHold.complete(const [ CountryOption(code: 'FR', name: 'France'), ]); await tester.pumpAndSettle(); expect(find.textContaining('France'), findsWidgets); }); testWidgets('Profile shows countries SectionError without blanking form', (tester) async { _tallSurface(tester); final auth = _ControllableAuth( cachedProfile: const UserProfile( firstName: 'Ada', lastName: 'Lovelace', email: 'ada@prediqo.test', countryOfResidence: 'FR', gender: 'female', ), )..countriesFail = Exception('countries down'); await _boot(auth); await tester.pumpWidget(_wrap(auth)); await tester.pumpAndSettle(); expect(find.byType(SectionError), findsOneWidget); expect(find.text('Ada'), findsOneWidget); expect(find.text('Save profile'), findsOneWidget); }); testWidgets('Profile shows SectionError when profile fails with empty cache', (tester) async { _tallSurface(tester); final auth = _ControllableAuth()..profileFail = Exception('profile down'); // Countries succeed so only profile error shows. await _boot(auth); await tester.pumpWidget(_wrap(auth)); await tester.pumpAndSettle(); expect(find.byType(SectionError), findsWidgets); expect(find.text('Save profile'), findsNothing); }); testWidgets('Profile retry does not launch parallel duplicate profile fetches', (tester) async { _tallSurface(tester); final auth = _ControllableAuth() ..profileFail = Exception('profile down') ..countriesFail = Exception('countries down'); await _boot(auth); await tester.pumpWidget(_wrap(auth)); await tester.pump(); await tester.pump(const Duration(milliseconds: 50)); expect(find.byType(SectionError), findsWidgets); final before = auth.getProfileCalls; auth.profileFail = null; auth.profileHold = Completer(); final retry = find.byKey(const Key('section_error_retry')); expect(retry, findsWidgets); await tester.ensureVisible(retry.first); await tester.tap(retry.first); await tester.pump(); if (retry.evaluate().isNotEmpty) { await tester.tap(retry.first); await tester.pump(); } expect(auth.getProfileCalls, before + 1); auth.profileHold!.complete(const UserProfile( firstName: 'Ada', lastName: 'Lovelace', email: 'ada@prediqo.test', countryOfResidence: 'FR', gender: 'female', )); await tester.pumpAndSettle(); expect(find.text('Ada'), findsOneWidget); }); }