From e105e59cbeb7cd1ff9e85c39aec750ba8c09c191 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Thu, 3 Dec 2026 21:11:54 +0100 Subject: [PATCH] Read the time through clock --- lib/core/formatting/formatting.dart | 3 +- lib/core/network/auth_credential.dart | 3 +- lib/core/network/jwt.dart | 3 +- lib/core/widgets/about.dart | 3 +- lib/core/widgets/dashboard/calendar.dart | 7 ++- .../widgets/dashboard/widgets/routines.dart | 3 +- lib/core/widgets/datetime_input.dart | 7 ++- test/core/network/auth_credential_test.dart | 55 +++++++++++++++++++ test/core/network/jwt_test.dart | 11 +++- .../core/widgets/dashboard/calendar_test.dart | 28 ++++++++++ .../dashboard/widgets/routines_test.dart | 15 +++++ 11 files changed, 124 insertions(+), 14 deletions(-) create mode 100644 test/core/network/auth_credential_test.dart diff --git a/lib/core/formatting/formatting.dart b/lib/core/formatting/formatting.dart index a4bb6bd3a..6a33a6ce2 100644 --- a/lib/core/formatting/formatting.dart +++ b/lib/core/formatting/formatting.dart @@ -18,6 +18,7 @@ import 'dart:math'; +import 'package:clock/clock.dart'; import 'package:flutter/widgets.dart'; import 'package:intl/intl.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; @@ -48,7 +49,7 @@ String weightUnit(bool isMetric, BuildContext context) { /// it (react has them from Intl) would be four more strings to translate for /// a case nobody is looking at. String relativeDate(BuildContext context, DateTime date, {DateTime? now}) { - final today = now ?? DateTime.now(); + final today = now ?? clock.now(); // Calendar arithmetic in UTC, so a DST day is not 23 or 25 hours long final elapsed = DateTime.utc( today.year, diff --git a/lib/core/network/auth_credential.dart b/lib/core/network/auth_credential.dart index b667adb4b..cd8c3b766 100644 --- a/lib/core/network/auth_credential.dart +++ b/lib/core/network/auth_credential.dart @@ -16,6 +16,7 @@ * along with this program. If not, see . */ +import 'package:clock/clock.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:wger/core/network/jwt.dart'; @@ -43,7 +44,7 @@ abstract class JwtCredential with _$JwtCredential { /// True when the expiry falls within [leeway] of now, or is already past. /// False when the token carries no expiry at all. bool needsRefresh(Duration leeway) => - expiresAt != null && expiresAt!.isBefore(DateTime.now().toUtc().add(leeway)); + expiresAt != null && expiresAt!.isBefore(clock.now().toUtc().add(leeway)); /// User identifier carried by the token: its `sub` claim. Decoded on /// every call, so callers should not hammer it in tight loops. Null when diff --git a/lib/core/network/jwt.dart b/lib/core/network/jwt.dart index 58b6db351..a84e98352 100644 --- a/lib/core/network/jwt.dart +++ b/lib/core/network/jwt.dart @@ -18,6 +18,7 @@ import 'dart:convert'; +import 'package:clock/clock.dart'; import 'package:logging/logging.dart'; final _logger = Logger('jwt'); @@ -68,5 +69,5 @@ DateTime? jwtExpOnLocalClock(Map? payload) { if (iat is! num || exp is! num) { return jwtExp(payload); } - return DateTime.now().toUtc().add(Duration(seconds: (exp - iat).toInt())); + return clock.now().toUtc().add(Duration(seconds: (exp - iat).toInt())); } diff --git a/lib/core/widgets/about.dart b/lib/core/widgets/about.dart index f0ce6c871..9ffd739d4 100644 --- a/lib/core/widgets/about.dart +++ b/lib/core/widgets/about.dart @@ -18,6 +18,7 @@ import 'dart:io'; +import 'package:clock/clock.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:material_ui/material_ui.dart'; @@ -58,7 +59,7 @@ class AboutPage extends ConsumerWidget { final authState = ref.watch(authProvider).value; final isOnline = ref.watch(networkStatusProvider); final i18n = AppLocalizations.of(context); - final today = DateTime.now(); + final today = clock.now(); // The terms are the server operator's, not ours, so point at the instance // the user is actually connected to diff --git a/lib/core/widgets/dashboard/calendar.dart b/lib/core/widgets/dashboard/calendar.dart index 4a0a97589..e5e1de718 100644 --- a/lib/core/widgets/dashboard/calendar.dart +++ b/lib/core/widgets/dashboard/calendar.dart @@ -16,6 +16,7 @@ * along with this program. If not, see . */ +import 'package:clock/clock.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart' as riverpod; import 'package:material_ui/material_ui.dart'; import 'package:table_calendar/table_calendar.dart'; @@ -67,7 +68,7 @@ class DashboardCalendarWidget extends riverpod.ConsumerStatefulWidget { class _DashboardCalendarWidgetState extends riverpod.ConsumerState with TickerProviderStateMixin { RangeSelectionMode _rangeSelectionMode = RangeSelectionMode.toggledOff; - DateTime _focusedDay = DateTime.now(); + DateTime _focusedDay = clock.now(); DateTime? _selectedDay; DateTime? _rangeStart; DateTime? _rangeEnd; @@ -245,8 +246,8 @@ class _DashboardCalendarWidgetState extends riverpod.ConsumerState( locale: Localizations.localeOf(context).languageCode, - firstDay: DateTime.now().subtract(const Duration(days: 1000)), - lastDay: DateTime.now().add(const Duration(days: 365)), + firstDay: clock.now().subtract(const Duration(days: 1000)), + lastDay: clock.now().add(const Duration(days: 365)), focusedDay: _focusedDay, selectedDayPredicate: (day) => isSameDay(_selectedDay, day), rangeStartDay: _rangeStart, diff --git a/lib/core/widgets/dashboard/widgets/routines.dart b/lib/core/widgets/dashboard/widgets/routines.dart index b7b2856b0..977764460 100644 --- a/lib/core/widgets/dashboard/widgets/routines.dart +++ b/lib/core/widgets/dashboard/widgets/routines.dart @@ -16,6 +16,7 @@ * along with this program. If not, see . */ +import 'package:clock/clock.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:material_ui/material_ui.dart'; import 'package:wger/core/date.dart'; @@ -224,7 +225,7 @@ class DetailContentWidget extends StatelessWidget { width: double.infinity, child: Row( children: [ - if (dayData.date.isSameDayAs(DateTime.now())) const Icon(Icons.today), + if (dayData.date.isSameDayAs(clock.now())) const Icon(Icons.today), Expanded( child: Text( dayData.day == null || dayData.day!.isRest diff --git a/lib/core/widgets/datetime_input.dart b/lib/core/widgets/datetime_input.dart index bf3df1463..93f7b0b35 100644 --- a/lib/core/widgets/datetime_input.dart +++ b/lib/core/widgets/datetime_input.dart @@ -16,6 +16,7 @@ * along with this program. If not, see . */ +import 'package:clock/clock.dart'; import 'package:material_ui/material_ui.dart'; import 'package:wger/core/formatting/formatting.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; @@ -210,7 +211,7 @@ class _DateInputWidgetState extends State { final picked = await showDatePicker( context: context, - initialDate: _value ?? DateTime.now(), + initialDate: _value ?? clock.now(), firstDate: widget.firstDate ?? DateTime(2000), lastDate: widget.lastDate ?? DateTime(2100), ); @@ -274,8 +275,8 @@ class _DateTimeInputWidgetState extends State { DateInputWidget( value: _value, labelText: i18n.date, - firstDate: widget.firstDate ?? DateTime(DateTime.now().year - 10), - lastDate: widget.lastDate ?? DateTime.now(), + firstDate: widget.firstDate ?? DateTime(clock.now().year - 10), + lastDate: widget.lastDate ?? clock.now(), onChanged: (date) => _report( _value.copyWith(year: date.year, month: date.month, day: date.day), ), diff --git a/test/core/network/auth_credential_test.dart b/test/core/network/auth_credential_test.dart new file mode 100644 index 000000000..4e4cf09f6 --- /dev/null +++ b/test/core/network/auth_credential_test.dart @@ -0,0 +1,55 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 - 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 . + */ + +import 'package:clock/clock.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:wger/core/network/auth_credential.dart'; + +void main() { + group('JwtCredential.needsRefresh', () { + final now = DateTime.utc(2026, 3, 7, 18, 30); + const leeway = Duration(minutes: 1); + + bool needsRefresh(DateTime? expiresAt) => withClock( + Clock.fixed(now), + () => JwtCredential(accessToken: 'token', expiresAt: expiresAt).needsRefresh(leeway), + ); + + test('a token valid beyond the leeway is kept', () { + expect(needsRefresh(now.add(const Duration(minutes: 2))), isFalse); + }); + + test('a token expiring within the leeway is refreshed ahead of time', () { + expect(needsRefresh(now.add(const Duration(seconds: 30))), isTrue); + }); + + test('an expired token is refreshed', () { + expect(needsRefresh(now.subtract(const Duration(seconds: 1))), isTrue); + }); + + test('a local expiry compares as the same instant', () { + // expiresAt may come back from storage in the local zone + expect(needsRefresh(now.add(const Duration(minutes: 2)).toLocal()), isFalse); + expect(needsRefresh(now.add(const Duration(seconds: 30)).toLocal()), isTrue); + }); + + test('a token without expiry is never refreshed', () { + expect(needsRefresh(null), isFalse); + }); + }); +} diff --git a/test/core/network/jwt_test.dart b/test/core/network/jwt_test.dart index a84c42bb1..66154136e 100644 --- a/test/core/network/jwt_test.dart +++ b/test/core/network/jwt_test.dart @@ -18,6 +18,7 @@ import 'dart:convert'; +import 'package:clock/clock.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:wger/core/network/jwt.dart'; @@ -80,10 +81,14 @@ void main() { group('jwtExpOnLocalClock', () { test('anchors the token lifetime to the local clock', () { // iat/exp lie far in the past; only their 600 s difference may matter. - final result = jwtExpOnLocalClock({'iat': 1700000000, 'exp': 1700000600}); + final now = DateTime.utc(2026, 3, 7, 18, 30); + final result = withClock( + Clock.fixed(now), + () => jwtExpOnLocalClock({'iat': 1700000000, 'exp': 1700000600}), + ); - final expected = DateTime.now().toUtc().add(const Duration(seconds: 600)); - expect(result!.difference(expected).abs(), lessThan(const Duration(seconds: 5))); + expect(result, DateTime.utc(2026, 3, 7, 18, 40)); + expect(result!.isUtc, isTrue); }); test('falls back to the absolute exp when iat is missing', () { diff --git a/test/core/widgets/dashboard/calendar_test.dart b/test/core/widgets/dashboard/calendar_test.dart index 87f990561..706fc5fee 100644 --- a/test/core/widgets/dashboard/calendar_test.dart +++ b/test/core/widgets/dashboard/calendar_test.dart @@ -16,6 +16,7 @@ * along with this program. If not, see . */ +import 'package:clock/clock.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:material_ui/material_ui.dart'; import 'package:timezone/data/latest_all.dart' as tzdata; @@ -273,4 +274,31 @@ void main() { expect(find.text('81 kg'), findsOneWidget); expect(find.text('80 kg'), findsNothing); }); + + testWidgets('a selected range lists the events of every day in it', (tester) async { + // A fixed day mid-month, so the whole range is on the first page + await withClock(Clock.fixed(DateTime(2026, 3, 10, 12)), () async { + DateTime day(int d) => DateTime(2026, 3, d); + await tester.pumpWidget( + renderWidget( + categories: [bodyWeight], + dailyBuckets: { + bodyWeight.id!: [bucket(day(9), 79), bucket(day(11), 81), bucket(day(12), 82)], + }, + ), + ); + await tester.pumpAndSettle(); + + // A long press starts the range, a tap ends it + await tester.longPress(find.text('9').first); + await tester.pumpAndSettle(); + await tester.tap(find.text('11').first); + await tester.pumpAndSettle(); + + expect(find.text('79 kg'), findsOneWidget); + expect(find.text('81 kg'), findsOneWidget); + // The day after the range + expect(find.text('82 kg'), findsNothing); + }); + }); } diff --git a/test/core/widgets/dashboard/widgets/routines_test.dart b/test/core/widgets/dashboard/widgets/routines_test.dart index de087f582..20db30dcf 100644 --- a/test/core/widgets/dashboard/widgets/routines_test.dart +++ b/test/core/widgets/dashboard/widgets/routines_test.dart @@ -18,6 +18,7 @@ import 'dart:async'; +import 'package:clock/clock.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/misc.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -161,6 +162,20 @@ void main() { expect(find.byIcon(Icons.info), findsOneWidget); }); + testWidgets('marks the day that is today', (tester) async { + // The second day of the test routine is on 2024-11-02 + await withClock(Clock.fixed(DateTime(2024, 11, 2, 9)), () async { + await pumpCard(tester, () => _StubRoutinesRiverpod([getTestRoutine()])); + + final secondDay = find.ancestor(of: find.text('second day'), matching: find.byType(Row)); + expect(find.byIcon(Icons.today), findsOneWidget); + expect( + find.descendant(of: secondDay.first, matching: find.byIcon(Icons.today)), + findsOneWidget, + ); + }); + }); + testWidgets('the detail page opens for the shown routine', (tester) async { await pumpCard(tester, () => _StubRoutinesRiverpod([getTestRoutine()]));