games_app/prediqo_mobile/test/admin_section_load_test.dart
2026-10-25 20:49:23 +02:00

591 lines
17 KiB
Dart

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/network/api_client.dart';
import 'package:prediqo_mobile/core/theme/app_theme.dart';
import 'package:prediqo_mobile/data/repositories/admin_repository_impl.dart';
import 'package:prediqo_mobile/data/repositories/auth_repository_impl.dart';
import 'package:prediqo_mobile/domain/repositories/health_repository.dart';
import 'package:prediqo_mobile/domain/repositories/repositories.dart';
import 'package:prediqo_mobile/features/admin/presentation/network_screen.dart';
import 'package:prediqo_mobile/features/admin/presentation/options_screen.dart';
import 'package:prediqo_mobile/features/admin/presentation/settings_screen.dart';
import 'package:prediqo_mobile/features/admin/presentation/user_detail_screen.dart';
import 'package:prediqo_mobile/features/admin/presentation/user_management_screen.dart';
import 'package:prediqo_mobile/features/auth/bloc/auth_bloc.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:prediqo_mobile/shared/widgets/tloto_gradient_app_bar.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'support/e2e_fixtures.dart';
const _sampleUser = AdminUserListItem(
id: 'u1',
email: 'ada@prediqo.test',
roleId: 1,
roleName: 'user',
emailVerified: true,
totpEnabled: false,
isEnabled: true,
isAccountNonExpired: true,
isAccountNonLocked: true,
isCredentialsNonExpired: true,
createdAt: '2024-01-01T00:00:00Z',
);
const _sampleSettings = SystemSettings(
passwordMinLength: 8,
passwordRequireUppercase: true,
passwordRequireLowercase: true,
passwordRequireNumber: true,
passwordRequireSpecial: false,
accessTokenExpiry: '15m',
refreshTokenExpiry: '7d',
);
class _ControllableAdmin extends AdminRepositoryImpl {
_ControllableAdmin(super.api);
Completer<AdminUserListResult>? listHold;
Completer<AdminUserDetails?>? detailHold;
Completer<SystemSettings>? settingsHold;
Object? failWith;
var listCalls = 0;
var detailCalls = 0;
var settingsCalls = 0;
@override
Future<AdminUserListResult> listUsers({
String? search,
int limit = 50,
int offset = 0,
bool force = false,
}) async {
listCalls++;
if (failWith != null) throw failWith!;
if (listHold != null) return listHold!.future;
return const AdminUserListResult(users: [_sampleUser], total: 1);
}
@override
Future<AdminUserDetails?> getUserDetails(
String userId, {
bool force = false,
}) async {
detailCalls++;
if (failWith != null) throw failWith!;
if (detailHold != null) return detailHold!.future;
return AdminUserDetails(
user: AdminUserDetailUser(
id: userId,
email: 'ada@prediqo.test',
roleName: 'user',
emailVerified: true,
totpEnabled: false,
isEnabled: true,
isAccountNonExpired: true,
isAccountNonLocked: true,
isCredentialsNonExpired: true,
createdAt: '2024-01-01T00:00:00Z',
),
balances: const [],
);
}
@override
Future<SystemSettings> getSettings({bool force = false}) async {
settingsCalls++;
if (failWith != null) throw failWith!;
if (settingsHold != null) return settingsHold!.future;
return _sampleSettings;
}
@override
Future<SystemSettings> updateSettings(SystemSettings settings) async => settings;
@override
Future<void> updateUserFlags(
String userId, {
bool? isEnabled,
bool? isAccountNonExpired,
bool? isAccountNonLocked,
bool? isCredentialsNonExpired,
}) async {}
}
class _ControllableHealth implements HealthRepository {
Completer<HealthStatus>? hold;
Object? failWith;
var calls = 0;
HealthStatus? cached;
@override
Future<HealthStatus> getHealth({bool force = false}) async {
calls++;
if (failWith != null) throw failWith!;
if (hold != null) return hold!.future;
return cached ??
const HealthStatus(
network: 'shasta',
withdrawalsEnabled: false,
env: 'test',
);
}
@override
HealthStatus? peekLast() => cached;
@override
void invalidate() => cached = null;
}
class _StubAuth implements AuthRepository {
@override
Future<bool> isLoggedIn() async => true;
@override
Future<({String? userId, String? role})> getStoredUser() async =>
(userId: 'admin1', role: 'admin');
@override
Future<LoginResult> login(
String email,
String password, {
String? totpCode,
String? captchaToken,
}) async =>
throw UnimplementedError();
@override
Future<RegisterResult> register(RegisterRequest request) async =>
throw UnimplementedError();
@override
Future<({bool valid, String? reason})> validateReferralCode(String code) async =>
(valid: true, reason: null);
@override
Future<void> resendVerificationEmail(String email) async {}
@override
Future<void> logout() async {}
@override
Future<Map<String, dynamic>> setup2FA({String? password, String? totpCode}) async =>
{};
@override
Future<List<String>> enable2FA(String code) async => const [];
@override
Future<void> disable2FA({required String password, required String code}) async {}
@override
Future<List<String>> regenerateRecoveryCodes(String totpCode) async => const [];
@override
Future<UserProfile> getProfile({bool force = false}) async =>
throw UnimplementedError();
@override
UserProfile? peekLastProfile() => null;
@override
void invalidateProfile() {}
@override
Future<List<CountryOption>> getCountries({bool force = false}) async => const [];
@override
List<CountryOption>? peekLastCountries() => null;
@override
void invalidateCountries() {}
@override
Future<void> 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<void> changePassword({
required String currentPassword,
required String newPassword,
}) async {}
@override
Future<void> forgotPassword(String email) async {}
}
Future<void> _bootLocale() async {
configureE2eTestEnvironment();
if (sl.isRegistered<AppConfig>()) await sl.reset();
sl.registerSingleton<AppConfig>(
const AppConfig(apiBaseUrl: 'http://localhost', isProduction: false, wsEnabled: false),
);
final locale = LocaleController();
SharedPreferences.setMockInitialValues({'app_locale': 'en'});
await locale.load();
sl.registerSingleton<LocaleController>(locale);
}
void _tallSurface(WidgetTester tester) {
tester.view.physicalSize = const Size(400, 2400);
tester.view.devicePixelRatio = 1.0;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
}
void main() {
tearDown(() async {
if (sl.isRegistered<AppConfig>()) await sl.reset();
});
testWidgets('User management shows skeletons then list (chrome kept)', (tester) async {
_tallSurface(tester);
await _bootLocale();
final api = ApiClient(config: sl());
final hold = Completer<AdminUserListResult>();
final admin = _ControllableAdmin(api)..listHold = hold;
await tester.pumpWidget(
MaterialApp(
theme: AppTheme.dark,
home: UserManagementScreen(adminRepo: admin),
),
);
await tester.pump();
expect(find.byKey(const Key('admin_users_screen')), findsOneWidget);
expect(find.byType(TlotoGradientAppBar), findsOneWidget);
expect(find.text('User Management'), findsOneWidget);
expect(find.byKey(const Key('admin_users_search')), findsOneWidget);
expect(find.text('Search'), findsNothing);
expect(find.byType(PredSkeletonCard), findsWidgets);
expect(find.byType(CircularProgressIndicator), findsNothing);
hold.complete(const AdminUserListResult(users: [_sampleUser], total: 1));
await tester.pump();
await tester.pump(const Duration(milliseconds: 50));
expect(find.text('ada@prediqo.test'), findsOneWidget);
expect(find.byType(PredSkeletonCard), findsNothing);
await tester.pumpWidget(const SizedBox.shrink());
await tester.pump();
});
testWidgets('User management SectionError + retry (no blank)', (tester) async {
_tallSurface(tester);
await _bootLocale();
final api = ApiClient(config: sl());
final admin = _ControllableAdmin(api)..failWith = Exception('offline');
await tester.pumpWidget(
MaterialApp(
theme: AppTheme.dark,
home: UserManagementScreen(adminRepo: admin),
),
);
await tester.pump();
await tester.pump(const Duration(milliseconds: 50));
expect(find.byType(SectionError), findsOneWidget);
expect(find.byType(TlotoGradientAppBar), findsOneWidget);
expect(find.text('User Management'), findsOneWidget);
admin.failWith = null;
await tester.tap(find.byKey(const Key('section_error_retry')));
await tester.pump();
await tester.pump(const Duration(milliseconds: 50));
expect(find.text('ada@prediqo.test'), findsOneWidget);
expect(admin.listCalls, greaterThanOrEqualTo(2));
await tester.pumpWidget(const SizedBox.shrink());
await tester.pump();
});
testWidgets('User detail skeletons then content', (tester) async {
_tallSurface(tester);
await _bootLocale();
final api = ApiClient(config: sl());
final hold = Completer<AdminUserDetails?>();
final admin = _ControllableAdmin(api)..detailHold = hold;
await tester.pumpWidget(
MaterialApp(
theme: AppTheme.dark,
home: UserDetailScreen(userId: 'u1', adminRepo: admin),
),
);
await tester.pump();
expect(find.byKey(const Key('admin_user_detail_screen')), findsOneWidget);
expect(find.byType(TlotoGradientAppBar), findsOneWidget);
expect(find.byType(PredSkeletonCard), findsWidgets);
hold.complete(
AdminUserDetails(
user: AdminUserDetailUser(
id: 'u1',
email: 'ada@prediqo.test',
roleName: 'user',
emailVerified: true,
totpEnabled: false,
isEnabled: true,
isAccountNonExpired: true,
isAccountNonLocked: true,
isCredentialsNonExpired: true,
createdAt: '2024-01-01T00:00:00Z',
),
balances: const [],
),
);
await tester.pump();
await tester.pump(const Duration(milliseconds: 50));
expect(find.text('ada@prediqo.test'), findsWidgets);
await tester.pumpWidget(const SizedBox.shrink());
await tester.pump();
});
testWidgets('Options shows admin tiles for admin', (tester) async {
_tallSurface(tester);
await _bootLocale();
final auth = AuthBloc(_StubAuth());
final ready = auth.stream.firstWhere((s) => s.isAdmin);
auth.add(const AuthCheckRequested());
await ready;
await tester.pumpWidget(
BlocProvider.value(
value: auth,
child: MaterialApp(
theme: AppTheme.dark,
home: const OptionsScreen(),
),
),
);
await tester.pump();
expect(find.byKey(const Key('options_screen')), findsOneWidget);
expect(find.byType(TlotoGradientAppBar), findsOneWidget);
expect(find.text('Network status'), findsOneWidget);
expect(find.text('Users'), findsOneWidget);
expect(find.text('Settings'), findsWidgets);
await tester.pumpWidget(const SizedBox.shrink());
await tester.pump();
addTearDown(auth.close);
});
testWidgets('Settings skeletons then form for admin', (tester) async {
_tallSurface(tester);
await _bootLocale();
final api = ApiClient(config: sl());
final hold = Completer<SystemSettings>();
final admin = _ControllableAdmin(api)..settingsHold = hold;
final auth = AuthBloc(_StubAuth());
final ready = auth.stream.firstWhere((s) => s.isAdmin);
auth.add(const AuthCheckRequested());
await ready;
await tester.pumpWidget(
BlocProvider.value(
value: auth,
child: MaterialApp(
theme: AppTheme.dark,
home: SettingsScreen(adminRepo: admin),
),
),
);
await tester.pump();
expect(find.byKey(const Key('admin_settings_screen')), findsOneWidget);
expect(find.byType(TlotoGradientAppBar), findsOneWidget);
expect(find.byType(PredSkeletonCard), findsWidgets);
hold.complete(_sampleSettings);
await tester.pump();
await tester.pump(const Duration(milliseconds: 50));
expect(find.text('Password policy'), findsOneWidget);
await tester.pumpWidget(const SizedBox.shrink());
await tester.pump();
addTearDown(auth.close);
});
testWidgets('Network skeletons then health card', (tester) async {
_tallSurface(tester);
await _bootLocale();
final hold = Completer<HealthStatus>();
final health = _ControllableHealth()..hold = hold;
await tester.pumpWidget(
RepositoryProvider<HealthRepository>.value(
value: health,
child: MaterialApp(
theme: AppTheme.dark,
home: const NetworkScreen(),
),
),
);
await tester.pump();
expect(find.byKey(const Key('admin_network_screen')), findsOneWidget);
expect(find.byType(PredSkeletonCard), findsWidgets);
hold.complete(
const HealthStatus(network: 'shasta', withdrawalsEnabled: false, env: 'test'),
);
await tester.pump();
await tester.pump(const Duration(milliseconds: 50));
expect(find.textContaining('SHASTA'), findsOneWidget);
await tester.pumpWidget(const SizedBox.shrink());
await tester.pump();
});
testWidgets('Network SectionError + retry', (tester) async {
_tallSurface(tester);
await _bootLocale();
final health = _ControllableHealth()..failWith = Exception('down');
await tester.pumpWidget(
RepositoryProvider<HealthRepository>.value(
value: health,
child: MaterialApp(
theme: AppTheme.dark,
home: const NetworkScreen(),
),
),
);
await tester.pump();
await tester.pump(const Duration(milliseconds: 50));
expect(find.byType(SectionError), findsOneWidget);
health.failWith = null;
await tester.tap(find.byKey(const Key('section_error_retry')));
await tester.pump();
await tester.pump(const Duration(milliseconds: 50));
expect(find.textContaining('SHASTA'), findsOneWidget);
expect(health.calls, greaterThanOrEqualTo(2));
await tester.pumpWidget(const SizedBox.shrink());
await tester.pump();
});
testWidgets('Settings hydrates from cache without skeleton', (tester) async {
_tallSurface(tester);
await _bootLocale();
final api = ApiClient(config: sl());
final hold = Completer<SystemSettings>();
final admin = _ControllableAdmin(api)..settingsHold = hold;
admin.settingsStore.put(_sampleSettings);
final auth = AuthBloc(_StubAuth());
final ready = auth.stream.firstWhere((s) => s.isAdmin);
auth.add(const AuthCheckRequested());
await ready;
await tester.pumpWidget(
BlocProvider.value(
value: auth,
child: MaterialApp(
theme: AppTheme.dark,
home: SettingsScreen(adminRepo: admin),
),
),
);
await tester.pump();
expect(find.byType(PredSkeletonCard), findsNothing);
expect(find.text('Password policy'), findsOneWidget);
hold.complete(_sampleSettings);
await tester.pump();
await tester.pumpWidget(const SizedBox.shrink());
await tester.pump();
addTearDown(auth.close);
});
testWidgets('Users hydrates from cache without skeleton', (tester) async {
_tallSurface(tester);
await _bootLocale();
final api = ApiClient(config: sl());
final hold = Completer<AdminUserListResult>();
final admin = _ControllableAdmin(api)..listHold = hold;
await admin.usersStore.get(
AdminUsersListStore.keyFor(limit: 25, offset: 0),
() async => const AdminUserListResult(users: [_sampleUser], total: 1),
);
await tester.pumpWidget(
MaterialApp(
theme: AppTheme.dark,
home: UserManagementScreen(adminRepo: admin),
),
);
await tester.pump();
expect(find.byType(PredSkeletonCard), findsNothing);
expect(find.text('ada@prediqo.test'), findsOneWidget);
hold.complete(const AdminUserListResult(users: [_sampleUser], total: 1));
await tester.pump();
await tester.pumpWidget(const SizedBox.shrink());
await tester.pump();
});
testWidgets('Network hydrates from cache without skeleton', (tester) async {
_tallSurface(tester);
await _bootLocale();
final hold = Completer<HealthStatus>();
final health = _ControllableHealth()
..hold = hold
..cached = const HealthStatus(
network: 'shasta',
withdrawalsEnabled: false,
env: 'test',
);
await tester.pumpWidget(
RepositoryProvider<HealthRepository>.value(
value: health,
child: MaterialApp(
theme: AppTheme.dark,
home: const NetworkScreen(),
),
),
);
await tester.pump();
expect(find.byType(PredSkeletonCard), findsNothing);
expect(find.textContaining('SHASTA'), findsOneWidget);
hold.complete(health.cached!);
await tester.pump();
await tester.pumpWidget(const SizedBox.shrink());
await tester.pump();
});
}