summaryrefslogtreecommitdiff
path: root/player-android/test/screens/settings_screen_test.dart
blob: 71c2d7d029788828d0e380601c3a3acbafee4205 (plain)
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
// Widget tests for SettingsScreen.
//
// Tests cover:
//   1. Displays username: the token stored in TokenStorage is shown as the
//      signed-in username.
//   2. Saves base URL: entering a URL and tapping Save persists it via the
//      settings provider.
//   3. Logout flow: tapping Log Out calls AuthStateNotifier.logout and clears
//      the stored token.
//
// Riverpod providers are overridden with in-memory fakes so tests run without
// a real server, OS keychain, or SharedPreferences disk I/O.
//
// Run with: flutter test test/screens/settings_screen_test.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/providers/api_client_provider.dart';
import 'package:player_android/providers/auth_state_provider.dart';
import 'package:player_android/providers/settings_provider.dart';
import 'package:player_android/screens/settings_screen.dart';

// ---------------------------------------------------------------------------
// Fakes
// ---------------------------------------------------------------------------

/// In-memory [TokenStorage] that avoids the platform OS keychain in tests.
class _FakeTokenStorage implements TokenStorage {
  String? _token;

  @override
  Future<String?> readToken() async => _token;

  @override
  Future<void> writeToken(String token) async => _token = token;

  @override
  Future<void> deleteToken() async => _token = null;
}

/// In-memory [SettingsNotifier] whose state is set directly in tests.
///
/// Uses [AsyncNotifier] the same way the production notifier does, but
/// bypasses [SharedPreferences] so tests have no disk I/O.
class _FakeSettingsNotifier extends SettingsNotifier {
  _FakeSettingsNotifier(this._initialUrl);

  final String _initialUrl;

  // Captures the last URL passed to setServerBaseUrl for test assertions.
  String? savedUrl;

  @override
  Future<AppSettings> build() async =>
      AppSettings(serverBaseUrl: _initialUrl);

  @override
  Future<void> setServerBaseUrl(String url) async {
    savedUrl = url;
    // Mirror the production implementation: update in-memory state immediately.
    state = AsyncData(AppSettings(serverBaseUrl: url));
  }
}

// ---------------------------------------------------------------------------
// Helper: pump SettingsScreen inside a minimal ProviderScope.
// ---------------------------------------------------------------------------

