1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
|
// Widget tests for PodcastEpisodesScreen (podcast_episodes_screen.dart).
//
// Tests cover:
// 1. Renders a loading indicator while listEpisodes is in flight.
// 2. Renders episode rows after a successful load.
// 3. Shows an empty-state widget when listEpisodes returns [].
// 4. Shows an error view when listEpisodes throws a DioException.
// 5. Pull-to-refresh calls listEpisodes again.
// 6. Played toggle: tapping fires onToggleComplete (optimistic update).
// 7. Progress bar is shown when positionSeconds > 0 and not completed.
// 8. Progress bar is hidden when episode is completed.
// 9. Progress bar is hidden when positionSeconds is 0.
// 10. Revert on error: played icon reverts when toggleEpisodeComplete fails.
// 11. episodeListErrorMessage and episodeToggleErrorMessage helper unit tests.
// 12. Play button visible when mediaId is non-null; tapping navigates to audio player.
// 13. Download button visible when mediaId is null; tapping calls downloadEpisode.
// 14. Download success updates row to show play button.
// 15. Download error shows SnackBar.
// 16. episodeDownloadErrorMessage helper unit tests.
//
// Riverpod providers are overridden with fakes so tests run without a real
// server or OS keychain.
//
// Run with: flutter test test/screens/podcast_episodes_screen_test.dart
import 'dart:async';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:go_router/go_router.dart';
import 'package:player_android/api/dio_client.dart';
import 'package:player_android/api/player_api_client.dart';
import 'package:player_android/models/models.dart';
import 'package:player_android/providers/api_client_provider.dart';
import 'package:player_android/screens/podcast_episodes_screen.dart';
import 'package:player_android/utils/error_mappers.dart';
// ---------------------------------------------------------------------------
// Fakes
// ---------------------------------------------------------------------------
/// In-memory [TokenStorage] used to avoid the platform-specific OS keychain.
class _FakeTokenStorage implements TokenStorage {
const _FakeTokenStorage();
@override
Future<String?> readToken() async => 'test-token';
@override
Future<void> writeToken(String token) async {}
@override
Future<void> deleteToken() async {}
}
/// Controllable [PlayerApiClient] stub for [PodcastEpisodesScreen] tests.
///
/// Implements [listEpisodes], [toggleEpisodeComplete], and [downloadEpisode];
/// all other methods remain [UnimplementedError] — the screen calls only these.
class _FakeApiClient extends PlayerApiClient {
_FakeApiClient() : super(dio: Dio());
/// When non-null, [listEpisodes] returns this list.
List<PodcastEpisode>? episodesResult;
/// When non-null, [listEpisodes] throws this instead of returning.
Object? episodesError;
/// Records every call to [listEpisodes] — useful for refresh tests.
int listEpisodesCallCount = 0;
/// Completer for the current in-flight [toggleEpisodeComplete]; replaced
/// per call so each test can control one toggle at a time.
Completer<void>? _toggleCompleter;
/// Resolves the current pending [toggleEpisodeComplete] successfully.
void completeToggle() => _toggleCompleter?.complete();
/// Rejects the current pending [toggleEpisodeComplete] with [error].
void failToggle(Object error) => _toggleCompleter?.completeError(error);
/// When non-null, [downloadEpisode] returns this [Media] result.
Media? downloadResult;
/// When non-null, [downloadEpisode] throws this error.
Object? downloadError;
/// Records every call to [downloadEpisode] — useful for download tests.
int downloadEpisodeCallCount = 0;
/// When non-null, [downloadEpisode] returns this completer's future instead
/// of resolving immediately. This lets a test hold the first call
/// in-flight so a second tap can be verified to be suppressed by the guard.
Completer<Media>? downloadCompleter;
@override
Future<List<PodcastEpisode>> listEpisodes(
int podcastSetId, {
int? limit,
int? offset,
}) async {
listEpisodesCallCount++;
if (episodesError != null) throw episodesError!;
return episodesResult!;
}
@override
Future<void> toggleEpisodeComplete(int episodeId) {
_toggleCompleter = Completer<void>();
return _toggleCompleter!.future;
}
@override
Future<Media> downloadEpisode(int episodeId) async {
downloadEpisodeCallCount++;
if (downloadError != null) throw downloadError!;
// If a completer is provided, the caller controls when the future resolves.
if (downloadCompleter != null) return downloadCompleter!.future;
return downloadResult!;
}
}
/// [PlayerApiClient] stub that delays [listEpisodes] until [complete] is
/// called. Used to inspect the mid-flight loading state.
class _DelayedFakeApiClient extends PlayerApiClient {
_DelayedFakeApiClient() : super(dio: Dio());
final _completer = Completer<List<PodcastEpisode>>();
/// Resolves the pending [listEpisodes] call with [episodes].
void complete(List<PodcastEpisode> episodes) =>
_completer.complete(episodes);
@override
Future<List<PodcastEpisode>> listEpisodes(
int podcastSetId, {
int? limit,
int? offset,
}) =>
_completer.future;
}
// ---------------------------------------------------------------------------
// Sample data
// ---------------------------------------------------------------------------
/// An unplayed episode with no saved position.
const _kEpisode1 = PodcastEpisode(
id: 1,
feedId: 10,
guid: 'ep-1',
title: 'Introduction to Flutter',
description: 'Episode 1',
episodeUrl: 'https://example.com/ep1.mp3',
fileName: 'ep1.mp3',
isDownloaded: false,
isCompleted: false,
positionSeconds: 0,
durationSeconds: 1800.0, // 30 min
);
/// An episode that has been partially played (halfway through).
const _kEpisodeInProgress = PodcastEpisode(
id: 2,
feedId: 10,
guid: 'ep-2',
title: 'Advanced Dart',
description: 'Episode 2',
episodeUrl: 'https://example.com/ep2.mp3',
fileName: 'ep2.mp3',
isDownloaded: false,
isCompleted: false,
positionSeconds: 900.0, // 15 min of 30 min
durationSeconds: 1800.0,
);
/// An episode that has been fully played / marked as completed.
const _kEpisodeCompleted = PodcastEpisode(
id: 3,
feedId: 10,
guid: 'ep-3',
title: 'State Management',
description: 'Episode 3',
episodeUrl: 'https://example.com/ep3.mp3',
fileName: 'ep3.mp3',
isDownloaded: false,
isCompleted: true,
positionSeconds: 1800.0,
durationSeconds: 1800.0,
);
/// An episode that has been downloaded (mediaId is non-null) and is playable.
const _kEpisodeDownloaded = PodcastEpisode(
id: 4,
feedId: 10,
mediaId: 99,
guid: 'ep-4',
title: 'Async Await Deep Dive',
description: 'Episode 4',
episodeUrl: 'https://example.com/ep4.mp3',
fileName: 'ep4.mp3',
isDownloaded: true,
isCompleted: false,
positionSeconds: 0,
durationSeconds: 2700.0,
);
// ---------------------------------------------------------------------------
// Stub Media used as the downloadEpisode response.
// ---------------------------------------------------------------------------
/// Minimal [Media] stub returned by the fake [downloadEpisode] implementation.
///
/// Only [id] is relevant to [PodcastEpisodesScreen]; the remaining required
/// fields are filled with zero-values so the const constructor compiles.
const _kDownloadedMedia = Media(
id: 55,
setId: 10,
relPath: 'podcasts/ep1.mp3',
fileName: 'ep1.mp3',
absPath: '/media/podcasts/ep1.mp3',
type: 'audio',
duration: 1800.0,
codec: 'mp3',
resolution: '',
bitrate: 128,
fileSizeBytes: 0,
width: 0,
height: 0,
thumbnailPath: '',
playCount: 0,
);
// ---------------------------------------------------------------------------
// Helpers: pump PodcastEpisodesScreen inside a minimal ProviderScope.
// ---------------------------------------------------------------------------
/// Key used by the stub audio-player destination route in navigation tests.
const _kAudioPlayerDestKey = Key('nav_audio_player');
/// Pumps [PodcastEpisodesScreen] (set 10, "Tech Talks") inside a
/// [ProviderScope] that overrides [apiClientProvider] and
/// [tokenStorageProvider] with fakes.
///
/// Uses plain [MaterialApp] (no GoRouter) — suited for tests that do not
/// exercise navigation (i.e. no episode rows with [mediaId] non-null).
Future<void> _pumpScreen(
WidgetTester tester,
PlayerApiClient fakeClient,
) async {
await tester.pumpWidget(
ProviderScope(
overrides: [
tokenStorageProvider.overrideWithValue(const _FakeTokenStorage()),
apiClientProvider.overrideWithValue(fakeClient),
],
child: const MaterialApp(
home: PodcastEpisodesScreen(setId: 10, setName: 'Tech Talks'),
),
),
);
}
/// Builds a [GoRouter] with [PodcastEpisodesScreen] at its root and a stub
/// `/audio/:mediaId` route so navigation tests can verify the correct
/// destination is reached when the play button is tapped.
GoRouter _buildRouterWithAudioStub(PlayerApiClient fakeClient) {
return GoRouter(
initialLocation: '/podcasts/10/episodes',
routes: [
GoRoute(
path: '/podcasts/:setId/episodes',
builder: (context, state) {
final setId = int.tryParse(state.pathParameters['setId']!) ?? 0;
return PodcastEpisodesScreen(setId: setId, setName: 'Tech Talks');
},
),
GoRoute(
path: '/audio/:mediaId',
builder: (context, state) => Scaffold(
body: Text(
'Audio ${state.pathParameters['mediaId']}',
key: _kAudioPlayerDestKey,
),
),
),
],
);
}
/// Pumps [PodcastEpisodesScreen] inside a [GoRouter] so that navigation via
/// `context.go('/audio/:mediaId')` resolves correctly in play-button tests.
Future<void> _pumpScreenWithRouter(
WidgetTester tester,
PlayerApiClient fakeClient,
) async {
final router = _buildRouterWithAudioStub(fakeClient);
await tester.pumpWidget(
ProviderScope(
overrides: [
tokenStorageProvider.overrideWithValue(const _FakeTokenStorage()),
apiClientProvider.overrideWithValue(fakeClient),
],
child: MaterialApp.router(routerConfig: router),
),
);
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
void main() {
// --------------------------------------------------------------------------
// Loading state
// --------------------------------------------------------------------------
group('loading state', () {
testWidgets('shows loading indicator while listEpisodes is in flight',
(tester) async {
final fakeClient = _DelayedFakeApiClient();
await _pumpScreen(tester, fakeClient);
// Pump a single frame: initState → addPostFrameCallback fires, but the
// Future has not resolved yet.
await tester.pump();
expect(find.byKey(const Key('episodes_loading')), findsOneWidget);
expect(find.byType(CircularProgressIndicator), findsAtLeastNWidgets(1));
// Resolve the fake to avoid "async work pending" warnings.
fakeClient.complete([_kEpisode1]);
await tester.pumpAndSettle();
});
});
// --------------------------------------------------------------------------
// Renders episodes
// --------------------------------------------------------------------------
group('renders episode rows', () {
testWidgets('shows a row for each episode returned by listEpisodes',
(tester) async {
final fakeClient = _FakeApiClient()
..episodesResult = [_kEpisode1, _kEpisodeInProgress];
await _pumpScreen(tester, fakeClient);
await tester.pumpAndSettle();
expect(find.text('Introduction to Flutter'), findsOneWidget);
expect(find.text('Advanced Dart'), findsOneWidget);
});
testWidgets('renders the episodes list widget after a successful load',
(tester) async {
final fakeClient = _FakeApiClient()..episodesResult = [_kEpisode1];
await _pumpScreen(tester, fakeClient);
await tester.pumpAndSettle();
expect(find.byKey(const Key('episodes_list')), findsOneWidget);
});
testWidgets('renders individual episode row keys', (tester) async {
final fakeClient = _FakeApiClient()
..episodesResult = [_kEpisode1, _kEpisodeInProgress];
await _pumpScreen(tester, fakeClient);
await tester.pumpAndSettle();
expect(find.byKey(const Key('episode_row_1')), findsOneWidget);
expect(find.byKey(const Key('episode_row_2')), findsOneWidget);
});
testWidgets('shows set name in app bar when provided', (tester) async {
final fakeClient = _FakeApiClient()..episodesResult = [];
await _pumpScreen(tester, fakeClient);
await tester.pumpAndSettle();
expect(find.text('Tech Talks'), findsOneWidget);
});
});
// --------------------------------------------------------------------------
// Played toggle — optimistic update
// --------------------------------------------------------------------------
group('played toggle — optimistic update', () {
testWidgets(
'tapping toggle on unplayed episode immediately shows completed icon',
(tester) async {
final fakeClient = _FakeApiClient()
..episodesResult = [_kEpisode1]; // isCompleted = false
await _pumpScreen(tester, fakeClient);
await tester.pumpAndSettle();
// Before tap: check_circle_outline (unplayed).
final toggleKey = find.byKey(const Key('episode_played_toggle_1'));
expect(toggleKey, findsOneWidget);
expect(
find.descendant(
of: toggleKey,
matching: find.byIcon(Icons.check_circle_outline),
),
findsOneWidget,
);
// Tap the toggle — optimistic update fires immediately.
await tester.tap(toggleKey);
await tester.pump(); // one frame: setState applied
// After tap: check_circle (played), still before API call resolves.
expect(
find.descendant(
of: toggleKey,
matching: find.byIcon(Icons.check_circle),
),
findsOneWidget,
);
// Resolve the API call to prevent "async work pending" warnings.
fakeClient.completeToggle();
await tester.pumpAndSettle();
});
testWidgets(
'tapping toggle on completed episode immediately shows outline icon',
(tester) async {
final fakeClient = _FakeApiClient()
..episodesResult = [_kEpisodeCompleted]; // isCompleted = true
await _pumpScreen(tester, fakeClient);
await tester.pumpAndSettle();
final toggleKey = find.byKey(const Key('episode_played_toggle_3'));
// Before tap: check_circle (played).
expect(
find.descendant(
of: toggleKey,
matching: find.byIcon(Icons.check_circle),
),
findsOneWidget,
);
await tester.tap(toggleKey);
await tester.pump();
// After tap: check_circle_outline (unplayed) — optimistic flip.
expect(
find.descendant(
of: toggleKey,
matching: find.byIcon(Icons.check_circle_outline),
),
findsOneWidget,
);
fakeClient.completeToggle();
await tester.pumpAndSettle();
});
});
// --------------------------------------------------------------------------
// Played toggle — revert on error
// --------------------------------------------------------------------------
group('played toggle — revert on error', () {
testWidgets('reverts to original state when toggleEpisodeComplete fails',
(tester) async {
final fakeClient = _FakeApiClient()
..episodesResult = [_kEpisode1]; // isCompleted = false
await _pumpScreen(tester, fakeClient);
await tester.pumpAndSettle();
final toggleKey = find.byKey(const Key('episode_played_toggle_1'));
// Tap to trigger optimistic update.
await tester.tap(toggleKey);
await tester.pump();
// Optimistic state: check_circle (played).
expect(
find.descendant(
of: toggleKey,
matching: find.byIcon(Icons.check_circle),
),
findsOneWidget,
);
// Fail the API call — the screen should revert.
fakeClient.failToggle(
DioException(
requestOptions: RequestOptions(path: '/api/v1/podcasts/episodes/1/complete'),
type: DioExceptionType.connectionError,
),
);
await tester.pumpAndSettle();
// After revert: check_circle_outline (unplayed) again.
expect(
find.descendant(
of: toggleKey,
matching: find.byIcon(Icons.check_circle_outline),
),
findsOneWidget,
);
// A SnackBar error message is shown.
expect(find.byType(SnackBar), findsOneWidget);
expect(
find.textContaining('Could not reach'),
findsOneWidget,
);
});
});
// --------------------------------------------------------------------------
// Progress bar visibility
// --------------------------------------------------------------------------
group('progress bar visibility', () {
testWidgets(
'shows progress bar when positionSeconds > 0 and not completed',
(tester) async {
final fakeClient = _FakeApiClient()
..episodesResult = [_kEpisodeInProgress]; // pos=900, dur=1800, not completed
await _pumpScreen(tester, fakeClient);
await tester.pumpAndSettle();
expect(find.byKey(const Key('episode_progress_bar')), findsOneWidget);
});
testWidgets('hides progress bar when episode is completed', (tester) async {
final fakeClient = _FakeApiClient()
..episodesResult = [_kEpisodeCompleted]; // isCompleted = true
await _pumpScreen(tester, fakeClient);
await tester.pumpAndSettle();
expect(find.byKey(const Key('episode_progress_bar')), findsNothing);
});
testWidgets('hides progress bar when positionSeconds is 0', (tester) async {
final fakeClient = _FakeApiClient()
..episodesResult = [_kEpisode1]; // positionSeconds = 0
await _pumpScreen(tester, fakeClient);
await tester.pumpAndSettle();
expect(find.byKey(const Key('episode_progress_bar')), findsNothing);
});
testWidgets('progress bar value reflects fraction of duration played',
(tester) async {
final fakeClient = _FakeApiClient()
..episodesResult = [_kEpisodeInProgress]; // 900/1800 = 0.5
await _pumpScreen(tester, fakeClient);
await tester.pumpAndSettle();
final progressBar = tester.widget<LinearProgressIndicator>(
find.byKey(const Key('episode_progress_bar')),
);
// 900 / 1800 = 0.5; allow floating-point tolerance.
expect(progressBar.value, closeTo(0.5, 0.001));
});
});
// --------------------------------------------------------------------------
// Empty state
// --------------------------------------------------------------------------
group('empty state', () {
testWidgets('shows empty-state widget when listEpisodes returns []',
(tester) async {
final fakeClient = _FakeApiClient()..episodesResult = [];
await _pumpScreen(tester, fakeClient);
await tester.pumpAndSettle();
expect(find.byKey(const Key('episodes_empty')), findsOneWidget);
expect(find.byKey(const Key('episodes_list')), findsNothing);
expect(find.byKey(const Key('episodes_loading')), findsNothing);
});
});
// --------------------------------------------------------------------------
// Error state
// --------------------------------------------------------------------------
group('error state', () {
testWidgets('shows error message when listEpisodes throws a network error',
(tester) async {
final fakeClient = _FakeApiClient()
..episodesError = DioException(
requestOptions:
RequestOptions(path: '/api/v1/podcasts/10/episodes'),
type: DioExceptionType.connectionError,
);
await _pumpScreen(tester, fakeClient);
await tester.pumpAndSettle();
expect(find.byKey(const Key('episodes_error')), findsOneWidget);
expect(find.byKey(const Key('episodes_list')), findsNothing);
expect(
find.textContaining('Could not reach the server'),
findsOneWidget,
);
});
testWidgets('shows retry button and a successful retry renders the list',
(tester) async {
final fakeClient = _FakeApiClient()
..episodesError = DioException(
requestOptions:
RequestOptions(path: '/api/v1/podcasts/10/episodes'),
type: DioExceptionType.connectionError,
);
await _pumpScreen(tester, fakeClient);
await tester.pumpAndSettle();
expect(find.byKey(const Key('episodes_retry')), findsOneWidget);
// Fix the error before tapping retry.
fakeClient
..episodesError = null
..episodesResult = [_kEpisode1];
await tester.tap(find.byKey(const Key('episodes_retry')));
await tester.pumpAndSettle();
expect(find.byKey(const Key('episodes_list')), findsOneWidget);
// listEpisodes was called twice: once on init, once on retry.
expect(fakeClient.listEpisodesCallCount, equals(2));
});
});
// --------------------------------------------------------------------------
// Pull-to-refresh
// --------------------------------------------------------------------------
group('pull-to-refresh', () {
testWidgets('pull-to-refresh calls listEpisodes a second time',
(tester) async {
final fakeClient = _FakeApiClient()..episodesResult = [_kEpisode1];
await _pumpScreen(tester, fakeClient);
await tester.pumpAndSettle();
expect(fakeClient.listEpisodesCallCount, equals(1));
// Simulate pull-to-refresh by dragging down on the list.
await tester.drag(
find.byKey(const Key('episodes_list')),
const Offset(0, 300),
);
await tester.pumpAndSettle();
expect(fakeClient.listEpisodesCallCount, equals(2));
});
});
// --------------------------------------------------------------------------
// episodeListErrorMessage helper
// --------------------------------------------------------------------------
group('episodeListErrorMessage', () {
test('returns connectivity message for connectionError', () {
final err = DioException(
requestOptions: RequestOptions(path: '/api/v1/podcasts/10/episodes'),
type: DioExceptionType.connectionError,
);
expect(
episodeListErrorMessage(err),
contains('Could not reach the server'),
);
});
test('returns not-found message for 404', () {
final err = DioException(
requestOptions: RequestOptions(path: '/api/v1/podcasts/10/episodes'),
response: Response(
requestOptions: RequestOptions(path: '/api/v1/podcasts/10/episodes'),
statusCode: 404,
),
type: DioExceptionType.badResponse,
);
expect(episodeListErrorMessage(err), contains('not found'));
});
test('returns generic message for unknown error type', () {
expect(
episodeListErrorMessage(Exception('boom')),
contains('Unexpected error'),
);
});
});
// --------------------------------------------------------------------------
// episodeToggleErrorMessage helper
// --------------------------------------------------------------------------
group('episodeToggleErrorMessage', () {
test('returns connectivity message for connectionError', () {
final err = DioException(
requestOptions:
RequestOptions(path: '/api/v1/podcasts/episodes/1/complete'),
type: DioExceptionType.connectionError,
);
expect(
episodeToggleErrorMessage(err),
contains('Could not reach'),
);
});
test('returns not-found message for 404', () {
final err = DioException(
requestOptions:
RequestOptions(path: '/api/v1/podcasts/episodes/1/complete'),
response: Response(
requestOptions:
RequestOptions(path: '/api/v1/podcasts/episodes/1/complete'),
statusCode: 404,
),
type: DioExceptionType.badResponse,
);
expect(episodeToggleErrorMessage(err), contains('not found'));
});
test('returns permission message for 403', () {
final err = DioException(
requestOptions:
RequestOptions(path: '/api/v1/podcasts/episodes/1/complete'),
response: Response(
requestOptions:
RequestOptions(path: '/api/v1/podcasts/episodes/1/complete'),
statusCode: 403,
),
type: DioExceptionType.badResponse,
);
expect(episodeToggleErrorMessage(err), contains('permission'));
});
test('returns generic message for non-Dio error', () {
expect(
episodeToggleErrorMessage(Exception('boom')),
contains('Could not update episode'),
);
});
});
// --------------------------------------------------------------------------
// Play button
// --------------------------------------------------------------------------
group('play button', () {
testWidgets(
'shows play button when episode has a mediaId (is downloaded)',
(tester) async {
final fakeClient = _FakeApiClient()
..episodesResult = [_kEpisodeDownloaded]; // mediaId: 99
await _pumpScreenWithRouter(tester, fakeClient);
await tester.pumpAndSettle();
expect(
find.byKey(const Key('episode_play_button_4')),
findsOneWidget,
);
// Download button must not appear when mediaId is set.
expect(
find.byKey(const Key('episode_download_button_4')),
findsNothing,
);
});
testWidgets(
'tapping play button navigates to audio player screen',
(tester) async {
final fakeClient = _FakeApiClient()
..episodesResult = [_kEpisodeDownloaded]; // mediaId: 99
await _pumpScreenWithRouter(tester, fakeClient);
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('episode_play_button_4')));
await tester.pumpAndSettle();
// Navigation should have pushed the stub audio-player route.
expect(find.byKey(_kAudioPlayerDestKey), findsOneWidget);
expect(find.text('Audio 99'), findsOneWidget);
});
});
// --------------------------------------------------------------------------
// Download button
// --------------------------------------------------------------------------
group('download button', () {
testWidgets(
'shows download button when episode has no mediaId (not downloaded)',
(tester) async {
final fakeClient = _FakeApiClient()
..episodesResult = [_kEpisode1]; // mediaId: null
await _pumpScreen(tester, fakeClient);
await tester.pumpAndSettle();
expect(
find.byKey(const Key('episode_download_button_1')),
findsOneWidget,
);
// Play button must not appear when mediaId is null.
expect(
find.byKey(const Key('episode_play_button_1')),
findsNothing,
);
});
testWidgets(
'tapping download button calls downloadEpisode',
(tester) async {
final fakeClient = _FakeApiClient()
..episodesResult = [_kEpisode1]
..downloadResult = _kDownloadedMedia;
await _pumpScreen(tester, fakeClient);
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('episode
|