485 lines
16 KiB
Dart
485 lines
16 KiB
Dart
import 'package:dio/dio.dart';
|
|
import 'package:flutter_test/flutter_test.dart';
|
|
import 'package:google_fonts/google_fonts.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/realtime/game_socket_service.dart';
|
|
import 'package:prediqo_mobile/data/models/advertisement_models.dart';
|
|
import 'package:prediqo_mobile/data/models/faq_models.dart';
|
|
import 'package:prediqo_mobile/data/models/game_catalog_models.dart';
|
|
import 'package:prediqo_mobile/data/models/notification_models.dart';
|
|
import 'package:prediqo_mobile/data/models/prediction_models.dart';
|
|
import 'package:prediqo_mobile/data/models/referral_models.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/data/repositories/wallet_repository_impl.dart';
|
|
import 'package:prediqo_mobile/domain/repositories/advertisement_repository.dart';
|
|
import 'package:prediqo_mobile/domain/repositories/faq_repository.dart';
|
|
import 'package:prediqo_mobile/domain/repositories/game_catalog_repository.dart';
|
|
import 'package:prediqo_mobile/domain/repositories/health_repository.dart';
|
|
import 'package:prediqo_mobile/domain/repositories/notification_repository.dart';
|
|
import 'package:prediqo_mobile/domain/repositories/prediction_repository.dart';
|
|
import 'package:prediqo_mobile/domain/repositories/referral_repository.dart';
|
|
import 'package:prediqo_mobile/domain/repositories/repositories.dart';
|
|
import 'package:prediqo_mobile/features/auth/bloc/auth_bloc.dart';
|
|
import 'package:prediqo_mobile/features/prediction/bloc/prediction_bloc.dart';
|
|
import 'package:prediqo_mobile/features/wallet/bloc/wallet_bloc.dart';
|
|
import 'package:prediqo_mobile/l10n/locale_controller.dart';
|
|
import 'package:shared_preferences/shared_preferences.dart';
|
|
|
|
/// Disables network font fetching so widget tests settle reliably.
|
|
void configureE2eTestEnvironment() {
|
|
TestWidgetsFlutterBinding.ensureInitialized();
|
|
SharedPreferences.setMockInitialValues({'app_locale': 'en'});
|
|
GoogleFonts.config.allowRuntimeFetching = false;
|
|
}
|
|
|
|
/// Pumps frames without waiting for endless animations/timers.
|
|
Future<void> e2ePump(WidgetTester tester, {int frames = 3}) async {
|
|
for (var i = 0; i < frames; i++) {
|
|
await tester.pump(const Duration(milliseconds: 100));
|
|
}
|
|
}
|
|
|
|
/// Advances past the branded splash min delay (~1.2s) plus a few frames.
|
|
Future<void> e2ePumpPastSplash(WidgetTester tester) async {
|
|
await tester.pump(const Duration(milliseconds: 1300));
|
|
await e2ePump(tester, frames: 5);
|
|
}
|
|
|
|
/// Mock HTTP responses for wallet screens when [WalletRepositoryImpl] is used.
|
|
class E2eMockInterceptor extends Interceptor {
|
|
@override
|
|
void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
|
|
final path = options.path;
|
|
if (path.contains('/wallet-types')) {
|
|
handler.resolve(
|
|
Response(
|
|
requestOptions: options,
|
|
data: [
|
|
{
|
|
'id': 1,
|
|
'code': 'USDT',
|
|
'name': 'USDT (TRC20)',
|
|
'decimals': 6,
|
|
'network': 'TRON',
|
|
},
|
|
],
|
|
),
|
|
);
|
|
return;
|
|
}
|
|
if (path.contains('/balances')) {
|
|
handler.resolve(
|
|
Response(
|
|
requestOptions: options,
|
|
data: [
|
|
{
|
|
'walletType': {'id': 1, 'code': 'USDT', 'name': 'USDT', 'decimals': 6},
|
|
'available': '1000000',
|
|
'locked': '0',
|
|
},
|
|
],
|
|
),
|
|
);
|
|
return;
|
|
}
|
|
if (path.contains('/transactions')) {
|
|
handler.resolve(Response(requestOptions: options, data: []));
|
|
return;
|
|
}
|
|
if (path.contains('/advertisements')) {
|
|
handler.resolve(Response(requestOptions: options, data: [
|
|
{
|
|
'id': 'ad-1',
|
|
'placement': 'home_hero',
|
|
'title': 'Welcome to Prediqo',
|
|
'subtitle': 'Predict candle direction',
|
|
'ctaLabel': 'Play',
|
|
'linkUrl': '/predict',
|
|
'imageUrl': null,
|
|
'accentColor': '#10B981',
|
|
'sortOrder': 0,
|
|
},
|
|
]));
|
|
return;
|
|
}
|
|
if (path.contains('/games') && !path.contains('candle-predict')) {
|
|
handler.resolve(Response(requestOptions: options, data: [
|
|
{
|
|
'id': 'g1',
|
|
'slug': 'candle-predict',
|
|
'title': 'Candle Predict',
|
|
'description': 'Long or short before the candle closes.',
|
|
'category': 'prediction',
|
|
'thumbnailUrl': null,
|
|
'accentColor': '#10B981',
|
|
'status': 'active',
|
|
'isFeatured': true,
|
|
'sortOrder': 0,
|
|
},
|
|
]));
|
|
return;
|
|
}
|
|
if (path.contains('/security-notifications')) {
|
|
handler.resolve(Response(requestOptions: options, data: {
|
|
'items': [],
|
|
'total': 0,
|
|
'unreadCount': 0,
|
|
}));
|
|
return;
|
|
}
|
|
handler.next(options);
|
|
}
|
|
}
|
|
|
|
/// Fake auth for E2E: simulates login without a live API.
|
|
class FakeAuthRepository implements AuthRepository {
|
|
FakeAuthRepository({this.startLoggedIn = false});
|
|
|
|
bool startLoggedIn;
|
|
bool _loggedIn = false;
|
|
String? _userId;
|
|
String? _role;
|
|
|
|
@override
|
|
Future<LoginResult> login(String email, String password, {String? totpCode}) async {
|
|
if (email.isEmpty || password.isEmpty) throw Exception('Invalid credentials');
|
|
_loggedIn = true;
|
|
_userId = 'e2e-user';
|
|
_role = 'user';
|
|
return LoginResult(userId: _userId!, emailHash: 'hash', role: _role!, expiresIn: 3600);
|
|
}
|
|
|
|
@override
|
|
Future<RegisterResult> register(RegisterRequest request) async {
|
|
return const RegisterResult(
|
|
message: 'Registered (fake)',
|
|
emailVerificationRequired: true,
|
|
userId: 'e2e-new-user',
|
|
);
|
|
}
|
|
|
|
@override
|
|
Future<List<CountryOption>> getCountries() async => const [
|
|
CountryOption(code: 'FR', name: 'France'),
|
|
CountryOption(code: 'US', name: 'United States'),
|
|
];
|
|
|
|
@override
|
|
Future<({bool valid, String? reason})> validateReferralCode(String code) async =>
|
|
(valid: code.toUpperCase() == 'VALID', reason: null);
|
|
|
|
@override
|
|
Future<void> resendVerificationEmail(String email) async {}
|
|
|
|
@override
|
|
Future<void> logout() async {
|
|
_loggedIn = false;
|
|
_userId = null;
|
|
_role = null;
|
|
}
|
|
|
|
@override
|
|
Future<bool> isLoggedIn() async {
|
|
if (_loggedIn) return true;
|
|
return startLoggedIn;
|
|
}
|
|
|
|
@override
|
|
Future<({String? userId, String? role})> getStoredUser() async {
|
|
if (startLoggedIn && !_loggedIn) {
|
|
return (userId: 'e2e-user', role: 'user');
|
|
}
|
|
return (userId: _userId, role: _role);
|
|
}
|
|
|
|
@override
|
|
Future<Map<String, dynamic>> setup2FA({String? password, String? totpCode}) async =>
|
|
{'qrCodeUrl': 'data:image/png;base64,', 'secret': 'TESTSECRET'};
|
|
|
|
@override
|
|
Future<List<String>> enable2FA(String code) async =>
|
|
const ['AAAA-BBBB', 'CCCC-DDDD', 'EEEE-FFFF'];
|
|
|
|
@override
|
|
Future<List<String>> regenerateRecoveryCodes(String totpCode) async =>
|
|
const ['GGGG-HHHH', 'IIII-JJJJ', 'KKKK-LLLL'];
|
|
|
|
@override
|
|
Future<void> disable2FA({required String password, required String code}) async {}
|
|
|
|
@override
|
|
Future<UserProfile> getProfile() async =>
|
|
const UserProfile(
|
|
email: 'e2e@prediqo.test',
|
|
countryOfResidence: 'FR',
|
|
gender: 'male',
|
|
totpEnabled: false,
|
|
);
|
|
|
|
@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 {
|
|
if (email.isEmpty) throw Exception('Email required');
|
|
}
|
|
}
|
|
|
|
class FakePredictionRepository implements PredictionRepository {
|
|
@override
|
|
Future<GameStateModel> getState({int? intervalMinutes}) async => _sampleState();
|
|
|
|
@override
|
|
Future<CandlesPageModel> getCandlesPage({
|
|
int? intervalMinutes,
|
|
int limit = 60,
|
|
int? beforeOpenMs,
|
|
}) async =>
|
|
const CandlesPageModel(
|
|
items: [
|
|
OhlcCandleModel(time: 1, open: 100, high: 105, low: 99, close: 103, candleOpenMs: 1000),
|
|
OhlcCandleModel(time: 2, open: 103, high: 106, low: 101, close: 102, candleOpenMs: 2000),
|
|
],
|
|
hasMore: false,
|
|
);
|
|
|
|
@override
|
|
Future<void> placeBet({
|
|
required String direction,
|
|
required double stakeAmount,
|
|
required int intervalMinutes,
|
|
String stakeAccountKind = 'main',
|
|
}) async {}
|
|
|
|
@override
|
|
Future<void> placeMultiBet({
|
|
required int level,
|
|
required List<String> sequence,
|
|
required double stakeAmount,
|
|
required int intervalMinutes,
|
|
String stakeAccountKind = 'main',
|
|
}) async {}
|
|
|
|
@override
|
|
Future<AutoSettingsModel> saveAutoSettings(Map<String, dynamic> body) async =>
|
|
AutoSettingsModel(
|
|
enabled: body['enabled'] == true,
|
|
direction: body['direction'] as String?,
|
|
stakeDisplay: (body['stakeAmount'] as num?)?.toDouble() ?? 1,
|
|
mode: (body['mode'] ?? 'each_round').toString(),
|
|
periodMinutes: (body['periodMinutes'] as num?)?.toInt() ?? 1,
|
|
stakeAccountKind: (body['stakeAccountKind'] ?? 'main').toString(),
|
|
);
|
|
|
|
@override
|
|
Future<PredictionsPageModel> getMyBets({
|
|
int page = 1,
|
|
int pageSize = 5,
|
|
int? intervalMinutes,
|
|
String? stakeAccountKind,
|
|
String? status,
|
|
}) async =>
|
|
const PredictionsPageModel(items: [], total: 0, page: 1, totalPages: 1);
|
|
|
|
static GameStateModel _sampleState() => GameStateModel(
|
|
config: const PredictConfigModel(
|
|
stakeAmounts: [1, 5, 10],
|
|
minStakeAmount: 1,
|
|
maxStakeAmount: 100,
|
|
payoutMultiplier: 1.8,
|
|
predictionWindowSeconds: 30,
|
|
isActive: true,
|
|
predictionTypes: PredictionTypesModel(single: true, auto: true, multiCandle: true),
|
|
),
|
|
intervals: const [
|
|
IntervalModel(
|
|
id: 1,
|
|
intervalMinutes: 1,
|
|
label: '1m',
|
|
isDefault: true,
|
|
isActive: true,
|
|
payoutMultiplier: 1.8,
|
|
),
|
|
],
|
|
selectedIntervalMinutes: 1,
|
|
interval: const IntervalModel(
|
|
id: 1,
|
|
intervalMinutes: 1,
|
|
label: '1m',
|
|
isDefault: true,
|
|
isActive: true,
|
|
payoutMultiplier: 1.8,
|
|
),
|
|
round: const RoundModel(
|
|
id: 'r1',
|
|
status: 'betting',
|
|
secondsToBettingEnd: 20,
|
|
secondsToBettingStart: 0,
|
|
secondsToClose: 60,
|
|
longPoolPercent: 52,
|
|
shortPoolPercent: 48,
|
|
),
|
|
multiLevels: const [
|
|
MultiLevelModel(level: 2, candleCount: 2, enabled: true, payoutMultiplier: 3.2),
|
|
],
|
|
);
|
|
}
|
|
|
|
class FakeHealthRepository implements HealthRepository {
|
|
@override
|
|
Future<HealthStatus> getHealth() async => const HealthStatus(
|
|
network: 'shasta',
|
|
withdrawalsEnabled: false,
|
|
env: 'test',
|
|
withdrawalNetworkFeeRaw: '1000000',
|
|
);
|
|
}
|
|
|
|
class FakeReferralRepository implements ReferralRepository {
|
|
@override
|
|
Future<ReferralDashboardModel> getDashboard({int maxDepth = 10}) async =>
|
|
const ReferralDashboardModel(
|
|
referralCode: 'E2ETEST',
|
|
referralLink: 'https://prediqo.test/register?ref=E2ETEST',
|
|
directReferrals: 1,
|
|
bonusWithdrawable: true,
|
|
programEnabled: true,
|
|
networkSize: 1,
|
|
totalEarnedRaw: '0',
|
|
paidRaw: '0',
|
|
pendingRaw: '0',
|
|
);
|
|
|
|
@override
|
|
Future<ReferralCommissionsPage> getCommissions({int limit = 25, int offset = 0}) async =>
|
|
const ReferralCommissionsPage(items: [], total: 0);
|
|
|
|
@override
|
|
Future<({List<BonusBalanceModel> balances, bool bonusWithdrawable})> getBonusBalances() async =>
|
|
(balances: <BonusBalanceModel>[], bonusWithdrawable: false);
|
|
|
|
@override
|
|
Future<void> transferBonusToMain({required int walletTypeId, required String amountRaw}) async {}
|
|
}
|
|
|
|
class FakeFaqRepository implements FaqRepository {
|
|
@override
|
|
Future<List<FaqEntryModel>> listEntries({String? search, String? category}) async => const [
|
|
FaqEntryModel(
|
|
id: '1',
|
|
question: 'How do predictions work?',
|
|
answer: 'Choose long or short before the round locks.',
|
|
category: 'game',
|
|
),
|
|
];
|
|
}
|
|
|
|
class FakeAdvertisementRepository implements AdvertisementRepository {
|
|
@override
|
|
Future<List<AdvertisementModel>> list({String? placement}) async => const [
|
|
AdvertisementModel(
|
|
id: 'ad-1',
|
|
placement: 'home_hero',
|
|
title: 'Welcome to Prediqo',
|
|
subtitle: 'Predict candle direction',
|
|
ctaLabel: 'Play',
|
|
linkUrl: '/predict',
|
|
accentColor: '#10B981',
|
|
sortOrder: 0,
|
|
),
|
|
];
|
|
}
|
|
|
|
class FakeNotificationRepository implements NotificationRepository {
|
|
@override
|
|
Future<SecurityNotificationsPage> list({
|
|
int limit = 30,
|
|
int offset = 0,
|
|
bool unreadOnly = false,
|
|
}) async =>
|
|
const SecurityNotificationsPage(items: [], total: 0, unreadCount: 0);
|
|
|
|
@override
|
|
Future<void> markRead(String notificationId) async {}
|
|
|
|
@override
|
|
Future<void> markAllRead() async {}
|
|
}
|
|
|
|
class FakeGameCatalogRepository implements GameCatalogRepository {
|
|
@override
|
|
Future<List<GameCatalogItem>> list({bool? featured}) async => const [
|
|
GameCatalogItem(
|
|
id: 'g1',
|
|
slug: 'candle-predict',
|
|
title: 'Candle Predict',
|
|
description: 'Long or short before the candle closes.',
|
|
category: 'prediction',
|
|
accentColor: '#10B981',
|
|
status: 'active',
|
|
isFeatured: true,
|
|
sortOrder: 0,
|
|
implementationKey: 'candle-predict',
|
|
),
|
|
];
|
|
}
|
|
|
|
/// Resets DI and registers fakes for integration / E2E widget tests.
|
|
Future<void> setupE2eDependencies({bool loggedIn = false, bool wsEnabled = false}) async {
|
|
if (sl.isRegistered<AuthBloc>()) {
|
|
await sl.reset();
|
|
} else if (sl.isRegistered<AppConfig>()) {
|
|
await sl.reset();
|
|
}
|
|
|
|
final config = AppConfig(
|
|
apiBaseUrl: 'http://localhost:4000',
|
|
isProduction: false,
|
|
wsEnabled: wsEnabled,
|
|
);
|
|
|
|
sl.registerSingleton<AppConfig>(config);
|
|
final localeController = LocaleController();
|
|
await localeController.load();
|
|
sl.registerSingleton<LocaleController>(localeController);
|
|
sl.registerLazySingleton<ApiClient>(() {
|
|
final client = ApiClient(config: sl());
|
|
client.dio.interceptors.insert(0, E2eMockInterceptor());
|
|
return client;
|
|
});
|
|
sl.registerLazySingleton<FakeAuthRepository>(() => FakeAuthRepository(startLoggedIn: loggedIn));
|
|
sl.registerLazySingleton<AuthRepository>(() => sl<FakeAuthRepository>());
|
|
sl.registerLazySingleton<PredictionRepository>(() => FakePredictionRepository());
|
|
sl.registerLazySingleton<HealthRepository>(() => FakeHealthRepository());
|
|
sl.registerLazySingleton<ReferralRepository>(() => FakeReferralRepository());
|
|
sl.registerLazySingleton<FaqRepository>(() => FakeFaqRepository());
|
|
sl.registerLazySingleton<AdvertisementRepository>(() => FakeAdvertisementRepository());
|
|
sl.registerLazySingleton<NotificationRepository>(() => FakeNotificationRepository());
|
|
sl.registerLazySingleton<GameCatalogRepository>(() => FakeGameCatalogRepository());
|
|
sl.registerLazySingleton<GameSocketService>(() => GameSocketService(sl(), sl()));
|
|
sl.registerLazySingleton<WalletRepositoryImpl>(() => WalletRepositoryImpl(sl()));
|
|
sl.registerLazySingleton<AdminRepositoryImpl>(() => AdminRepositoryImpl(sl()));
|
|
sl.registerFactory<AuthBloc>(() => AuthBloc(sl())..add(const AuthCheckRequested()));
|
|
sl.registerFactory<WalletBloc>(() => WalletBloc(sl<WalletRepositoryImpl>()));
|
|
sl.registerFactory<PredictionBloc>(() => PredictionBloc(sl(), sl(), sl()));
|
|
}
|