games_app/prediqo_mobile/test/welcome_section_load_test.dart

446 lines
14 KiB
Dart

import 'dart:async';
import 'package:flutter/material.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/network/connectivity_controller.dart';
import 'package:prediqo_mobile/core/theme/app_theme.dart';
import 'package:prediqo_mobile/data/models/advertisement_models.dart';
import 'package:prediqo_mobile/data/models/game_catalog_models.dart';
import 'package:prediqo_mobile/data/models/marketing_models.dart';
import 'package:prediqo_mobile/domain/repositories/advertisement_repository.dart';
import 'package:prediqo_mobile/domain/repositories/game_catalog_repository.dart';
import 'package:prediqo_mobile/domain/repositories/marketing_repository.dart';
import 'package:prediqo_mobile/features/welcome/presentation/welcome_screen.dart';
import 'package:prediqo_mobile/features/welcome/utils/marketing_fallback.dart';
import 'package:prediqo_mobile/l10n/locale_controller.dart';
import 'package:prediqo_mobile/shared/widgets/offline_banner.dart';
import 'package:prediqo_mobile/shared/widgets/pred_skeleton.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'support/e2e_fixtures.dart';
class _ControllableAds implements AdvertisementRepository {
Completer<List<AdvertisementModel>>? hold;
final List<AdvertisementModel> cached;
var listCalls = 0;
Object? failWith;
_ControllableAds({this.cached = const []});
@override
List<AdvertisementModel>? peekCached({String? placement}) =>
cached.isEmpty ? null : cached;
@override
List<AdvertisementModel>? peekLast({String? placement}) =>
cached.isEmpty ? null : cached;
@override
void invalidate({String? placement}) {}
@override
Future<List<AdvertisementModel>> list({String? placement, bool force = false}) async {
listCalls++;
if (failWith != null) throw failWith!;
if (hold != null) return hold!.future;
return cached.isEmpty
? [
const AdvertisementModel(
id: 'a1',
placement: 'home_hero',
title: 'Bonus',
accentColor: '#10B981',
sortOrder: 0,
),
]
: cached;
}
}
class _ControllableGames implements GameCatalogRepository {
Completer<List<GameCatalogItem>>? hold;
final List<GameCatalogItem> cached;
_ControllableGames({this.cached = const []});
@override
List<GameCatalogItem>? peekCached({bool featured = false}) =>
cached.isEmpty ? null : cached;
@override
List<GameCatalogItem>? peekLast({bool featured = false}) =>
cached.isEmpty ? null : cached;
@override
void invalidate() {}
@override
Future<List<GameCatalogItem>> list({bool? featured, bool force = false}) async {
if (hold != null) return hold!.future;
return cached.isEmpty
? [
const GameCatalogItem(
id: 'g1',
slug: 'candle-predict',
title: 'Candle Predict',
category: 'prediction',
accentColor: '#10B981',
status: 'active',
isFeatured: true,
sortOrder: 0,
implementationKey: 'candle-predict',
),
]
: cached;
}
}
class _ControllableMarketing implements MarketingRepository {
Completer<MarketingActivityFeed>? activityHold;
MarketingActivityFeed? cachedFeed;
List<MarketingWithdrawalItem>? cachedWithdrawals;
Object? failActivity;
Object? failWithdrawals;
@override
MarketingDailyStats? peekLastDailyStats() => null;
@override
MarketingActivityFeed? peekLastActivityFeed() => cachedFeed;
@override
List<MarketingWithdrawalItem>? peekLastWithdrawals() => cachedWithdrawals;
@override
void invalidate() {
cachedFeed = null;
cachedWithdrawals = null;
}
@override
Future<MarketingDailyStats> getDailyStats({bool force = false}) async =>
const MarketingDailyStats(
uniquePlayersToday: 42,
totalParticipationsToday: 128,
day: '2026-10-17',
);
@override
Future<MarketingActivityFeed> getActivityFeed({bool force = false}) async {
if (failActivity != null) throw failActivity!;
if (activityHold != null) return activityHold!.future;
return cachedFeed ??
const MarketingActivityFeed(
activePlayersCount: 1250,
items: [
MarketingActivityItem(
id: 'a1',
publicId: 'ab***12',
kind: 'bet',
amountLabel: '0',
statusLabel: 'Playing',
createdAt: '2026-10-17T12:00:00Z',
synthetic: true,
),
MarketingActivityItem(
id: 'a2',
publicId: 'cd***34',
kind: 'bet',
amountLabel: '0',
statusLabel: 'Playing',
createdAt: '2026-10-17T12:01:00Z',
synthetic: true,
),
MarketingActivityItem(
id: 'a3',
publicId: 'ef***56',
kind: 'bet',
amountLabel: '0',
statusLabel: 'Playing',
createdAt: '2026-10-17T12:02:00Z',
synthetic: true,
),
MarketingActivityItem(
id: 'a4',
publicId: 'gh***78',
kind: 'bet',
amountLabel: '0',
statusLabel: 'Playing',
createdAt: '2026-10-17T12:03:00Z',
synthetic: true,
),
MarketingActivityItem(
id: 'a5',
publicId: 'ij***90',
kind: 'bet',
amountLabel: '0',
statusLabel: 'Playing',
createdAt: '2026-10-17T12:04:00Z',
synthetic: true,
),
MarketingActivityItem(
id: 'a6',
publicId: 'kl***11',
kind: 'bet',
amountLabel: '0',
statusLabel: 'Playing',
createdAt: '2026-10-17T12:05:00Z',
synthetic: true,
),
],
);
}
@override
Future<List<MarketingWithdrawalItem>> getWithdrawalFeed({bool force = false}) async {
if (failWithdrawals != null) throw failWithdrawals!;
return cachedWithdrawals ??
const [
MarketingWithdrawalItem(
id: 'w1',
publicId: 'cd***34',
amountLabel: '50',
statusLabel: 'Completed',
createdAt: '2026-10-17T12:00:00Z',
synthetic: true,
),
];
}
}
const _sampleGame = GameCatalogItem(
id: 'g1',
slug: 'candle-predict',
title: 'Candle Predict',
category: 'prediction',
accentColor: '#10B981',
status: 'active',
isFeatured: true,
sortOrder: 0,
implementationKey: 'candle-predict',
);
Future<void> _bootWelcome({
required AdvertisementRepository ads,
required GameCatalogRepository games,
MarketingRepository? marketing,
}) async {
configureE2eTestEnvironment();
if (sl.isRegistered<AppConfig>()) await sl.reset();
sl.registerSingleton<AppConfig>(
const AppConfig(apiBaseUrl: 'http://localhost', isProduction: false, wsEnabled: false),
);
sl.registerSingleton<ConnectivityController>(ConnectivityController());
final locale = LocaleController();
SharedPreferences.setMockInitialValues({'app_locale': 'en'});
await locale.load();
sl.registerSingleton<LocaleController>(locale);
sl.registerLazySingleton<ApiClient>(() => ApiClient(config: sl()));
sl.registerLazySingleton<AdvertisementRepository>(() => ads);
sl.registerLazySingleton<GameCatalogRepository>(() => games);
sl.registerLazySingleton<MarketingRepository>(
() => marketing ?? _ControllableMarketing(),
);
}
void _tallSurface(WidgetTester tester) {
tester.view.physicalSize = const Size(400, 2800);
tester.view.devicePixelRatio = 1.0;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
}
Future<void> _pumpFrames(WidgetTester tester) async {
await tester.pump();
await tester.pump(const Duration(milliseconds: 50));
await tester.pump(const Duration(milliseconds: 100));
}
void main() {
tearDown(() async {
if (sl.isRegistered<AppConfig>()) await sl.reset();
});
test('empty marketing fallback has no invented activity', () {
expect(emptyMarketingActivityFeed.items, isEmpty);
expect(emptyMarketingActivityFeed.activePlayersCount, 0);
});
test('rotateActivityWindow avoids recently shown ids when possible', () {
final pool = List.generate(
8,
(i) => MarketingActivityItem(
id: 'id$i',
publicId: 'u$i***x',
kind: 'bet',
amountLabel: '0',
statusLabel: 'Playing',
createdAt: '',
synthetic: true,
),
);
final first = rotateActivityWindow(
pool: pool,
windowSize: 5,
generation: 0,
recentlyShown: {},
);
final second = rotateActivityWindow(
pool: pool,
windowSize: 5,
generation: 1,
recentlyShown: first.map((e) => e.publicId).toSet(),
);
expect(first.length, 5);
expect(second.length, 5);
expect(second.map((e) => e.publicId).toSet().intersection(first.map((e) => e.publicId).toSet()).length,
lessThan(5));
});
testWidgets('Welcome paints hero + games while ads still loading', (tester) async {
_tallSurface(tester);
final adsHold = Completer<List<AdvertisementModel>>();
final ads = _ControllableAds()..hold = adsHold;
final games = _ControllableGames(cached: const [_sampleGame]);
await _bootWelcome(ads: ads, games: games);
await tester.pumpWidget(
MaterialApp(theme: AppTheme.dark, home: const WelcomeScreen()),
);
await _pumpFrames(tester);
expect(find.byKey(const Key('welcome_screen')), findsOneWidget);
expect(find.byType(OfflineBanner), findsOneWidget);
expect(find.byKey(const Key('welcome_get_started')), findsOneWidget);
expect(find.text('Candle Predict'), findsOneWidget);
expect(find.byKey(const Key('welcome_stats_strip')), findsNothing);
adsHold.complete(const [
AdvertisementModel(
id: 'a1',
placement: 'home_hero',
title: 'Welcome bonus',
accentColor: '#10B981',
sortOrder: 0,
),
]);
await _pumpFrames(tester);
expect(find.text('Welcome bonus'), findsOneWidget);
await tester.pumpWidget(const SizedBox.shrink());
await tester.pump();
});
testWidgets('Welcome Live Activity shows Playing and active count, no Won/USDT', (tester) async {
_tallSurface(tester);
final ads = _ControllableAds(
cached: const [
AdvertisementModel(
id: 'a1',
placement: 'home_hero',
title: 'Welcome bonus',
accentColor: '#10B981',
sortOrder: 0,
),
],
);
final games = _ControllableGames(cached: const [_sampleGame]);
await _bootWelcome(ads: ads, games: games);
await tester.pumpWidget(
MaterialApp(theme: AppTheme.dark, home: const WelcomeScreen()),
);
await _pumpFrames(tester);
expect(find.byKey(const Key('welcome_activity_ticker')), findsOneWidget);
expect(find.byKey(const Key('welcome_activity_title')), findsOneWidget);
expect(find.textContaining('Playing'), findsWidgets);
expect(find.textContaining('1\u00a0250'), findsOneWidget); // active count
expect(find.text('Won'), findsNothing);
// Activity rows must not show stake amounts like "10 USDT" / "+12 USDT".
expect(find.textContaining('+'), findsNothing);
expect(find.text('50 USDT'), findsOneWidget); // withdrawals only
await tester.pumpWidget(const SizedBox.shrink());
await tester.pump();
});
testWidgets('Welcome marketing soft-fails with titles and section retry', (tester) async {
_tallSurface(tester);
final ads = _ControllableAds(
cached: const [
AdvertisementModel(
id: 'a1',
placement: 'home_hero',
title: 'Welcome bonus',
accentColor: '#10B981',
sortOrder: 0,
),
],
);
final games = _ControllableGames(cached: const [_sampleGame]);
final marketing = _ControllableMarketing()
..failActivity = Exception('activity down')
..failWithdrawals = Exception('wd down');
await _bootWelcome(ads: ads, games: games, marketing: marketing);
await tester.pumpWidget(
MaterialApp(theme: AppTheme.dark, home: const WelcomeScreen()),
);
await _pumpFrames(tester);
// Structure always visible (Featured Games pattern); section-level error only.
expect(find.byKey(const Key('welcome_activity_ticker')), findsOneWidget);
expect(find.byKey(const Key('welcome_activity_title')), findsOneWidget);
expect(find.byKey(const Key('welcome_withdrawal_ticker')), findsOneWidget);
expect(find.byKey(const Key('welcome_withdrawals_title')), findsOneWidget);
expect(find.textContaining('Connection failed'), findsWidgets);
expect(find.byKey(const Key('welcome_stats_strip')), findsNothing);
// Independent retry restores activity without full page reload.
marketing.failActivity = null;
await tester.tap(find.byKey(const Key('section_error_retry')).first);
await _pumpFrames(tester);
expect(find.textContaining('Playing'), findsWidgets);
expect(find.byKey(const Key('welcome_activity_title')), findsOneWidget);
await tester.pumpWidget(const SizedBox.shrink());
await tester.pump();
});
testWidgets('Welcome shows games skeleton while catalog loads', (tester) async {
_tallSurface(tester);
final gamesHold = Completer<List<GameCatalogItem>>();
final ads = _ControllableAds(
cached: const [
AdvertisementModel(
id: 'a1',
placement: 'home_hero',
title: 'Welcome bonus',
accentColor: '#10B981',
sortOrder: 0,
),
],
);
final games = _ControllableGames()..hold = gamesHold;
await _bootWelcome(ads: ads, games: games);
await tester.pumpWidget(
MaterialApp(theme: AppTheme.dark, home: const WelcomeScreen()),
);
await _pumpFrames(tester);
expect(find.byType(PredSkeletonCard), findsWidgets);
gamesHold.complete(const [_sampleGame]);
await _pumpFrames(tester);
expect(find.text('Candle Predict'), findsOneWidget);
await tester.pumpWidget(const SizedBox.shrink());
await tester.pump();
});
}