/// Pumps [SettingsScreen] inside a [ProviderScope] that overrides:
///   - [tokenStorageProvider] with an in-memory fake (avoids OS keychain)
///   - [settingsProvider] with an in-memory fake (avoids SharedPreferences)
///
/// Uses [MaterialApp.router] with a minimal [GoRouter] so that [context.go]
/// calls inside [SettingsScreen._logout] do not throw "No GoRouter in context".
///
/// Returns a record containing:
///   - [storage]: the fake token storage for post-test assertions.
///   - [settings]: the fake settings notifier for post-test assertions.
Future<({_FakeTokenStorage storage, _FakeSettingsNotifier settings})>
    _pumpSettingsScreen(
  WidgetTester tester, {
  String initialToken = 'alice',
  String initialUrl = 'http://10.0.2.2:8080',
}) async {
  final fakeStorage = _FakeTokenStorage().._token = initialToken;
  final fakeSettings = _FakeSettingsNotifier(initialUrl);

  // A minimal GoRouter that renders SettingsScreen at '/'.  The /login route
  // is included so that the safety-net context.go(AppRoutes.login) in
  // _logout() does not trigger a "route not found" error.
  final router = GoRouter(
    initialLocation: '/',
    routes: [
      GoRoute(
        path: '/',
        builder: (_, __) => const SettingsScreen(),
      ),
      GoRoute(
        path: '/login',
        builder: (_, __) => const Scaffold(body: Text('Login')),
      ),
    ],
  );

  await tester.pumpWidget(
    ProviderScope(
      overrides: [
        // Avoid OS keychain / SharedPreferences in tests.
        tokenStorageProvider.overrideWithValue(fakeStorage),
        settingsProvider.overrideWith(() => fakeSettings),
      ],
      child: MaterialApp.router(routerConfig: router),
    ),
  );

  // Allow async providers (_currentUsernameProvider, settingsProvider) to
  // resolve their futures before we inspect the widget tree.
  await tester.pumpAndSettle();

  return (storage: fakeStorage, settings: fakeSettings);
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

void main() {
  // --------------------------------------------------------------------------
  // Username display
  // --------------------------------------------------------------------------

  group('username display', () {
    testWidgets('shows the token stored in TokenStorage as the username',
        (tester) async {
      await _pumpSettingsScreen(tester, initialToken: 'alice');

      // The settings_username widget should show the stored token value.
      expect(find.byKey(const Key('settings_username')), findsOneWidget);
      expect(find.text('alice'), findsOneWidget);
    });

    testWidgets('shows placeholder when no token is stored', (tester) async {
      // Pump with an empty token — simulates a freshly logged-out state
      // where the screen is still mounted transiently before redirect.
      final fakeStorage = _FakeTokenStorage(); // _token is null
      final fakeSettings = _FakeSettingsNotifier('http://10.0.2.2:8080');

      final router = GoRouter(
        initialLocation: '/',
        routes: [
          GoRoute(
            path: '/',
            builder: (_, __) => const SettingsScreen(),
          ),
          GoRoute(
            path: '/login',
            builder: (_, __) => const Scaffold(body: Text('Login')),
          ),
        ],
      );

      await tester.pumpWidget(
        ProviderScope(
          overrides: [
            tokenStorageProvider.overrideWithValue(fakeStorage),
            settingsProvider.overrideWith(() => fakeSettings),
          ],
          child: MaterialApp.router(routerConfig: router),
        ),
      );
      await tester.pumpAndSettle();

      // When the token is null, the username row shows the fallback '—'.
      expect(find.text('—'), findsOneWidget);
    });
  });

  // --------------------------------------------------------------------------
  // Base URL editing
  // --------------------------------------------------------------------------

  group('base URL', () {
    testWidgets('pre-fills the URL field from the settings provider',
        (tester) async {
      await _pumpSettingsScreen(
        tester,
        initialUrl: 'https://player.example.com',
      );

      // The URL field should be seeded with the persisted value.
      final field = tester.widget<TextField>(
        find.byKey(const Key('settings_base_url')),
      );
      expect(field.controller?.text, equals('https://player.example.com'));
    });

    testWidgets('saves URL when Save URL button is tapped', (tester) async {
      final result = await _pumpSettingsScreen(
        tester,
        initialUrl: 'http://10.0.2.2:8080',
      );

      // Edit the URL field.
      await tester.tap(find.byKey(const Key('settings_base_url')));
      await tester.pump();
      await tester.enterText(
        find.byKey(const Key('settings_base_url')),
        'https://new-server.example.com',
      );

      // Tap Save URL.
      await tester.tap(find.byKey(const Key('settings_save_url')));
      await tester.pumpAndSettle();

      // The fake notifier should have captured the new URL.
      expect(
        result.settings.savedUrl,
        equals('https://new-server.example.com'),
      );
    });

    testWidgets('saves URL when keyboard Done action is triggered',
        (tester) async {
      final result = await _pumpSettingsScreen(tester);

      await tester.tap(find.byKey(const Key('settings_base_url')));
      await tester.pump();
      await tester.enterText(
        find.byKey(const Key('settings_base_url')),
        'http://192.168.1.100:8080',
      );

      // Simulate the "Done" keyboard action.
      await tester.testTextInput.receiveAction(TextInputAction.done);
      await tester.pumpAndSettle();

      expect(
        result.settings.savedUrl,
        equals('http://192.168.1.100:8080'),
      );
    });

    testWidgets('does not save when URL field is empty', (tester) async {
      final result = await _pumpSettingsScreen(
        tester,
        initialUrl: 'http://10.0.2.2:8080',
      );

      // Clear the field and tap Save.
      await tester.enterText(find.byKey(const Key('settings_base_url')), '');
      await tester.tap(find.byKey(const Key('settings_save_url')));
      await tester.pumpAndSettle();

      // Nothing should have been saved since the field was blank.
      expect(result.settings.savedUrl, isNull);
    });
  });

  // --------------------------------------------------------------------------
  // Logout flow
  // --------------------------------------------------------------------------

  group('logout flow', () {
    testWidgets('logout button is visible and enabled initially',
        (tester) async {
      await _pumpSettingsScreen(tester);

      expect(find.byKey(const Key('settings_logout')), findsOneWidget);
      expect(find.byType(CircularProgressIndicator), findsNothing);
    });

    testWidgets('tapping logout clears the token from TokenStorage',
        (tester) async {
      final result = await _pumpSettingsScreen(
        tester,
        initialToken: 'alice',
      );

      // Verify the token is set before logout.
      expect(result.storage._token, equals('alice'));

      // Tap the logout button.
      await tester.tap(find.byKey(const Key('settings_logout')));
      await tester.pumpAndSettle();

      // AuthStateNotifier.logout() should have deleted the token.
      expect(result.storage._token, isNull);
    });

    testWidgets('tapping logout updates auth state to unauthenticated',
        (tester) async {
      // Capture the auth state notifier to inspect state after logout.
      AuthState? capturedState;
      final fakeStorage = _FakeTokenStorage().._token = 'bob';
      final fakeSettings = _FakeSettingsNotifier('http://10.0.2.2:8080');

      // Minimal GoRouter: '/' renders SettingsScreen, '/login' is the redirect
      // target so context.go('/login') in the logout handler does not throw.
      final router = GoRouter(
        initialLocation: '/',
        routes: [
          GoRoute(
            path: '/',
            builder: (_, __) => Consumer(
              builder: (context, ref, _) {
                // Watch and capture auth state for post-logout assertion.
                final authAsync = ref.watch(authStateProvider);
                authAsync.whenData((s) => capturedState = s);
                return const SettingsScreen();
              },
            ),
          ),
          GoRoute(
            path: '/login',
            builder: (_, __) => const Scaffold(body: Text('Login')),
          ),
        ],
      );

      await tester.pumpWidget(
        ProviderScope(
          overrides: [
            tokenStorageProvider.overrideWithValue(fakeStorage),
            settingsProvider.overrideWith(() => fakeSettings),
          ],
          child: MaterialApp.router(routerConfig: router),
        ),
      );
      await tester.pumpAndSettle();

      await tester.tap(find.byKey(const Key('settings_logout')));
      await tester.pumpAndSettle();

      // After logout the auth state should be unauthenticated.
      expect(capturedState?.isUnauthenticated, isTrue);
    });
  });
}