mirror of
https://github.com/wger-project/flutter.git
synced 2026-12-03 02:24:30 +01:00
Switch the pasted-token field from DRF tokens to refresh tokens
This commit is contained in:
370
test/auth/auth_notifier_login_test.dart
Normal file
370
test/auth/auth_notifier_login_test.dart
Normal file
@@ -0,0 +1,370 @@
|
||||
/*
|
||||
* This file is part of wger Workout Manager <https://github.com/wger-project>.
|
||||
* Copyright (c) 2026 wger Team
|
||||
*
|
||||
* wger Workout Manager is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:http/http.dart';
|
||||
import 'package:mockito/annotations.dart';
|
||||
import 'package:mockito/mockito.dart';
|
||||
import 'package:package_info_plus/package_info_plus.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
|
||||
import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
|
||||
import 'package:wger/core/exceptions/http_exception.dart';
|
||||
import 'package:wger/core/exceptions/mfa_required_exception.dart';
|
||||
import 'package:wger/helpers/consts.dart';
|
||||
import 'package:wger/helpers/shared_preferences.dart';
|
||||
import 'package:wger/providers/auth_notifier.dart';
|
||||
import 'package:wger/providers/auth_state.dart';
|
||||
import 'package:wger/providers/secure_token_storage.dart';
|
||||
|
||||
import 'auth_notifier_login_test.mocks.dart';
|
||||
|
||||
@GenerateMocks([http.Client, SecureTokenStorage])
|
||||
void main() {
|
||||
SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty();
|
||||
|
||||
late MockClient mockClient;
|
||||
late MockSecureTokenStorage mockSecureStorage;
|
||||
|
||||
const serverUrl = 'https://wger.example';
|
||||
const username = 'alice';
|
||||
const password = 'hunter2';
|
||||
const powerSyncUrl = 'https://ps.example/';
|
||||
|
||||
final tHeadlessLogin = Uri.parse('$serverUrl/_allauth/app/v1/auth/login');
|
||||
final tHeadlessSignup = Uri.parse('$serverUrl/_allauth/app/v1/auth/signup');
|
||||
final tVersion = Uri.parse('$serverUrl/api/v2/version/');
|
||||
final tMinAppVersion = Uri.parse('$serverUrl/api/v2/min-app-version/');
|
||||
final tPowerSyncToken = Uri.parse('$serverUrl/api/v2/powersync-token');
|
||||
final tLiveness = Uri.parse('${powerSyncUrl}probes/liveness');
|
||||
|
||||
/// Builds a JWT-shaped string with the given payload. Signature is a sham,
|
||||
/// we only decode the middle segment.
|
||||
String makeJwt(Map<String, dynamic> payload) {
|
||||
String enc(Map<String, dynamic> m) =>
|
||||
base64Url.encode(utf8.encode(jsonEncode(m))).replaceAll('=', '');
|
||||
return '${enc({'alg': 'HS256', 'typ': 'JWT'})}.${enc(payload)}.signature';
|
||||
}
|
||||
|
||||
ProviderContainer makeContainer() {
|
||||
final c = ProviderContainer(
|
||||
overrides: [
|
||||
authHttpClientProvider.overrideWithValue(mockClient),
|
||||
secureTokenStorageProvider.overrideWithValue(mockSecureStorage),
|
||||
],
|
||||
);
|
||||
addTearDown(c.dispose);
|
||||
return c;
|
||||
}
|
||||
|
||||
setUp(() async {
|
||||
mockClient = MockClient();
|
||||
mockSecureStorage = MockSecureTokenStorage();
|
||||
when(mockSecureStorage.deleteRefreshToken()).thenAnswer((_) async {});
|
||||
when(mockSecureStorage.readRefreshToken()).thenAnswer((_) async => null);
|
||||
when(mockSecureStorage.writeRefreshToken(any)).thenAnswer((_) async {});
|
||||
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
PackageInfo.setMockInitialValues(
|
||||
appName: 'wger',
|
||||
packageName: 'com.example.example',
|
||||
version: '1.2.3',
|
||||
buildNumber: '2',
|
||||
buildSignature: 'buildSignature',
|
||||
);
|
||||
await PreferenceHelper.asyncPref.clear();
|
||||
|
||||
// Default gating-chain mocks (happy path). Login-flow tests override
|
||||
// only what they care about.
|
||||
when(mockClient.get(tVersion)).thenAnswer((_) async => Response('"99.99.99"', 200));
|
||||
when(mockClient.get(tMinAppVersion)).thenAnswer((_) async => Response('"0.0.1"', 200));
|
||||
when(
|
||||
mockClient.get(tPowerSyncToken, headers: anyNamed('headers')),
|
||||
).thenAnswer(
|
||||
(_) async => Response(
|
||||
jsonEncode({'token': 'ps-jwt', 'powersync_url': powerSyncUrl}),
|
||||
200,
|
||||
),
|
||||
);
|
||||
when(mockClient.get(tLiveness)).thenAnswer((_) async => Response('OK', 200));
|
||||
// _serverConfigSane probe → null `next` means clean.
|
||||
when(
|
||||
mockClient.get(any, headers: anyNamed('headers')),
|
||||
).thenAnswer((_) async => Response(jsonEncode({'next': null}), 200));
|
||||
// Re-stub the explicit ones (any-match above otherwise wins).
|
||||
when(mockClient.get(tVersion)).thenAnswer((_) async => Response('"99.99.99"', 200));
|
||||
when(mockClient.get(tMinAppVersion)).thenAnswer((_) async => Response('"0.0.1"', 200));
|
||||
when(
|
||||
mockClient.get(tPowerSyncToken, headers: anyNamed('headers')),
|
||||
).thenAnswer(
|
||||
(_) async => Response(
|
||||
jsonEncode({'token': 'ps-jwt', 'powersync_url': powerSyncUrl}),
|
||||
200,
|
||||
),
|
||||
);
|
||||
when(mockClient.get(tLiveness)).thenAnswer((_) async => Response('OK', 200));
|
||||
});
|
||||
|
||||
group('login: headless happy path', () {
|
||||
test('200 → stores headless JWT bundle, wipes legacy PREFS_USER, state has tokens', () async {
|
||||
final accessJwt = makeJwt({'sub': '7', 'exp': 1900000000});
|
||||
when(
|
||||
mockClient.post(tHeadlessLogin, headers: anyNamed('headers'), body: anyNamed('body')),
|
||||
).thenAnswer(
|
||||
(_) async => Response(
|
||||
jsonEncode({
|
||||
'status': 200,
|
||||
'data': {},
|
||||
'meta': {'access_token': accessJwt, 'refresh_token': 'fresh-refresh'},
|
||||
}),
|
||||
200,
|
||||
),
|
||||
);
|
||||
|
||||
final container = makeContainer();
|
||||
// Let auto-login settle as logged-out (no PREFS_USER yet).
|
||||
await container.read(authProvider.future);
|
||||
|
||||
// Seed a stale legacy blob *after* auto-login, so we can assert
|
||||
// login() wipes it on success without auto-login itself trying to
|
||||
// probe with it.
|
||||
await PreferenceHelper.asyncPref.setString(
|
||||
PREFS_USER,
|
||||
jsonEncode({'token': 'stale-legacy', 'serverUrl': serverUrl}),
|
||||
);
|
||||
|
||||
final result = await container
|
||||
.read(authProvider.notifier)
|
||||
.login(username, password, serverUrl, null);
|
||||
|
||||
expect(result, LoginActions.proceed);
|
||||
final state = container.read(authProvider).value!;
|
||||
expect(state.tokenType, AuthTokenType.headlessJwt);
|
||||
expect(state.accessToken, accessJwt);
|
||||
expect(state.token, isNull);
|
||||
expect(state.status, AuthStatus.loggedIn);
|
||||
|
||||
// Refresh token in secure storage.
|
||||
verify(mockSecureStorage.writeRefreshToken('fresh-refresh')).called(1);
|
||||
|
||||
// Headless prefs populated.
|
||||
final prefs = PreferenceHelper.asyncPref;
|
||||
expect(await prefs.getString(PREFS_ACCESS_TOKEN), accessJwt);
|
||||
expect(await prefs.getString(PREFS_TOKEN_TYPE), AuthTokenType.headlessJwt.name);
|
||||
expect(await prefs.getString(PREFS_SERVER_URL), serverUrl);
|
||||
|
||||
// Stale legacy blob wiped.
|
||||
expect(await prefs.containsKey(PREFS_USER), false);
|
||||
});
|
||||
|
||||
test('Authorization is not built by the notifier itself; the auth client owns it', () async {
|
||||
final accessJwt = makeJwt({'exp': 1900000000});
|
||||
when(
|
||||
mockClient.post(tHeadlessLogin, headers: anyNamed('headers'), body: anyNamed('body')),
|
||||
).thenAnswer(
|
||||
(_) async => Response(
|
||||
jsonEncode({
|
||||
'status': 200,
|
||||
'data': {},
|
||||
'meta': {'access_token': accessJwt, 'refresh_token': 'r'},
|
||||
}),
|
||||
200,
|
||||
),
|
||||
);
|
||||
|
||||
final container = makeContainer();
|
||||
await container.read(authProvider.future);
|
||||
await container.read(authProvider.notifier).login(username, password, serverUrl, null);
|
||||
|
||||
// The headless login POST is unauthenticated (no Authorization header).
|
||||
final captured =
|
||||
verify(
|
||||
mockClient.post(
|
||||
tHeadlessLogin,
|
||||
headers: captureAnyNamed('headers'),
|
||||
body: anyNamed('body'),
|
||||
),
|
||||
).captured.last
|
||||
as Map<String, String>;
|
||||
expect(captured.containsKey('authorization'), false);
|
||||
});
|
||||
});
|
||||
|
||||
group('login: headless 401 / MFA detection', () {
|
||||
test(
|
||||
'401 with `meta.session_token` + `mfa_authenticate` flow → MfaRequiredException',
|
||||
() async {
|
||||
when(
|
||||
mockClient.post(tHeadlessLogin, headers: anyNamed('headers'), body: anyNamed('body')),
|
||||
).thenAnswer(
|
||||
(_) async => Response(
|
||||
jsonEncode({
|
||||
'status': 401,
|
||||
'data': {
|
||||
'flows': [
|
||||
{
|
||||
'id': 'mfa_authenticate',
|
||||
'is_pending': true,
|
||||
'types': ['totp', 'recovery_codes'],
|
||||
},
|
||||
],
|
||||
},
|
||||
'meta': {'session_token': 'flow-handle-xyz', 'is_authenticated': false},
|
||||
}),
|
||||
401,
|
||||
),
|
||||
);
|
||||
|
||||
final container = makeContainer();
|
||||
await container.read(authProvider.future);
|
||||
|
||||
try {
|
||||
await container.read(authProvider.notifier).login(username, password, serverUrl, null);
|
||||
fail('expected MfaRequiredException');
|
||||
} on MfaRequiredException catch (e) {
|
||||
expect(e.sessionToken, 'flow-handle-xyz');
|
||||
expect(e.availableFactors, ['totp', 'recovery_codes']);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test('plain 401 (no session_token) → WgerHttpException', () async {
|
||||
when(
|
||||
mockClient.post(tHeadlessLogin, headers: anyNamed('headers'), body: anyNamed('body')),
|
||||
).thenAnswer(
|
||||
(_) async => Response(
|
||||
jsonEncode({
|
||||
'status': 401,
|
||||
'data': {},
|
||||
'meta': {'is_authenticated': false},
|
||||
}),
|
||||
401,
|
||||
),
|
||||
);
|
||||
|
||||
final container = makeContainer();
|
||||
await container.read(authProvider.future);
|
||||
|
||||
expect(
|
||||
container.read(authProvider.notifier).login(username, password, serverUrl, null),
|
||||
throwsA(isA<WgerHttpException>()),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
group('login: pasted refresh token', () {
|
||||
final tRefresh = Uri.parse('$serverUrl/_allauth/app/v1/tokens/refresh');
|
||||
|
||||
test('exchanges at tokens/refresh and stores the rotated bundle', () async {
|
||||
final newAccess = makeJwt({'exp': 1900000000});
|
||||
when(
|
||||
mockClient.post(tRefresh, headers: anyNamed('headers'), body: anyNamed('body')),
|
||||
).thenAnswer(
|
||||
(_) async => Response(
|
||||
jsonEncode({
|
||||
'status': 200,
|
||||
'data': {},
|
||||
'meta': {'access_token': newAccess, 'refresh_token': 'rotated-refresh'},
|
||||
}),
|
||||
200,
|
||||
),
|
||||
);
|
||||
|
||||
final container = makeContainer();
|
||||
await container.read(authProvider.future);
|
||||
|
||||
final result = await container
|
||||
.read(authProvider.notifier)
|
||||
.login('', '', serverUrl, 'pasted-refresh-token');
|
||||
|
||||
expect(result, LoginActions.proceed);
|
||||
final state = container.read(authProvider).value!;
|
||||
expect(state.tokenType, AuthTokenType.headlessJwt);
|
||||
expect(state.accessToken, newAccess);
|
||||
|
||||
verify(mockSecureStorage.writeRefreshToken('rotated-refresh')).called(1);
|
||||
// Must not have hit the username/password endpoint.
|
||||
verifyNever(
|
||||
mockClient.post(tHeadlessLogin, headers: anyNamed('headers'), body: anyNamed('body')),
|
||||
);
|
||||
// The pasted refresh token is sent as the body of the exchange call.
|
||||
final captured =
|
||||
verify(
|
||||
mockClient.post(
|
||||
tRefresh,
|
||||
headers: anyNamed('headers'),
|
||||
body: captureAnyNamed('body'),
|
||||
),
|
||||
).captured.single
|
||||
as String;
|
||||
expect(jsonDecode(captured)['refresh_token'], 'pasted-refresh-token');
|
||||
});
|
||||
|
||||
test('server rejection surfaces as WgerHttpException', () async {
|
||||
when(
|
||||
mockClient.post(tRefresh, headers: anyNamed('headers'), body: anyNamed('body')),
|
||||
).thenAnswer((_) async => Response(jsonEncode({'detail': 'invalid'}), 401));
|
||||
|
||||
final container = makeContainer();
|
||||
await container.read(authProvider.future);
|
||||
|
||||
expect(
|
||||
container.read(authProvider.notifier).login('', '', serverUrl, 'bad-refresh-token'),
|
||||
throwsA(isA<WgerHttpException>()),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
group('register: headless signup', () {
|
||||
test('200 stores tokens directly without a follow-up login call', () async {
|
||||
final accessJwt = makeJwt({'exp': 1900000000});
|
||||
when(
|
||||
mockClient.post(tHeadlessSignup, headers: anyNamed('headers'), body: anyNamed('body')),
|
||||
).thenAnswer(
|
||||
(_) async => Response(
|
||||
jsonEncode({
|
||||
'status': 200,
|
||||
'data': {},
|
||||
'meta': {'access_token': accessJwt, 'refresh_token': 'r'},
|
||||
}),
|
||||
200,
|
||||
),
|
||||
);
|
||||
|
||||
final container = makeContainer();
|
||||
await container.read(authProvider.future);
|
||||
|
||||
final result = await container
|
||||
.read(authProvider.notifier)
|
||||
.register(
|
||||
username: username,
|
||||
password: password,
|
||||
email: 'alice@example.com',
|
||||
serverUrl: serverUrl,
|
||||
);
|
||||
|
||||
expect(result, LoginActions.proceed);
|
||||
expect(container.read(authProvider).value!.tokenType, AuthTokenType.headlessJwt);
|
||||
verify(mockSecureStorage.writeRefreshToken('r')).called(1);
|
||||
});
|
||||
});
|
||||
}
|
||||
254
test/auth/auth_notifier_login_test.mocks.dart
Normal file
254
test/auth/auth_notifier_login_test.mocks.dart
Normal file
@@ -0,0 +1,254 @@
|
||||
// Mocks generated by Mockito 5.4.6 from annotations
|
||||
// in wger/test/auth/auth_notifier_login_test.dart.
|
||||
// Do not manually edit this file.
|
||||
|
||||
// ignore_for_file: no_leading_underscores_for_library_prefixes
|
||||
import 'dart:async' as _i3;
|
||||
import 'dart:convert' as _i4;
|
||||
import 'dart:typed_data' as _i6;
|
||||
|
||||
import 'package:http/http.dart' as _i2;
|
||||
import 'package:mockito/mockito.dart' as _i1;
|
||||
import 'package:mockito/src/dummies.dart' as _i5;
|
||||
import 'package:wger/providers/secure_token_storage.dart' as _i7;
|
||||
|
||||
// ignore_for_file: type=lint
|
||||
// ignore_for_file: avoid_redundant_argument_values
|
||||
// ignore_for_file: avoid_setters_without_getters
|
||||
// ignore_for_file: comment_references
|
||||
// ignore_for_file: deprecated_member_use
|
||||
// ignore_for_file: deprecated_member_use_from_same_package
|
||||
// ignore_for_file: implementation_imports
|
||||
// ignore_for_file: invalid_use_of_visible_for_testing_member
|
||||
// ignore_for_file: must_be_immutable
|
||||
// ignore_for_file: prefer_const_constructors
|
||||
// ignore_for_file: unnecessary_parenthesis
|
||||
// ignore_for_file: camel_case_types
|
||||
// ignore_for_file: subtype_of_sealed_class
|
||||
// ignore_for_file: invalid_use_of_internal_member
|
||||
|
||||
class _FakeResponse_0 extends _i1.SmartFake implements _i2.Response {
|
||||
_FakeResponse_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation);
|
||||
}
|
||||
|
||||
class _FakeStreamedResponse_1 extends _i1.SmartFake implements _i2.StreamedResponse {
|
||||
_FakeStreamedResponse_1(Object parent, Invocation parentInvocation)
|
||||
: super(parent, parentInvocation);
|
||||
}
|
||||
|
||||
/// A class which mocks [Client].
|
||||
///
|
||||
/// See the documentation for Mockito's code generation for more information.
|
||||
class MockClient extends _i1.Mock implements _i2.Client {
|
||||
MockClient() {
|
||||
_i1.throwOnMissingStub(this);
|
||||
}
|
||||
|
||||
@override
|
||||
_i3.Future<_i2.Response> head(Uri? url, {Map<String, String>? headers}) =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.method(#head, [url], {#headers: headers}),
|
||||
returnValue: _i3.Future<_i2.Response>.value(
|
||||
_FakeResponse_0(
|
||||
this,
|
||||
Invocation.method(#head, [url], {#headers: headers}),
|
||||
),
|
||||
),
|
||||
)
|
||||
as _i3.Future<_i2.Response>);
|
||||
|
||||
@override
|
||||
_i3.Future<_i2.Response> get(Uri? url, {Map<String, String>? headers}) =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.method(#get, [url], {#headers: headers}),
|
||||
returnValue: _i3.Future<_i2.Response>.value(
|
||||
_FakeResponse_0(
|
||||
this,
|
||||
Invocation.method(#get, [url], {#headers: headers}),
|
||||
),
|
||||
),
|
||||
)
|
||||
as _i3.Future<_i2.Response>);
|
||||
|
||||
@override
|
||||
_i3.Future<_i2.Response> post(
|
||||
Uri? url, {
|
||||
Map<String, String>? headers,
|
||||
Object? body,
|
||||
_i4.Encoding? encoding,
|
||||
}) =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.method(
|
||||
#post,
|
||||
[url],
|
||||
{#headers: headers, #body: body, #encoding: encoding},
|
||||
),
|
||||
returnValue: _i3.Future<_i2.Response>.value(
|
||||
_FakeResponse_0(
|
||||
this,
|
||||
Invocation.method(
|
||||
#post,
|
||||
[url],
|
||||
{#headers: headers, #body: body, #encoding: encoding},
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
as _i3.Future<_i2.Response>);
|
||||
|
||||
@override
|
||||
_i3.Future<_i2.Response> put(
|
||||
Uri? url, {
|
||||
Map<String, String>? headers,
|
||||
Object? body,
|
||||
_i4.Encoding? encoding,
|
||||
}) =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.method(
|
||||
#put,
|
||||
[url],
|
||||
{#headers: headers, #body: body, #encoding: encoding},
|
||||
),
|
||||
returnValue: _i3.Future<_i2.Response>.value(
|
||||
_FakeResponse_0(
|
||||
this,
|
||||
Invocation.method(
|
||||
#put,
|
||||
[url],
|
||||
{#headers: headers, #body: body, #encoding: encoding},
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
as _i3.Future<_i2.Response>);
|
||||
|
||||
@override
|
||||
_i3.Future<_i2.Response> patch(
|
||||
Uri? url, {
|
||||
Map<String, String>? headers,
|
||||
Object? body,
|
||||
_i4.Encoding? encoding,
|
||||
}) =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.method(
|
||||
#patch,
|
||||
[url],
|
||||
{#headers: headers, #body: body, #encoding: encoding},
|
||||
),
|
||||
returnValue: _i3.Future<_i2.Response>.value(
|
||||
_FakeResponse_0(
|
||||
this,
|
||||
Invocation.method(
|
||||
#patch,
|
||||
[url],
|
||||
{#headers: headers, #body: body, #encoding: encoding},
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
as _i3.Future<_i2.Response>);
|
||||
|
||||
@override
|
||||
_i3.Future<_i2.Response> delete(
|
||||
Uri? url, {
|
||||
Map<String, String>? headers,
|
||||
Object? body,
|
||||
_i4.Encoding? encoding,
|
||||
}) =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.method(
|
||||
#delete,
|
||||
[url],
|
||||
{#headers: headers, #body: body, #encoding: encoding},
|
||||
),
|
||||
returnValue: _i3.Future<_i2.Response>.value(
|
||||
_FakeResponse_0(
|
||||
this,
|
||||
Invocation.method(
|
||||
#delete,
|
||||
[url],
|
||||
{#headers: headers, #body: body, #encoding: encoding},
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
as _i3.Future<_i2.Response>);
|
||||
|
||||
@override
|
||||
_i3.Future<String> read(Uri? url, {Map<String, String>? headers}) =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.method(#read, [url], {#headers: headers}),
|
||||
returnValue: _i3.Future<String>.value(
|
||||
_i5.dummyValue<String>(
|
||||
this,
|
||||
Invocation.method(#read, [url], {#headers: headers}),
|
||||
),
|
||||
),
|
||||
)
|
||||
as _i3.Future<String>);
|
||||
|
||||
@override
|
||||
_i3.Future<_i6.Uint8List> readBytes(
|
||||
Uri? url, {
|
||||
Map<String, String>? headers,
|
||||
}) =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.method(#readBytes, [url], {#headers: headers}),
|
||||
returnValue: _i3.Future<_i6.Uint8List>.value(_i6.Uint8List(0)),
|
||||
)
|
||||
as _i3.Future<_i6.Uint8List>);
|
||||
|
||||
@override
|
||||
_i3.Future<_i2.StreamedResponse> send(_i2.BaseRequest? request) =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.method(#send, [request]),
|
||||
returnValue: _i3.Future<_i2.StreamedResponse>.value(
|
||||
_FakeStreamedResponse_1(
|
||||
this,
|
||||
Invocation.method(#send, [request]),
|
||||
),
|
||||
),
|
||||
)
|
||||
as _i3.Future<_i2.StreamedResponse>);
|
||||
|
||||
@override
|
||||
void close() => super.noSuchMethod(
|
||||
Invocation.method(#close, []),
|
||||
returnValueForMissingStub: null,
|
||||
);
|
||||
}
|
||||
|
||||
/// A class which mocks [SecureTokenStorage].
|
||||
///
|
||||
/// See the documentation for Mockito's code generation for more information.
|
||||
class MockSecureTokenStorage extends _i1.Mock implements _i7.SecureTokenStorage {
|
||||
MockSecureTokenStorage() {
|
||||
_i1.throwOnMissingStub(this);
|
||||
}
|
||||
|
||||
@override
|
||||
_i3.Future<void> writeRefreshToken(String? token) =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.method(#writeRefreshToken, [token]),
|
||||
returnValue: _i3.Future<void>.value(),
|
||||
returnValueForMissingStub: _i3.Future<void>.value(),
|
||||
)
|
||||
as _i3.Future<void>);
|
||||
|
||||
@override
|
||||
_i3.Future<String?> readRefreshToken() =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.method(#readRefreshToken, []),
|
||||
returnValue: _i3.Future<String?>.value(),
|
||||
)
|
||||
as _i3.Future<String?>);
|
||||
|
||||
@override
|
||||
_i3.Future<void> deleteRefreshToken() =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.method(#deleteRefreshToken, []),
|
||||
returnValue: _i3.Future<void>.value(),
|
||||
returnValueForMissingStub: _i3.Future<void>.value(),
|
||||
)
|
||||
as _i3.Future<void>);
|
||||
}
|
||||
@@ -440,7 +440,7 @@ void main() {
|
||||
final prefs = PreferenceHelper.asyncPref;
|
||||
await prefs.remove(PREFS_USER);
|
||||
await prefs.setString(PREFS_ACCESS_TOKEN, accessToken);
|
||||
// Far in the future so we don't trip on expiry — refresh isn't wired yet.
|
||||
// Far in the future so we don't trip on expiry, refresh isn't wired yet.
|
||||
await prefs.setInt(
|
||||
PREFS_ACCESS_EXPIRES_AT,
|
||||
DateTime.now().add(const Duration(hours: 1)).millisecondsSinceEpoch,
|
||||
@@ -450,7 +450,7 @@ void main() {
|
||||
}
|
||||
|
||||
test('prefers the headless bundle over PREFS_USER and probes with Bearer', () async {
|
||||
// Both formats present — headless must win.
|
||||
// Both formats present, headless must win.
|
||||
await seedHeadlessBundle(accessToken: 'jwt-access');
|
||||
await PreferenceHelper.asyncPref.setString(
|
||||
PREFS_USER,
|
||||
|
||||
@@ -28,47 +28,47 @@ void main() {
|
||||
const atMin = MIN_SERVER_VERSION;
|
||||
final belowMin = Version(minVersion.major, minVersion.minor - 1, 0).toString();
|
||||
|
||||
test('server version greater than min — no update needed', () {
|
||||
test('server version greater than min, no update needed', () {
|
||||
expect(serverUpdateRequired(aboveMin), false);
|
||||
});
|
||||
|
||||
test('server version equal to min — no update needed', () {
|
||||
test('server version equal to min, no update needed', () {
|
||||
expect(serverUpdateRequired(atMin), false);
|
||||
});
|
||||
|
||||
test('server version less than min — update needed', () {
|
||||
test('server version less than min, update needed', () {
|
||||
expect(serverUpdateRequired(belowMin), true);
|
||||
});
|
||||
|
||||
test('server version with patch component less than min — update needed', () {
|
||||
test('server version with patch component less than min, update needed', () {
|
||||
expect(serverUpdateRequired('$belowMin.9'), true);
|
||||
});
|
||||
|
||||
test('server version with patch component greater than min — no update needed', () {
|
||||
test('server version with patch component greater than min, no update needed', () {
|
||||
expect(serverUpdateRequired('$atMin.1'), false);
|
||||
});
|
||||
|
||||
test('null server version — returns false (lenient, no lockout)', () {
|
||||
test('null server version, returns false (lenient, no lockout)', () {
|
||||
expect(serverUpdateRequired(null), false);
|
||||
});
|
||||
|
||||
test('server version with pre-release suffix — still parsed correctly', () {
|
||||
test('server version with pre-release suffix, still parsed correctly', () {
|
||||
expect(serverUpdateRequired('$aboveMin.0-beta'), false);
|
||||
});
|
||||
|
||||
test('server version with Python alpha suffix (e.g. 1.2.3.0a2) — parsed correctly', () {
|
||||
test('server version with Python alpha suffix (e.g. 1.2.3.0a2), parsed correctly', () {
|
||||
expect(serverUpdateRequired('$aboveMin.0a2'), false);
|
||||
});
|
||||
|
||||
test('server version with Python alpha suffix below min — blocked', () {
|
||||
test('server version with Python alpha suffix below min, blocked', () {
|
||||
expect(serverUpdateRequired('$belowMin.0a2'), true);
|
||||
});
|
||||
|
||||
test('server version with build metadata suffix — still parsed correctly', () {
|
||||
test('server version with build metadata suffix, still parsed correctly', () {
|
||||
expect(serverUpdateRequired('$belowMin.0 (git-abc1234)'), true);
|
||||
});
|
||||
|
||||
test('completely unparseable server version — returns false (lenient)', () {
|
||||
test('completely unparseable server version, returns false (lenient)', () {
|
||||
expect(serverUpdateRequired('unknown'), false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -31,44 +31,54 @@ import 'package:shared_preferences_platform_interface/in_memory_shared_preferenc
|
||||
import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
|
||||
import 'package:wger/l10n/generated/app_localizations.dart';
|
||||
import 'package:wger/providers/auth_notifier.dart';
|
||||
import 'package:wger/providers/secure_token_storage.dart';
|
||||
import 'package:wger/screens/auth_screen.dart';
|
||||
|
||||
import 'auth_screen_test.mocks.dart';
|
||||
|
||||
@GenerateMocks([http.Client])
|
||||
@GenerateMocks([http.Client, SecureTokenStorage])
|
||||
void main() {
|
||||
/// Replacement for SharedPreferences.setMockInitialValues()
|
||||
SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty();
|
||||
|
||||
late MockClient mockClient;
|
||||
late MockSecureTokenStorage mockSecureStorage;
|
||||
|
||||
final Uri tRegistration = Uri(
|
||||
final Uri tHeadlessLogin = Uri(
|
||||
scheme: 'https',
|
||||
host: 'wger.de',
|
||||
path: 'api/v2/register/',
|
||||
path: '/_allauth/app/v1/auth/login',
|
||||
);
|
||||
|
||||
final Uri tLogin = Uri(
|
||||
final Uri tHeadlessSignup = Uri(
|
||||
scheme: 'https',
|
||||
host: 'wger.de',
|
||||
path: 'api/v2/login/',
|
||||
path: '/_allauth/app/v1/auth/signup',
|
||||
);
|
||||
final Uri tProfileCheck = Uri(
|
||||
final Uri tHeadlessRefresh = Uri(
|
||||
scheme: 'https',
|
||||
host: 'wger.de',
|
||||
path: 'api/v2/userprofile/',
|
||||
path: '/_allauth/app/v1/tokens/refresh',
|
||||
);
|
||||
final responseLoginOk = {'token': '1234567890abcdef1234567890abcdef12345678'};
|
||||
|
||||
final responseRegistrationOk = {
|
||||
'message': 'api user successfully registered',
|
||||
'token': '1234567890abcdef1234567890abcdef12345678',
|
||||
const validJwt = 'header.payload.signature';
|
||||
const otherJwt = 'header2.payload2.signature2';
|
||||
|
||||
/// Headless envelope carrying a sham JWT. The signature segment is not
|
||||
/// validated client-side, so any three-dot string works.
|
||||
Map<String, dynamic> headlessAuthOk() => {
|
||||
'status': 200,
|
||||
'data': {},
|
||||
'meta': {
|
||||
'access_token': 'header.payload.signature',
|
||||
'refresh_token': 'refresh-token-${DateTime.now().microsecondsSinceEpoch}',
|
||||
},
|
||||
};
|
||||
|
||||
Widget getWidget() {
|
||||
return ProviderScope(
|
||||
overrides: [
|
||||
authHttpClientProvider.overrideWithValue(mockClient),
|
||||
secureTokenStorageProvider.overrideWithValue(mockSecureStorage),
|
||||
],
|
||||
child: const MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
@@ -81,6 +91,10 @@ void main() {
|
||||
|
||||
setUp(() {
|
||||
mockClient = MockClient();
|
||||
mockSecureStorage = MockSecureTokenStorage();
|
||||
when(mockSecureStorage.deleteRefreshToken()).thenAnswer((_) async {});
|
||||
when(mockSecureStorage.readRefreshToken()).thenAnswer((_) async => null);
|
||||
when(mockSecureStorage.writeRefreshToken(any)).thenAnswer((_) async {});
|
||||
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
PackageInfo.setMockInitialValues(
|
||||
@@ -91,26 +105,27 @@ void main() {
|
||||
buildSignature: 'buildSignature',
|
||||
);
|
||||
|
||||
// Happy-path stubs for the headless login / signup endpoints; tests
|
||||
// that exercise error responses override these as needed.
|
||||
when(
|
||||
mockClient.post(
|
||||
tLogin,
|
||||
tHeadlessLogin,
|
||||
headers: anyNamed('headers'),
|
||||
body: anyNamed('body'),
|
||||
),
|
||||
).thenAnswer((_) => Future(() => Response(json.encode(responseLoginOk), 200)));
|
||||
).thenAnswer((_) => Future(() => Response(json.encode(headlessAuthOk()), 200)));
|
||||
when(
|
||||
mockClient.post(
|
||||
tHeadlessSignup,
|
||||
headers: anyNamed('headers'),
|
||||
body: anyNamed('body'),
|
||||
),
|
||||
).thenAnswer((_) => Future(() => Response(json.encode(headlessAuthOk()), 200)));
|
||||
|
||||
when(mockClient.get(any)).thenAnswer((_) => Future(() => Response('"1.2.3.4"', 200)));
|
||||
when(
|
||||
mockClient.get(any, headers: anyNamed('headers')),
|
||||
).thenAnswer((_) => Future(() => Response('"1.2.3.4"', 200)));
|
||||
|
||||
when(
|
||||
mockClient.post(
|
||||
tRegistration,
|
||||
headers: anyNamed('headers'),
|
||||
body: anyNamed('body'),
|
||||
),
|
||||
).thenAnswer((_) => Future(() => Response(json.encode(responseRegistrationOk), 201)));
|
||||
});
|
||||
|
||||
group('Login mode', () {
|
||||
@@ -133,7 +148,7 @@ void main() {
|
||||
expect(find.byKey(const Key('actionButton')), findsOneWidget);
|
||||
expect(find.byKey(const Key('toggleActionButton')), findsOneWidget);
|
||||
expect(find.byKey(const Key('toggleCustomServerButton')), findsOneWidget);
|
||||
expect(find.byKey(const ValueKey('toggleApiTokenButton')), findsNothing);
|
||||
expect(find.byKey(const ValueKey('toggleRefreshTokenButton')), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('Login - with username & password - happy path', (WidgetTester tester) async {
|
||||
@@ -148,12 +163,12 @@ void main() {
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// Assert
|
||||
expect(find.byKey(const ValueKey('inputApiToken')), findsNothing);
|
||||
expect(find.byKey(const ValueKey('inputRefreshToken')), findsNothing);
|
||||
expect(find.textContaining('An Error Occurred'), findsNothing);
|
||||
verify(mockClient.get(any));
|
||||
verify(
|
||||
mockClient.post(
|
||||
tLogin,
|
||||
tHeadlessLogin,
|
||||
headers: anyNamed('headers'),
|
||||
body: json.encode({'username': 'testuser', 'password': '123456789'}),
|
||||
),
|
||||
@@ -169,7 +184,7 @@ void main() {
|
||||
};
|
||||
when(
|
||||
mockClient.post(
|
||||
tLogin,
|
||||
tHeadlessLogin,
|
||||
headers: anyNamed('headers'),
|
||||
body: anyNamed('body'),
|
||||
),
|
||||
@@ -189,30 +204,41 @@ void main() {
|
||||
expect(find.textContaining('Username or password unknown'), findsOne);
|
||||
verify(
|
||||
mockClient.post(
|
||||
tLogin,
|
||||
tHeadlessLogin,
|
||||
headers: anyNamed('headers'),
|
||||
body: json.encode({'username': 'testuser', 'password': '123456789'}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets('Login - with API token - happy path', (WidgetTester tester) async {
|
||||
// Arrange
|
||||
testWidgets('Login - with refresh token - happy path', (WidgetTester tester) async {
|
||||
// Arrange: stub tokens/refresh to return a rotated bundle.
|
||||
when(
|
||||
mockClient.post(tHeadlessRefresh, headers: anyNamed('headers'), body: anyNamed('body')),
|
||||
).thenAnswer(
|
||||
(_) => Future(
|
||||
() => Response(
|
||||
json.encode({
|
||||
'status': 200,
|
||||
'data': {},
|
||||
'meta': {'access_token': otherJwt, 'refresh_token': 'rotated'},
|
||||
}),
|
||||
200,
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpWidget(getWidget());
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// Act
|
||||
await tester.tap(find.byKey(const ValueKey('toggleCustomServerButton')));
|
||||
await tester.pump();
|
||||
await tester.tap(find.byKey(const ValueKey('toggleApiTokenButton')));
|
||||
await tester.tap(find.byKey(const ValueKey('toggleRefreshTokenButton')));
|
||||
await tester.pump();
|
||||
await tester.enterText(
|
||||
find.byKey(const ValueKey('inputApiToken')),
|
||||
'1234567890abcdef1234567890abcdef12345678',
|
||||
);
|
||||
await tester.enterText(find.byKey(const ValueKey('inputRefreshToken')), validJwt);
|
||||
|
||||
// Assert that API token mode is active before submitting.
|
||||
expect(find.byKey(const ValueKey('inputApiToken')), findsOne);
|
||||
// Assert that refresh-token mode is active before submitting.
|
||||
expect(find.byKey(const ValueKey('inputRefreshToken')), findsOne);
|
||||
expect(find.byKey(const Key('inputUsername')), findsNothing);
|
||||
expect(find.byKey(const Key('inputPassword')), findsNothing);
|
||||
|
||||
@@ -222,48 +248,40 @@ void main() {
|
||||
// Assert
|
||||
expect(find.textContaining('An Error Occurred'), findsNothing);
|
||||
|
||||
verify(
|
||||
mockClient.get(
|
||||
tProfileCheck,
|
||||
headers: argThat(
|
||||
predicate(
|
||||
(headers) =>
|
||||
headers is Map<String, String> &&
|
||||
headers['authorization'] == 'Token 1234567890abcdef1234567890abcdef12345678',
|
||||
),
|
||||
named: 'headers',
|
||||
),
|
||||
),
|
||||
);
|
||||
// The pasted token is sent in the body of tokens/refresh.
|
||||
final captured =
|
||||
verify(
|
||||
mockClient.post(
|
||||
tHeadlessRefresh,
|
||||
headers: anyNamed('headers'),
|
||||
body: captureAnyNamed('body'),
|
||||
),
|
||||
).captured.single
|
||||
as String;
|
||||
expect(json.decode(captured)['refresh_token'], validJwt);
|
||||
// The username/password endpoint must not be hit.
|
||||
verifyNever(
|
||||
mockClient.post(
|
||||
any,
|
||||
headers: anyNamed('headers'),
|
||||
body: anyNamed('body'),
|
||||
),
|
||||
mockClient.post(tHeadlessLogin, headers: anyNamed('headers'), body: anyNamed('body')),
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets('Login - with API token - wrong key', (WidgetTester tester) async {
|
||||
testWidgets('Login - with refresh token - server rejects it', (WidgetTester tester) async {
|
||||
// Arrange
|
||||
final response = {
|
||||
'detail': ['Invalid token'],
|
||||
};
|
||||
when(
|
||||
mockClient.get(tProfileCheck, headers: anyNamed('headers')),
|
||||
).thenAnswer((_) => Future(() => Response(json.encode(response), 400)));
|
||||
mockClient.post(tHeadlessRefresh, headers: anyNamed('headers'), body: anyNamed('body')),
|
||||
).thenAnswer((_) => Future(() => Response(json.encode(response), 401)));
|
||||
await tester.pumpWidget(getWidget());
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// Act
|
||||
await tester.tap(find.byKey(const ValueKey('toggleCustomServerButton')));
|
||||
await tester.pump();
|
||||
await tester.tap(find.byKey(const ValueKey('toggleApiTokenButton')));
|
||||
await tester.tap(find.byKey(const ValueKey('toggleRefreshTokenButton')));
|
||||
await tester.pump();
|
||||
await tester.enterText(
|
||||
find.byKey(const ValueKey('inputApiToken')),
|
||||
'31e2ea0322c07b9df583a9b6d1e794f7139e78d4',
|
||||
);
|
||||
await tester.enterText(find.byKey(const ValueKey('inputRefreshToken')), validJwt);
|
||||
await tester.tap(find.byKey(const Key('actionButton')));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
@@ -271,25 +289,16 @@ void main() {
|
||||
expect(find.textContaining('Detail'), findsOne);
|
||||
expect(find.textContaining('Invalid token'), findsOne);
|
||||
verify(
|
||||
mockClient.get(
|
||||
tProfileCheck,
|
||||
headers: argThat(
|
||||
predicate(
|
||||
(headers) =>
|
||||
headers is Map<String, String> &&
|
||||
headers['authorization'] == 'Token 31e2ea0322c07b9df583a9b6d1e794f7139e78d4',
|
||||
),
|
||||
named: 'headers',
|
||||
),
|
||||
),
|
||||
);
|
||||
verifyNever(
|
||||
mockClient.post(
|
||||
any,
|
||||
tHeadlessRefresh,
|
||||
headers: anyNamed('headers'),
|
||||
body: anyNamed('body'),
|
||||
),
|
||||
);
|
||||
// The username/password endpoint must not be hit.
|
||||
verifyNever(
|
||||
mockClient.post(tHeadlessLogin, headers: anyNamed('headers'), body: anyNamed('body')),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -342,7 +351,7 @@ void main() {
|
||||
expect(find.textContaining('An Error Occurred'), findsNothing);
|
||||
verify(
|
||||
mockClient.post(
|
||||
tRegistration,
|
||||
tHeadlessSignup,
|
||||
headers: anyNamed('headers'),
|
||||
body: json.encode({'username': 'testuser', 'password': '123456789'}),
|
||||
),
|
||||
@@ -363,7 +372,7 @@ void main() {
|
||||
|
||||
when(
|
||||
mockClient.post(
|
||||
tRegistration,
|
||||
tHeadlessSignup,
|
||||
headers: anyNamed('headers'),
|
||||
body: anyNamed('body'),
|
||||
),
|
||||
@@ -386,7 +395,7 @@ void main() {
|
||||
|
||||
verify(
|
||||
mockClient.post(
|
||||
tRegistration,
|
||||
tHeadlessSignup,
|
||||
headers: anyNamed('headers'),
|
||||
body: json.encode({'username': 'testuser', 'password': '123456789'}),
|
||||
),
|
||||
|
||||
@@ -10,6 +10,7 @@ import 'dart:typed_data' as _i6;
|
||||
import 'package:http/http.dart' as _i2;
|
||||
import 'package:mockito/mockito.dart' as _i1;
|
||||
import 'package:mockito/src/dummies.dart' as _i5;
|
||||
import 'package:wger/providers/secure_token_storage.dart' as _i7;
|
||||
|
||||
// ignore_for_file: type=lint
|
||||
// ignore_for_file: avoid_redundant_argument_values
|
||||
@@ -216,3 +217,38 @@ class MockClient extends _i1.Mock implements _i2.Client {
|
||||
returnValueForMissingStub: null,
|
||||
);
|
||||
}
|
||||
|
||||
/// A class which mocks [SecureTokenStorage].
|
||||
///
|
||||
/// See the documentation for Mockito's code generation for more information.
|
||||
class MockSecureTokenStorage extends _i1.Mock implements _i7.SecureTokenStorage {
|
||||
MockSecureTokenStorage() {
|
||||
_i1.throwOnMissingStub(this);
|
||||
}
|
||||
|
||||
@override
|
||||
_i3.Future<void> writeRefreshToken(String? token) =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.method(#writeRefreshToken, [token]),
|
||||
returnValue: _i3.Future<void>.value(),
|
||||
returnValueForMissingStub: _i3.Future<void>.value(),
|
||||
)
|
||||
as _i3.Future<void>);
|
||||
|
||||
@override
|
||||
_i3.Future<String?> readRefreshToken() =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.method(#readRefreshToken, []),
|
||||
returnValue: _i3.Future<String?>.value(),
|
||||
)
|
||||
as _i3.Future<String?>);
|
||||
|
||||
@override
|
||||
_i3.Future<void> deleteRefreshToken() =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.method(#deleteRefreshToken, []),
|
||||
returnValue: _i3.Future<void>.value(),
|
||||
returnValueForMissingStub: _i3.Future<void>.value(),
|
||||
)
|
||||
as _i3.Future<void>);
|
||||
}
|
||||
|
||||
@@ -251,12 +251,12 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations {
|
||||
as String);
|
||||
|
||||
@override
|
||||
String get useApiToken =>
|
||||
String get useRefreshToken =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.getter(#useApiToken),
|
||||
Invocation.getter(#useRefreshToken),
|
||||
returnValue: _i3.dummyValue<String>(
|
||||
this,
|
||||
Invocation.getter(#useApiToken),
|
||||
Invocation.getter(#useRefreshToken),
|
||||
),
|
||||
)
|
||||
as String);
|
||||
@@ -273,34 +273,45 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations {
|
||||
as String);
|
||||
|
||||
@override
|
||||
String get apiToken =>
|
||||
String get refreshToken =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.getter(#apiToken),
|
||||
Invocation.getter(#refreshToken),
|
||||
returnValue: _i3.dummyValue<String>(
|
||||
this,
|
||||
Invocation.getter(#apiToken),
|
||||
Invocation.getter(#refreshToken),
|
||||
),
|
||||
)
|
||||
as String);
|
||||
|
||||
@override
|
||||
String get invalidApiToken =>
|
||||
String get invalidRefreshToken =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.getter(#invalidApiToken),
|
||||
Invocation.getter(#invalidRefreshToken),
|
||||
returnValue: _i3.dummyValue<String>(
|
||||
this,
|
||||
Invocation.getter(#invalidApiToken),
|
||||
Invocation.getter(#invalidRefreshToken),
|
||||
),
|
||||
)
|
||||
as String);
|
||||
|
||||
@override
|
||||
String get apiTokenValidChars =>
|
||||
String get refreshTokenValidChars =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.getter(#apiTokenValidChars),
|
||||
Invocation.getter(#refreshTokenValidChars),
|
||||
returnValue: _i3.dummyValue<String>(
|
||||
this,
|
||||
Invocation.getter(#apiTokenValidChars),
|
||||
Invocation.getter(#refreshTokenValidChars),
|
||||
),
|
||||
)
|
||||
as String);
|
||||
|
||||
@override
|
||||
String get refreshTokenHelperText =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.getter(#refreshTokenHelperText),
|
||||
returnValue: _i3.dummyValue<String>(
|
||||
this,
|
||||
Invocation.getter(#refreshTokenHelperText),
|
||||
),
|
||||
)
|
||||
as String);
|
||||
|
||||
@@ -94,7 +94,7 @@ void main() {
|
||||
});
|
||||
});
|
||||
|
||||
group('variation setters — mutual exclusion', () {
|
||||
group('variation setters, mutual exclusion', () {
|
||||
test('setVariationGroup clears variationConnectToExercise', () {
|
||||
final n = container.read(addExerciseProvider.notifier);
|
||||
n.setVariationConnectToExercise(42);
|
||||
|
||||
@@ -47,7 +47,7 @@ void main() {
|
||||
});
|
||||
});
|
||||
|
||||
group('exerciseApiObject — English-only submission', () {
|
||||
group('exerciseApiObject, English-only submission', () {
|
||||
const state = AddExerciseState(
|
||||
author: 'Alice',
|
||||
exerciseNameEn: 'Bench Press',
|
||||
@@ -86,7 +86,7 @@ void main() {
|
||||
});
|
||||
});
|
||||
|
||||
group('exerciseApiObject — with translation', () {
|
||||
group('exerciseApiObject, with translation', () {
|
||||
const state = AddExerciseState(
|
||||
author: 'Alice',
|
||||
exerciseNameEn: 'Bench Press',
|
||||
|
||||
@@ -104,7 +104,7 @@ void main() {
|
||||
final container = await primedContainer();
|
||||
final state = container.read(exerciseListFiltersProvider);
|
||||
|
||||
// 1-char search term is below the threshold — should return all.
|
||||
// 1-char search term is below the threshold, should return all.
|
||||
container
|
||||
.read(exerciseListFiltersProvider.notifier)
|
||||
.setFilters(state.filters.copyWith(searchTerm: 'D'));
|
||||
|
||||
@@ -26,14 +26,14 @@ import 'package:wger/providers/network_provider.dart';
|
||||
///
|
||||
/// Without this, `NetworkStatus.check()` would do a real `InternetAddress.lookup`
|
||||
/// against `google.com` from every test that touches a provider depending on
|
||||
/// the network state — slow, non-deterministic (CI vs no CI internet), and
|
||||
/// the network state, slow, non-deterministic (CI vs no CI internet), and
|
||||
/// hits an external host from the test runner.
|
||||
///
|
||||
/// The [ConnectivityPlatform.instance] swap follows the officially recommended
|
||||
/// pattern from connectivity_plus' own tests:
|
||||
/// https://github.com/fluttercommunity/plus_plugins/blob/main/packages/connectivity_plus/connectivity_plus/test/connectivity_test.dart
|
||||
///
|
||||
/// Call once per test file (top of `main()` is fine — the static swaps stick
|
||||
/// Call once per test file (top of `main()` is fine, the static swaps stick
|
||||
/// for the entire file).
|
||||
void installFakeConnectivity() {
|
||||
ConnectivityPlatform.instance = _FakeConnectivityPlatform();
|
||||
|
||||
@@ -23,7 +23,7 @@ import 'package:wger/database/powersync/database.dart';
|
||||
/// SQLite instance. The schema is created explicitly because the production
|
||||
/// migration is a no-op (PowerSync owns the schema in production).
|
||||
///
|
||||
/// Each call returns an isolated database — call this in `setUp`, and call
|
||||
/// Each call returns an isolated database, call this in `setUp`, and call
|
||||
/// `db.close()` in `tearDown`.
|
||||
Future<DriftPowersyncDatabase> openTestDatabase() async {
|
||||
final db = DriftPowersyncDatabase(NativeDatabase.memory());
|
||||
|
||||
@@ -259,7 +259,7 @@ void main() {
|
||||
await tester.tap(find.byIcon(Icons.tune));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// Move the slider off the Off position — index 1 is the first grade, A
|
||||
// Move the slider off the Off position, index 1 is the first grade, A
|
||||
final sliderFinder = find.byType(Slider);
|
||||
final Slider slider = tester.widget<Slider>(sliderFinder);
|
||||
slider.onChanged!(1.0);
|
||||
@@ -272,7 +272,7 @@ void main() {
|
||||
await tester.enterText(find.byType(TextFormField), 'Apple');
|
||||
await tester.pump(const Duration(milliseconds: 600));
|
||||
|
||||
// Assert — index 1 maps to NutriScore.a
|
||||
// Assert, index 1 maps to NutriScore.a
|
||||
verify(
|
||||
mockIngredientRepo.searchIngredientServer(
|
||||
'Apple',
|
||||
|
||||
@@ -55,7 +55,7 @@ void main() {
|
||||
when(mockRepo.watchAllDrift()).thenAnswer((_) => Stream.value(plans));
|
||||
final container = makeContainer();
|
||||
// Explicit listener keeps the provider element alive while we wait for
|
||||
// the Drift-stream emission to propagate — in unit tests there is no
|
||||
// the Drift-stream emission to propagate, in unit tests there is no
|
||||
// widget pump that would do this for us.
|
||||
container.listen(nutritionProvider, (_, _) {});
|
||||
await pumpEventQueue();
|
||||
@@ -227,7 +227,7 @@ void main() {
|
||||
final container = makeContainer();
|
||||
final result = await container.read(nutritionProvider.notifier).addPlan(toAdd);
|
||||
|
||||
// Notifier no longer mints — the repository (Drift's clientDefault)
|
||||
// Notifier no longer mints, the repository (Drift's clientDefault)
|
||||
// does, on insert. The mock doesn't run that, so id stays null here.
|
||||
expect(identical(result, toAdd), isTrue);
|
||||
verify(mockRepo.addPlanLocalDrift(toAdd)).called(1);
|
||||
|
||||
@@ -163,7 +163,7 @@ void main() {
|
||||
const planUuid2 = 'cc000000-0000-4000-8000-000000000002';
|
||||
const planUuid3 = 'cc000000-0000-4000-8000-000000000003';
|
||||
|
||||
group('Plans — Drift', () {
|
||||
group('Plans, Drift', () {
|
||||
test('watchAllDrift emits an empty list when no plans exist', () async {
|
||||
expect(await repo.watchAllDrift().first, isEmpty);
|
||||
});
|
||||
@@ -374,7 +374,7 @@ void main() {
|
||||
});
|
||||
});
|
||||
|
||||
group('Meals — watchAllMealsHydrated', () {
|
||||
group('Meals, watchAllMealsHydrated', () {
|
||||
const mealUuid1 = 'aa000000-0000-4000-8000-000000000001';
|
||||
const mealUuid2 = 'aa000000-0000-4000-8000-000000000002';
|
||||
const itemUuid1 = 'bb000000-0000-4000-8000-000000000001';
|
||||
|
||||
@@ -55,7 +55,7 @@ void main() {
|
||||
when(mockRepo.addMealLocalDrift(any)).thenAnswer((_) async => Future.value());
|
||||
when(mockRepo.editMealLocalDrift(any)).thenAnswer((_) async => Future.value());
|
||||
// NutritionNotifier.build() subscribes to three Drift streams (plans,
|
||||
// meals, diary entries) — emit the seed plan and empty meals/diary so the
|
||||
// meals, diary entries), emit the seed plan and empty meals/diary so the
|
||||
// combined stream produces a value.
|
||||
when(mockRepo.watchAllDrift()).thenAnswer((_) => Stream.value([plan1]));
|
||||
when(mockRepo.watchAllMealsHydrated()).thenAnswer((_) => Stream.value(plan1.meals));
|
||||
|
||||
@@ -137,7 +137,7 @@ void main() {
|
||||
// separate stub is needed.
|
||||
when(mockIngredientRepo.getById(any)).thenAnswer((_) async => ingredient);
|
||||
// NutritionNotifier.build() subscribes to three Drift streams (plans,
|
||||
// meals, diary entries) — emit the seed plan and meals so the combined
|
||||
// meals, diary entries), emit the seed plan and meals so the combined
|
||||
// stream produces a value.
|
||||
when(mockRepo.watchAllDrift()).thenAnswer((_) => Stream.value([plan1]));
|
||||
when(mockRepo.watchAllMealsHydrated()).thenAnswer((_) => Stream.value(plan1.meals));
|
||||
|
||||
@@ -78,7 +78,7 @@ void main() {
|
||||
mockNutritionRepo.watchAllLogsHydrated(),
|
||||
).thenAnswer((_) => Stream.value(getTestNutritionLogs()));
|
||||
|
||||
// Ingredient lookups now go through PowerSync — stub the local repo.
|
||||
// Ingredient lookups now go through PowerSync, stub the local repo.
|
||||
when(mockIngredientRepo.getById(any)).thenAnswer((_) async => fetchedIngredient);
|
||||
when(mockIngredientRepo.watchById(any)).thenAnswer((_) => Stream.value(fetchedIngredient));
|
||||
});
|
||||
|
||||
@@ -130,7 +130,7 @@ void main() {
|
||||
// Confirmation dialog
|
||||
expect(find.byType(AlertDialog), findsOneWidget);
|
||||
|
||||
// Confirm tap — actual delete now goes through Drift + PowerSync (not
|
||||
// Confirm tap, actual delete now goes through Drift + PowerSync (not
|
||||
// REST), so we don't assert on the REST mock here.
|
||||
await tester.tap(find.text('Delete'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
@@ -124,7 +124,7 @@ void main() {
|
||||
test('does not touch DateTimeField columns even on registered tables', () {
|
||||
// `manager_workoutlog.date` is a DateTimeField on Django (not a
|
||||
// DateField), and `manager_workoutlog` isn't in the date-only
|
||||
// registry — the timestamp must round-trip unchanged.
|
||||
// registry, the timestamp must round-trip unchanged.
|
||||
final out = connector.genericTransform(
|
||||
'manager_workoutlog',
|
||||
{'date': '2024-11-01T17:30:00.000Z'},
|
||||
|
||||
@@ -103,7 +103,7 @@ void main() {
|
||||
});
|
||||
|
||||
test('does not prepend the server URL for absolute URLs on different hosts', () {
|
||||
// Useful when the REST API has already absolutised the URL — we must
|
||||
// Useful when the REST API has already absolutised the URL, we must
|
||||
// not double-prefix with the local server.
|
||||
final result = mediaUri('https://wger.de', 'https://other.example.com/x.jpg');
|
||||
expect(result?.host, 'other.example.com');
|
||||
|
||||
@@ -148,7 +148,7 @@ void main() {
|
||||
when(mockPrefs.setString(any, any)).thenAnswer((_) async {});
|
||||
when(mockPrefs.remove(any)).thenAnswer((_) async {});
|
||||
when(mockBase.serverUrl).thenReturn('https://example');
|
||||
// Default fetch — empty response so the auto-probe in build is
|
||||
// Default fetch, empty response so the auto-probe in build is
|
||||
// a harmless no-op for tests that don't care about it.
|
||||
stubFetch(responseBody: {'results': []});
|
||||
});
|
||||
@@ -186,7 +186,7 @@ void main() {
|
||||
|
||||
final container = makeContainer();
|
||||
// build() triggers an auto-probe in the background. We also
|
||||
// drive the notifier explicitly for ordering — both calls are
|
||||
// drive the notifier explicitly for ordering, both calls are
|
||||
// idempotent. Verify uses no .called() so we accept either one
|
||||
// or two invocations.
|
||||
await container.read(mediaUrlPrefixProvider.future);
|
||||
|
||||
@@ -68,7 +68,7 @@ void main() {
|
||||
expect(state.exerciseId, source.exerciseId);
|
||||
expect(state.weight, source.weight);
|
||||
expect(state.date, fixed);
|
||||
// setLog must clear the id — the source log is a template, the new
|
||||
// setLog must clear the id, the source log is a template, the new
|
||||
// state is a separate entry that will get its own UUID from Drift on
|
||||
// insert.
|
||||
expect(state.id, isNull);
|
||||
|
||||
@@ -74,7 +74,7 @@ void main() {
|
||||
mockExerciseRepo.watchAllDrift(),
|
||||
).thenAnswer((_) => Stream.value(ExerciseState(testExercises)));
|
||||
|
||||
// Drift the test routine in via the routines repository — the real
|
||||
// Drift the test routine in via the routines repository, the real
|
||||
// [RoutinesRiverpod] picks it up and exposes it through state.
|
||||
when(
|
||||
mockRoutinesRepo.watchAllDrift(),
|
||||
@@ -95,7 +95,7 @@ void main() {
|
||||
exerciseRepositoryProvider.overrideWithValue(mockExerciseRepo),
|
||||
workoutSessionRepositoryProvider.overrideWithValue(mockSessionRepo),
|
||||
// The repetition + weight unit catalogues are tiny direct-Drift
|
||||
// stream providers — overriding them inline is the established
|
||||
// stream providers, overriding them inline is the established
|
||||
// pattern (see also [exerciseCategoriesProvider] etc.).
|
||||
routineRepetitionUnitProvider.overrideWith(
|
||||
(ref) => Stream<List<RepetitionUnit>>.value(testRepetitionUnits),
|
||||
@@ -174,8 +174,8 @@ void main() {
|
||||
expect(find.byIcon(Icons.chevron_left), findsOneWidget);
|
||||
expect(find.byIcon(Icons.chevron_right), findsOneWidget);
|
||||
|
||||
// The form shows reps and weight — each with its own unit
|
||||
// picker (PopupMenuButton<int>) — plus the RiR slider, all at
|
||||
// The form shows reps and weight, each with its own unit
|
||||
// picker (PopupMenuButton<int>), plus the RiR slider, all at
|
||||
// once. Scope the popup-menu lookup to the LogPage so other
|
||||
// popup menus elsewhere in the app shell don't interfere.
|
||||
expect(find.byType(TextFormField), findsNWidgets(2));
|
||||
@@ -187,7 +187,7 @@ void main() {
|
||||
findsNWidgets(2),
|
||||
);
|
||||
expect(find.byType(RiRInputWidget), findsOneWidget);
|
||||
// Advance to the next page via the chevron — the RiR slider
|
||||
// Advance to the next page via the chevron, the RiR slider
|
||||
// would otherwise eat a horizontal-drag gesture started over
|
||||
// its track.
|
||||
await tester.tap(find.byIcon(Icons.chevron_right));
|
||||
|
||||
@@ -41,7 +41,7 @@ export 'routine_form_test_overrides.mocks.dart'
|
||||
/// without this stub.
|
||||
///
|
||||
/// When [exercise] / [session] are passed in by the caller they are used
|
||||
/// as-is — the caller owns the stubbing. Only the locally-created fallback
|
||||
/// as-is, the caller owns the stubbing. Only the locally-created fallback
|
||||
/// mocks get a default empty-stream stub here.
|
||||
List<Override> exerciseAndSessionRepoOverrides({
|
||||
MockExerciseRepository? exercise,
|
||||
@@ -73,7 +73,7 @@ MockWorkoutSessionRepository _emptySessionRepoMock() {
|
||||
/// Use this in widget tests that don't override the reference-data streams
|
||||
/// themselves; otherwise mix in [exerciseAndSessionRepoOverrides] alone.
|
||||
///
|
||||
/// [repetitionUnits] / [weightUnits] default to empty lists — sufficient for
|
||||
/// [repetitionUnits] / [weightUnits] default to empty lists, sufficient for
|
||||
/// most form widget tests where the units only need to satisfy the
|
||||
/// `awaitFirstValue` step. Pass real fixtures when the test exercises
|
||||
/// hydration logic that looks units up by id.
|
||||
|
||||
@@ -145,7 +145,7 @@ void main() {
|
||||
//
|
||||
// When the user taps "+" in gym mode to add an extra exercise,
|
||||
// addExerciseAfterPage() creates a SetConfigData with only exerciseId and
|
||||
// slotEntryId — no unit objects. The default constructor sets
|
||||
// slotEntryId, no unit objects. The default constructor sets
|
||||
// weightUnitId=WEIGHT_UNIT_KG and repetitionsUnitId=REP_UNIT_REPETITIONS_ID,
|
||||
// but Log.fromSetConfigData was using the object setters which overwrite
|
||||
// those IDs with null when the objects are null, causing the server to
|
||||
@@ -154,7 +154,7 @@ void main() {
|
||||
exerciseId: 1,
|
||||
slotEntryId: 1,
|
||||
exercise: exercise,
|
||||
// no weightUnit or repetitionsUnit objects — mirrors addExerciseAfterPage()
|
||||
// no weightUnit or repetitionsUnit objects, mirrors addExerciseAfterPage()
|
||||
);
|
||||
|
||||
final log = Log.fromSetConfigData(setConfig);
|
||||
|
||||
@@ -33,7 +33,7 @@ import 'routines_provider_repository_test.mocks.dart';
|
||||
void main() {
|
||||
final mockBaseProvider = MockWgerBaseProvider();
|
||||
// The repository now takes a Drift database in its constructor, but
|
||||
// none of the REST methods exercised in this file touch it — a plain
|
||||
// none of the REST methods exercised in this file touch it, a plain
|
||||
// mock instance is enough.
|
||||
final mockDb = MockDriftPowersyncDatabase();
|
||||
|
||||
|
||||
@@ -51,7 +51,7 @@ void main() {
|
||||
mockRepo = MockRoutinesRepository();
|
||||
when(mockRepo.watchAllDrift()).thenAnswer((_) => Stream.value(const <Routine>[]));
|
||||
// Mock repos for the two reference-data notifiers `fetchAndSetRoutineFull`
|
||||
// awaits — kept locally so individual tests can re-stub them with
|
||||
// awaits, kept locally so individual tests can re-stub them with
|
||||
// specific session/exercise data.
|
||||
mockSessionRepo = MockWorkoutSessionRepository();
|
||||
when(
|
||||
@@ -178,7 +178,7 @@ void main() {
|
||||
verify(mockRepo.editDayServer(day1)).called(1);
|
||||
verify(mockRepo.editDayServer(day2)).called(1);
|
||||
// dayData/dayDataGym are server-computed, so we must refresh once after
|
||||
// the batch — not once per edit.
|
||||
// the batch, not once per edit.
|
||||
verify(mockRepo.fetchAndSetRoutineFullServer(101)).called(1);
|
||||
});
|
||||
|
||||
|
||||
@@ -73,7 +73,7 @@ void main() {
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
group('Routines — Drift', () {
|
||||
group('Routines, Drift', () {
|
||||
test('watchAllDrift emits an empty list when no routines exist', () async {
|
||||
expect(await repo.watchAllDrift().first, isEmpty);
|
||||
});
|
||||
@@ -155,7 +155,7 @@ void main() {
|
||||
// else lives here.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
group('Days — REST', () {
|
||||
group('Days, REST', () {
|
||||
test('addDayServer POSTs to /day/ and returns the created Day', () async {
|
||||
final dayUri = Uri.https('localhost', 'api/v2/day/');
|
||||
when(mockBase.makeUrl('day')).thenReturn(dayUri);
|
||||
@@ -200,7 +200,7 @@ void main() {
|
||||
});
|
||||
});
|
||||
|
||||
group('Slots — REST', () {
|
||||
group('Slots, REST', () {
|
||||
test('addSlotServer POSTs to /slot/ and returns the created Slot', () async {
|
||||
final uri = Uri.https('localhost', 'api/v2/slot/');
|
||||
when(mockBase.makeUrl('slot')).thenReturn(uri);
|
||||
@@ -232,7 +232,7 @@ void main() {
|
||||
});
|
||||
});
|
||||
|
||||
group('Slot entries — REST', () {
|
||||
group('Slot entries, REST', () {
|
||||
SlotEntry makeEntry({int? id, int slotId = 1}) {
|
||||
// `config` is `late Object?` and required for toJson to work.
|
||||
return SlotEntry(
|
||||
@@ -292,7 +292,7 @@ void main() {
|
||||
});
|
||||
});
|
||||
|
||||
group('Configs — REST', () {
|
||||
group('Configs, REST', () {
|
||||
Map<String, dynamic> configResponse(int id, num value) => {
|
||||
'id': id,
|
||||
'iteration': 1,
|
||||
|
||||
@@ -108,7 +108,7 @@ void main() {
|
||||
// Confirmation dialog
|
||||
expect(find.byType(AlertDialog), findsOneWidget);
|
||||
|
||||
// Confirm tap — note: the actual delete now goes through Drift +
|
||||
// Confirm tap, note: the actual delete now goes through Drift +
|
||||
// PowerSync (not REST), so we don't verify a repository call here.
|
||||
// The UI flow up to dispatch is what's covered.
|
||||
await tester.tap(find.text('Delete'));
|
||||
|
||||
@@ -58,7 +58,7 @@ void main() {
|
||||
Future<List<dynamic>> readLogs() => db.select(db.workoutLogTable).get();
|
||||
Future<List<dynamic>> readSessions() => db.select(db.workoutSessionTable).get();
|
||||
|
||||
group('addLocalDrift — log already has a sessionId', () {
|
||||
group('addLocalDrift, log already has a sessionId', () {
|
||||
test('inserts the log without touching the session table', () async {
|
||||
final log = makeLog(sessionId: 'existing-session');
|
||||
|
||||
@@ -71,7 +71,7 @@ void main() {
|
||||
});
|
||||
});
|
||||
|
||||
group('addLocalDrift — log without sessionId', () {
|
||||
group('addLocalDrift, log without sessionId', () {
|
||||
test('reuses an existing session for the same routine and day', () async {
|
||||
final existingSession = WorkoutSession(
|
||||
id: 'existing-session-1',
|
||||
|
||||
@@ -70,7 +70,7 @@ void main() {
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
locale: const Locale('en'),
|
||||
// logout buttons in the recovery screens navigate to '/' after
|
||||
// calling the notifier — register both the entry route and a
|
||||
// calling the notifier, register both the entry route and a
|
||||
// stub for '/' so the navigation succeeds in tests. We can't
|
||||
// use `home` here since that conflicts with a routes['/'] entry.
|
||||
initialRoute: '/test',
|
||||
|
||||
@@ -128,7 +128,7 @@ void main() {
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// The body is wrapped in a ConstrainedBox(maxHeight: 280). Pull it out
|
||||
// of the tree and assert the cap is in place — this is what stops the
|
||||
// of the tree and assert the cap is in place, this is what stops the
|
||||
// dashboard cards from growing unbounded.
|
||||
final constrained = tester
|
||||
.widgetList<ConstrainedBox>(find.byType(ConstrainedBox))
|
||||
|
||||
Reference in New Issue
Block a user