From 8850f2d847cdc42d31808f6553f70d99ce663dfc Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Thu, 3 Dec 2026 19:17:09 +0100 Subject: [PATCH] Anchor the measurement tests on fixed days instead of the clock --- lib/features/measurements/charts/data.dart | 5 +- .../widgets/charts/heatmap_chart.dart | 5 +- .../widgets/charts/spark_charts.dart | 3 +- .../measurements/widgets/entries.dart | 3 +- .../measurements/widgets/forms/entry.dart | 3 +- .../widgets/forms/group_entry.dart | 3 +- .../widgets/measurement_tile.dart | 9 +- .../measurements/widgets/weight_form.dart | 3 +- .../measurements/charts/range_test.dart | 12 +- .../providers/measurement_notifier_test.dart | 2 +- .../measurement_repository_test.dart | 2 +- .../measurement_entries_screen_test.dart | 37 +++--- .../widgets/categories_card_test.dart | 26 +---- .../widgets/charts/heatmap_chart_test.dart | 48 ++++---- .../measurements/widgets/entries_test.dart | 107 +++++++----------- .../measurements/widgets/helpers_test.dart | 52 +-------- .../widgets/measurement_tile_test.dart | 23 +--- test_data/body_weight.dart | 6 +- test_data/measurements.dart | 68 ++++++++++- 19 files changed, 186 insertions(+), 231 deletions(-) diff --git a/lib/features/measurements/charts/data.dart b/lib/features/measurements/charts/data.dart index c92a11108..661251669 100644 --- a/lib/features/measurements/charts/data.dart +++ b/lib/features/measurements/charts/data.dart @@ -18,6 +18,7 @@ import 'dart:math'; +import 'package:clock/clock.dart'; import 'package:collection/collection.dart'; import 'package:material_ui/material_ui.dart'; import 'package:wger/features/measurements/charts/calendar.dart'; @@ -165,7 +166,7 @@ List weeklyDeltas( }) { final byWeek = groupBy(vals, (MeasurementChartEntry e) => weekStart(e.date)); if (summed) { - byWeek.remove(weekStart(today ?? DateTime.now())); + byWeek.remove(weekStart(today ?? clock.now())); } final weeks = byWeek.keys.toList()..sort(); @@ -652,7 +653,7 @@ MeasurementHeatmapGrid buildHeatmapGrid( DateTime? today, }) { final values = {for (final day in days) dayOf(day.date): day.value}; - final now = dayOf(today ?? DateTime.now()); + final now = dayOf(today ?? clock.now()); if (values.isEmpty) { return MeasurementHeatmapGrid( diff --git a/lib/features/measurements/widgets/charts/heatmap_chart.dart b/lib/features/measurements/widgets/charts/heatmap_chart.dart index c96c27a46..c6083421c 100644 --- a/lib/features/measurements/widgets/charts/heatmap_chart.dart +++ b/lib/features/measurements/widgets/charts/heatmap_chart.dart @@ -18,6 +18,7 @@ import 'dart:math'; +import 'package:clock/clock.dart'; import 'package:intl/intl.dart'; import 'package:material_ui/material_ui.dart'; import 'package:wger/core/formatting/formatting.dart'; @@ -109,7 +110,7 @@ class _MeasurementHeatmapWidgetFlState extends State if (selected == null) { // The grid is whole weeks and its last one usually runs past today, so // the span it covers ends today rather than on that Sunday - final today = DateTime.now(); + final today = clock.now(); final last = grid.dayAt(grid.weeks - 1, DateTime.daysPerWeek - 1); final end = last.isAfter(today) ? today : last; return '${dateFormat.format(grid.start)} - ${dateFormat.format(end)}'; @@ -212,7 +213,7 @@ class _HeatmapPainter extends CustomPainter { @override void paint(Canvas canvas, Size size) { final paint = Paint()..style = PaintingStyle.fill; - final today = DateTime.now(); + final today = clock.now(); final endOfToday = DateTime(today.year, today.month, today.day); for (var week = 0; week < grid.weeks; week++) { diff --git a/lib/features/measurements/widgets/charts/spark_charts.dart b/lib/features/measurements/widgets/charts/spark_charts.dart index 44ae0f8d4..ea6cf552e 100644 --- a/lib/features/measurements/widgets/charts/spark_charts.dart +++ b/lib/features/measurements/widgets/charts/spark_charts.dart @@ -25,6 +25,7 @@ library; import 'dart:math'; import 'dart:ui' show PointMode; +import 'package:clock/clock.dart'; import 'package:material_ui/material_ui.dart'; import 'package:wger/features/measurements/charts/calendar.dart'; import 'package:wger/features/measurements/charts/colors.dart'; @@ -247,7 +248,7 @@ class SparkHeatmap extends StatelessWidget { size: Size.infinite, painter: _SparkHeatmapPainter( grid: buildHeatmapGrid(days, maxWeeks: weeks, today: today), - today: today ?? DateTime.now(), + today: today ?? clock.now(), filled: scheme.primary, empty: scheme.surfaceContainerHighest, ), diff --git a/lib/features/measurements/widgets/entries.dart b/lib/features/measurements/widgets/entries.dart index dc3d6c2db..37a510829 100644 --- a/lib/features/measurements/widgets/entries.dart +++ b/lib/features/measurements/widgets/entries.dart @@ -16,6 +16,7 @@ * along with this program. If not, see . */ +import 'package:clock/clock.dart'; import 'package:collection/collection.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:material_ui/material_ui.dart'; @@ -97,7 +98,7 @@ class EntriesList extends ConsumerWidget { for (final plan in ref.watch(nutritionProvider).value?.plans ?? const []) ( - range: DateTimeRange(start: plan.startDate, end: plan.endDate ?? DateTime.now()), + range: DateTimeRange(start: plan.startDate, end: plan.endDate ?? clock.now()), name: plan.getLabel(context), ), ] diff --git a/lib/features/measurements/widgets/forms/entry.dart b/lib/features/measurements/widgets/forms/entry.dart index d1050471a..49e53bc84 100644 --- a/lib/features/measurements/widgets/forms/entry.dart +++ b/lib/features/measurements/widgets/forms/entry.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/widgets/datetime_input.dart'; @@ -55,7 +56,7 @@ class _MeasurementEntryFormState extends ConsumerState { widget._entry ?? MeasurementEntry( categoryId: widget._categoryId, - date: DateTime.now(), + date: clock.now(), value: 0, notes: '', ); diff --git a/lib/features/measurements/widgets/forms/group_entry.dart b/lib/features/measurements/widgets/forms/group_entry.dart index 6811e7037..473e0d1cd 100644 --- a/lib/features/measurements/widgets/forms/group_entry.dart +++ b/lib/features/measurements/widgets/forms/group_entry.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/widgets/datetime_input.dart'; @@ -40,7 +41,7 @@ class GroupMeasurementEntryForm extends ConsumerStatefulWidget { class _GroupMeasurementEntryFormState extends ConsumerState { final _form = GlobalKey(); - DateTime _date = DateTime.now(); + DateTime _date = clock.now(); late final Map _values = { for (final child in widget._group.children) child.id!: null, }; diff --git a/lib/features/measurements/widgets/measurement_tile.dart b/lib/features/measurements/widgets/measurement_tile.dart index 59f49b20c..6e0a2c473 100644 --- a/lib/features/measurements/widgets/measurement_tile.dart +++ b/lib/features/measurements/widgets/measurement_tile.dart @@ -18,6 +18,7 @@ import 'dart:math'; +import 'package:clock/clock.dart'; import 'package:collection/collection.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:intl/intl.dart'; @@ -263,8 +264,8 @@ class MeasurementTile extends ConsumerWidget { case SparkKind.line: // A full-history window has no fixed start; the data provides it - final start = window.start ?? dayOf(points.map((e) => e.date).minOrNull ?? DateTime.now()); - final days = window.days ?? daysBetween(start, DateTime.now()) + 1; + final start = window.start ?? dayOf(points.map((e) => e.date).minOrNull ?? clock.now()); + final days = window.days ?? daysBetween(start, clock.now()) + 1; final sparse = sparkIsSparse(points); return [ _SparkArea( @@ -406,7 +407,7 @@ class _WeekdayAxis extends StatelessWidget { Widget build(BuildContext context) { final theme = Theme.of(context); final format = DateFormat('EEEEE', Localizations.localeOf(context).toString()); - final now = DateTime.now(); + final now = clock.now(); final today = DateTime(now.year, now.month, now.day); return Row( @@ -455,7 +456,7 @@ class _MonthAxis extends StatelessWidget { Widget build(BuildContext context) { final theme = Theme.of(context); final locale = Localizations.localeOf(context).languageCode; - final today = DateTime.now(); + final today = clock.now(); final monthFormat = DateFormat.MMM(locale); final months = []; diff --git a/lib/features/measurements/widgets/weight_form.dart b/lib/features/measurements/widgets/weight_form.dart index d84b2ea7d..440720b24 100644 --- a/lib/features/measurements/widgets/weight_form.dart +++ b/lib/features/measurements/widgets/weight_form.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:wger/core/consts.dart'; @@ -64,7 +65,7 @@ class _WeightFormState extends riverpod.ConsumerState { widget._entry ?? MeasurementEntry( categoryId: widget._category.id!, - date: DateTime.now(), + date: clock.now(), value: 0, notes: '', ); diff --git a/test/features/measurements/charts/range_test.dart b/test/features/measurements/charts/range_test.dart index 78bc5f35a..b56bba237 100644 --- a/test/features/measurements/charts/range_test.dart +++ b/test/features/measurements/charts/range_test.dart @@ -23,12 +23,14 @@ import 'package:wger/features/measurements/charts/range.dart'; void main() { group('ChartRange', () { test('the week is the shortest range, the full history the longest', () { - final now = DateTime.now(); + final now = DateTime(2026, 3, 15, 12); - expect(ChartRange.all.cutoff, isNull); - expect(ChartRange.lastMonth.cutoff!.isAfter(ChartRange.last3Months.cutoff!), isTrue); - expect(ChartRange.lastWeek.cutoff!.isAfter(ChartRange.lastMonth.cutoff!), isTrue); - expect(ChartRange.lastWeek.cutoff!.isBefore(now), isTrue); + withClock(Clock.fixed(now), () { + expect(ChartRange.all.cutoff, isNull); + expect(ChartRange.lastMonth.cutoff!.isAfter(ChartRange.last3Months.cutoff!), isTrue); + expect(ChartRange.lastWeek.cutoff!.isAfter(ChartRange.lastMonth.cutoff!), isTrue); + expect(ChartRange.lastWeek.cutoff!.isBefore(now), isTrue); + }); }); test('the week covers today plus the six days before it', () { diff --git a/test/features/measurements/providers/measurement_notifier_test.dart b/test/features/measurements/providers/measurement_notifier_test.dart index 7ea1010ee..3058ad79c 100644 --- a/test/features/measurements/providers/measurement_notifier_test.dart +++ b/test/features/measurements/providers/measurement_notifier_test.dart @@ -164,7 +164,7 @@ void main() { group('addGroupEntries', () { test('addGroupEntries calls repository', () async { final notifier = container.read(measurementProvider.notifier); - final entries = [testNeasurementEntry9, testNeasurementEntry10]; + final entries = [testMeasurementEntry9, testMeasurementEntry10]; await notifier.addGroupEntries(entries); verify(mockRepo.addLocalDriftGroupEntries(entries)).called(1); diff --git a/test/features/measurements/providers/measurement_repository_test.dart b/test/features/measurements/providers/measurement_repository_test.dart index f6feea10b..c9e869eae 100644 --- a/test/features/measurements/providers/measurement_repository_test.dart +++ b/test/features/measurements/providers/measurement_repository_test.dart @@ -73,7 +73,7 @@ void main() { final old = MeasurementEntry( id: 'ancient', categoryId: category.id!, - date: DateTime.now().subtract(const Duration(days: 900)), + date: DateTime(2023, 9, 1), value: 42, notes: '', ); diff --git a/test/features/measurements/screens/measurement_entries_screen_test.dart b/test/features/measurements/screens/measurement_entries_screen_test.dart index e71654755..8d2ab8095 100644 --- a/test/features/measurements/screens/measurement_entries_screen_test.dart +++ b/test/features/measurements/screens/measurement_entries_screen_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:mockito/annotations.dart'; @@ -45,15 +46,6 @@ void main() { late MockNutritionRepository mockNutritionRepo; late MockIngredientRepository mockIngredientRepo; - /// The fixture's entries moved into the last few days, for the tests that - /// need a chart in every range rather than only in the full history - Map> recentEntries() => { - '1': [ - for (final (index, entry) in getMeasurementEntries()['1']!.indexed) - entry.copyWith(date: DateTime.now().subtract(Duration(days: index))), - ], - }; - setUp(() { // The shared chart range hydrates from SharedPreferences on first read SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty(); @@ -156,20 +148,23 @@ void main() { testWidgets('switching the range keeps the screen it already drew', (tester) async { // Entries in every range, so the switch is between two ranges that both // have something to draw - await tester.pumpWidget(createEntriesScreen(entries: recentEntries())); - await tester.tap(find.byType(TextButton)); - await tester.pumpAndSettle(); - expect(find.byType(MeasurementChartWidgetFl), findsOneWidget); + final today = DateTime(2026, 3, 15, 12); + await withClock(Clock.fixed(today), () async { + await tester.pumpWidget(createEntriesScreen(entries: {'1': entriesEndingAt(today, 6)})); + await tester.tap(find.byType(TextButton)); + await tester.pumpAndSettle(); + expect(find.byType(MeasurementChartWidgetFl), findsOneWidget); - // The new range watches different providers, both starting out loading: - // this is the frame in which the screen used to drop everything it had - await tester.ensureVisible(find.text('1 year')); - await tester.tap(find.text('1 year')); - await tester.pump(); + // The new range watches different providers, both starting out loading: + // this is the frame in which the screen used to drop everything it had + await tester.ensureVisible(find.text('1 year')); + await tester.tap(find.text('1 year')); + await tester.pump(); - expect(find.text('Body fat'), findsOneWidget); - expect(find.byType(CircularProgressIndicator), findsNothing); - expect(find.byType(MeasurementChartWidgetFl), findsOneWidget); + expect(find.text('Body fat'), findsOneWidget); + expect(find.byType(CircularProgressIndicator), findsNothing); + expect(find.byType(MeasurementChartWidgetFl), findsOneWidget); + }); }); testWidgets('Tests the localization of dates - EN', (WidgetTester tester) async { diff --git a/test/features/measurements/widgets/categories_card_test.dart b/test/features/measurements/widgets/categories_card_test.dart index 94c7d3e19..a2bffc8a1 100644 --- a/test/features/measurements/widgets/categories_card_test.dart +++ b/test/features/measurements/widgets/categories_card_test.dart @@ -103,16 +103,6 @@ _Seed _tripleGroup() { /// A sleep group: the total plus two stages, all on the same night _Seed _sleepGroup() { - MeasurementCategory child(String id, String name, MetricType type, int order) => - MeasurementCategory( - id: id, - name: name, - unit: 'min', - metricType: type, - parentId: 'sleep', - order: order, - ); - MeasurementEntry reading(String id, num value) => MeasurementEntry( id: 'e-$id', categoryId: id, @@ -122,17 +112,7 @@ _Seed _sleepGroup() { ); return ( - category: MeasurementCategory( - id: 'sleep', - name: 'Sleep', - unit: 'min', - metricType: MetricType.sleep, - children: [ - child('total', 'Total sleep', MetricType.sleepTotal, 0), - child('deep', 'Deep sleep', MetricType.sleepDeep, 1), - child('rem', 'REM sleep', MetricType.sleepRem, 2), - ], - ), + category: getSleepGroup(), entries: { 'total': [reading('total', 480)], 'deep': [reading('deep', 90)], @@ -191,8 +171,8 @@ void main() { final group = ( category: testMeasurementCategoryBloodPressure, entries: { - 'sys': [testNeasurementEntry9], - 'dia': [testNeasurementEntry10.copyWith(date: DateTime(2026, 1, 1, 9, 30))], + 'sys': [testMeasurementEntry9], + 'dia': [testMeasurementEntry10.copyWith(date: DateTime(2026, 1, 1, 9, 30))], }, ); diff --git a/test/features/measurements/widgets/charts/heatmap_chart_test.dart b/test/features/measurements/widgets/charts/heatmap_chart_test.dart index c800216f1..2b2cb0e3c 100644 --- a/test/features/measurements/widgets/charts/heatmap_chart_test.dart +++ b/test/features/measurements/widgets/charts/heatmap_chart_test.dart @@ -18,6 +18,7 @@ import 'dart:math'; +import 'package:clock/clock.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:material_ui/material_ui.dart'; import 'package:wger/features/measurements/charts/data.dart'; @@ -44,33 +45,34 @@ void main() { }); testWidgets('reads out the day that was tapped', (tester) async { - final today = DateTime.now(); - final day = DateTime(today.year, today.month, today.day); - await tester.pumpWidget(_wrap(MeasurementHeatmapWidgetFl([entry(500, day)], 'steps'))); - await tester.pumpAndSettle(); + final day = DateTime(2026, 3, 15); + await withClock(Clock.fixed(DateTime(2026, 3, 15, 12)), () async { + await tester.pumpWidget(_wrap(MeasurementHeatmapWidgetFl([entry(500, day)], 'steps'))); + await tester.pumpAndSettle(); - // A single day is a one-column grid, so its cell sits in the row of its - // weekday. The read-out is what the tooltip is on the other charts. - expect(buildHeatmapGrid([entry(500, day)]).weeks, 1); + // A single day is a one-column grid, so its cell sits in the row of its + // weekday. The read-out is what the tooltip is on the other charts. + expect(buildHeatmapGrid([entry(500, day)]).weeks, 1); - // Mirrors the widget's own layout: the read-out line above the grid, the - // weekday labels to its left, the month labels on top, and the square - // cells centred in what is left - const readoutHeight = 20.0; - const labelWidth = 22.0; - const labelHeight = 12.0; - final box = tester.getRect(find.byType(MeasurementHeatmapWidgetFl)); - final gridHeight = box.height - readoutHeight - labelHeight; - final step = min(box.width - labelWidth, gridHeight / DateTime.daysPerWeek); - final top = - box.top + readoutHeight + labelHeight + (gridHeight - step * DateTime.daysPerWeek) / 2; + // Mirrors the widget's own layout: the read-out line above the grid, the + // weekday labels to its left, the month labels on top, and the square + // cells centred in what is left + const readoutHeight = 20.0; + const labelWidth = 22.0; + const labelHeight = 12.0; + final box = tester.getRect(find.byType(MeasurementHeatmapWidgetFl)); + final gridHeight = box.height - readoutHeight - labelHeight; + final step = min(box.width - labelWidth, gridHeight / DateTime.daysPerWeek); + final top = + box.top + readoutHeight + labelHeight + (gridHeight - step * DateTime.daysPerWeek) / 2; - await tester.tapAt( - Offset(box.left + labelWidth + step / 2, top + step * (day.weekday - 1) + step / 2), - ); - await tester.pumpAndSettle(); + await tester.tapAt( + Offset(box.left + labelWidth + step / 2, top + step * (day.weekday - 1) + step / 2), + ); + await tester.pumpAndSettle(); - expect(find.textContaining('500'), findsOneWidget); + expect(find.textContaining('500'), findsOneWidget); + }); }); }); } diff --git a/test/features/measurements/widgets/entries_test.dart b/test/features/measurements/widgets/entries_test.dart index efab908df..4aa2fa978 100644 --- a/test/features/measurements/widgets/entries_test.dart +++ b/test/features/measurements/widgets/entries_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:mockito/annotations.dart'; @@ -191,35 +192,20 @@ void main() { testWidgets('A group charts its components and lists the readings', ( WidgetTester tester, ) async { - // The list defaults to the last three months, so a fixed date would fall - // out of the range as time passes - final night = DateTime.now().subtract(const Duration(days: 1)); - MeasurementCategory child(String id, String name, MetricType type, int order) => - MeasurementCategory( - id: id, - name: name, - unit: 'min', - metricType: type, - parentId: 'sleep', - order: order, - ); - final group = MeasurementCategory( - id: 'sleep', - name: 'Sleep', - unit: 'min', - metricType: MetricType.sleep, - children: [ - child('total', 'Total sleep', MetricType.sleepTotal, 0), - child('deep', 'Deep sleep', MetricType.sleepDeep, 1), - ], - ); + // The list defaults to the last three months, the clock keeps the night + // inside them + final today = DateTime(2026, 3, 15, 12); + final night = DateTime(2026, 3, 14, 23); + final group = getSleepGroup(components: const [MetricType.sleepTotal, MetricType.sleepDeep]); final entries = { for (final (id, value) in [('total', 480), ('deep', 90)]) id: [MeasurementEntry(id: 'e-$id', categoryId: id, date: night, value: value, notes: '')], }; - await tester.pumpWidget(createEntriesList(group, entries)); - await tester.pumpAndSettle(); + await withClock(Clock.fixed(today), () async { + await tester.pumpWidget(createEntriesList(group, entries)); + await tester.pumpAndSettle(); + }); // The group holds no entries itself, so its own list would be empty: it // shows the components' readings instead, the roll-up leading @@ -237,58 +223,49 @@ void main() { // A page is entries, a row is a reading, and a blood pressure page of // fifty entries lists twenty-five: reading "more to come" off the rows // left the list stuck on its first page - final readings = [ - for (var day = 0; day < 40; day++) DateTime.now().subtract(Duration(days: day)), - ]; + final today = DateTime(2026, 3, 15, 12); final group = testMeasurementCategoryBloodPressure; final entries = { for (final (id, value) in [('sys', 120), ('dia', 80)]) - id: [ - for (final (index, date) in readings.indexed) - MeasurementEntry(id: '$id-$index', categoryId: id, date: date, value: value, notes: ''), - ], + id: entriesEndingAt(today, 40, categoryId: id, value: (_) => value), }; final mockRepo = MockMeasurementRepository(); tester.view.physicalSize = const Size(800, 1600); tester.view.devicePixelRatio = 1.0; addTearDown(tester.view.reset); - await tester.pumpWidget(createEntriesList(group, entries, repo: mockRepo)); - await tester.pumpAndSettle(); - verify(mockRepo.watchGroupEntries('bp', limit: 50)).called(greaterThanOrEqualTo(1)); + await withClock(Clock.fixed(today), () async { + await tester.pumpWidget(createEntriesList(group, entries, repo: mockRepo)); + await tester.pumpAndSettle(); + verify(mockRepo.watchGroupEntries('bp', limit: 50)).called(greaterThanOrEqualTo(1)); - // Past the end, so the assertion does not hang on a row height - await tester.drag(find.byType(CustomScrollView), const Offset(0, -3000)); - await tester.pumpAndSettle(); + // Past the end, so the assertion does not hang on a row height + await tester.drag(find.byType(CustomScrollView), const Offset(0, -3000)); + await tester.pumpAndSettle(); - verify(mockRepo.watchGroupEntries('bp', limit: 100)).called(greaterThanOrEqualTo(1)); - // The larger page loads under a new provider; showing nothing meanwhile - // emptied the list and threw the user back to the top - final scrollable = tester.state( - find.descendant(of: find.byType(CustomScrollView), matching: find.byType(Scrollable)).first, - ); - expect(scrollable.position.pixels, greaterThan(0)); + verify(mockRepo.watchGroupEntries('bp', limit: 100)).called(greaterThanOrEqualTo(1)); + // The larger page loads under a new provider; showing nothing meanwhile + // emptied the list and threw the user back to the top + final scrollable = tester.state( + find.descendant(of: find.byType(CustomScrollView), matching: find.byType(Scrollable)).first, + ); + expect(scrollable.position.pixels, greaterThan(0)); + }); }); testWidgets('A tall screen lists the entries past the first few', (WidgetTester tester) async { // The list used to sit in a box of fixed height, so a tablet showed a // handful of rows and left the rest of the screen empty (#1002) - final entries = [ - for (var day = 0; day < 30; day++) - MeasurementEntry( - id: 'e-$day', - categoryId: 'c1', - date: DateTime.now().subtract(Duration(days: day)), - value: 100 + day, - notes: '', - ), - ]; + final today = DateTime(2026, 3, 15, 12); + final entries = entriesEndingAt(today, 30, categoryId: 'c1', value: (day) => 100 + day); tester.view.physicalSize = const Size(800, 2400); tester.view.devicePixelRatio = 1.0; addTearDown(tester.view.reset); - await tester.pumpWidget(createEntriesList(bodyFat, {'c1': entries})); - await tester.pumpAndSettle(); + await withClock(Clock.fixed(today), () async { + await tester.pumpWidget(createEntriesList(bodyFat, {'c1': entries})); + await tester.pumpAndSettle(); + }); // Newest first, so the fifteenth row is the value 114 expect(find.text('114 %'), findsOneWidget); @@ -305,19 +282,13 @@ void main() { unit: 'cm', chartType: ChartType.distribution, ); - final entries = [ - for (var day = 0; day < 30; day++) - MeasurementEntry( - id: 'e-$day', - categoryId: 'c1', - date: DateTime.now().subtract(Duration(days: day)), - value: 30 + day % 5, - notes: '', - ), - ]; + final today = DateTime(2026, 3, 15, 12); + final entries = entriesEndingAt(today, 30, categoryId: 'c1', value: (day) => 30 + day % 5); - await tester.pumpWidget(createEntriesList(category, {'c1': entries})); - await tester.pumpAndSettle(); + await withClock(Clock.fixed(today), () async { + await tester.pumpWidget(createEntriesList(category, {'c1': entries})); + await tester.pumpAndSettle(); + }); expect(find.byType(MeasurementDistributionWidgetFl), findsOneWidget); }); diff --git a/test/features/measurements/widgets/helpers_test.dart b/test/features/measurements/widgets/helpers_test.dart index adef995bd..700ee0e8d 100644 --- a/test/features/measurements/widgets/helpers_test.dart +++ b/test/features/measurements/widgets/helpers_test.dart @@ -296,37 +296,7 @@ void main() { MeasurementEntry(categoryId: categoryId, date: date, value: value, notes: ''); /// A sleep group as the importer writes it: the total plus its stages. - MeasurementCategory sleepGroup() => MeasurementCategory( - id: 'g', - name: 'Sleep', - unit: 'min', - metricType: MetricType.sleep, - children: [ - MeasurementCategory( - id: 'total', - name: 'Total sleep', - unit: 'min', - metricType: MetricType.sleepTotal, - parentId: 'g', - ), - MeasurementCategory( - id: 'deep', - name: 'Deep sleep', - unit: 'min', - metricType: MetricType.sleepDeep, - parentId: 'g', - order: 1, - ), - MeasurementCategory( - id: 'rem', - name: 'REM sleep', - unit: 'min', - metricType: MetricType.sleepRem, - parentId: 'g', - order: 2, - ), - ], - ); + MeasurementCategory sleepGroup() => getSleepGroup(); Map> sleepEntries({bool withStages = true}) => { 'total': [entry('total', DateTime(2026, 1, 2), 480)], @@ -375,21 +345,7 @@ void main() { test('several entries of one day add up within their component', () { // A nap next to the night: the bar shows the day, not the segment - final group = MeasurementCategory( - id: 'g', - name: 'Sleep', - unit: 'min', - metricType: MetricType.sleep, - children: [ - MeasurementCategory( - id: 'deep', - name: 'Deep sleep', - unit: 'min', - metricType: MetricType.sleepDeep, - parentId: 'g', - ), - ], - ); + final group = getSleepGroup(components: const [MetricType.sleepDeep]); final entries = { 'deep': [ entry('deep', DateTime(2026, 1, 2, 3), 90), @@ -549,7 +505,7 @@ void main() { group('buildSeriesChartSection change chart', () { final history = [ for (var i = 0; i < 100; i++) - MeasurementChartEntry(60 + (i % 5), DateTime.now().subtract(Duration(days: 99 - i))), + MeasurementChartEntry(60 + (i % 5), DateTime(2026, 3, 15 - (99 - i))), ]; Future pumpDelta(WidgetTester tester) => _pumpWidgetList( @@ -589,7 +545,7 @@ void main() { group('buildSeriesChartSection distribution chart', () { final history = [ for (var i = 0; i < 100; i++) - MeasurementChartEntry(60 + (i % 5), DateTime.now().subtract(Duration(days: 99 - i))), + MeasurementChartEntry(60 + (i % 5), DateTime(2026, 3, 15 - (99 - i))), ]; Future pumpDistribution(WidgetTester tester) => _pumpWidgetList( diff --git a/test/features/measurements/widgets/measurement_tile_test.dart b/test/features/measurements/widgets/measurement_tile_test.dart index 730ae1bdc..246f66983 100644 --- a/test/features/measurements/widgets/measurement_tile_test.dart +++ b/test/features/measurements/widgets/measurement_tile_test.dart @@ -279,27 +279,8 @@ void main() { }); testWidgets('sleep tile: the total leads, stacked bars behind it', (tester) async { - final group = MeasurementCategory( - id: 'sleep', - name: 'Sleep', - unit: 'min', - metricType: MetricType.sleep, - children: [ - MeasurementCategory( - id: 'total', - name: 'Total sleep', - unit: 'min', - metricType: MetricType.sleepTotal, - parentId: 'sleep', - ), - MeasurementCategory( - id: 'deep', - name: 'Deep sleep', - unit: 'min', - metricType: MetricType.sleepDeep, - parentId: 'sleep', - ), - ], + final group = getSleepGroup( + components: const [MetricType.sleepTotal, MetricType.sleepDeep], ); final entries = { 'total': [_entry('total', 432, _day(1))], diff --git a/test_data/body_weight.dart b/test_data/body_weight.dart index 4c70bbb8a..4bc28c5ab 100644 --- a/test_data/body_weight.dart +++ b/test_data/body_weight.dart @@ -27,14 +27,14 @@ final testWeightEntry1 = MeasurementEntry( id: '1', categoryId: testBodyWeightCategoryId, value: 80.0, - date: DateTime.utc(2021, 01, 01, 15, 30), + date: DateTime(2021, 01, 01, 15, 30), notes: 'After the run', ); final testWeightEntry2 = MeasurementEntry( id: '2', categoryId: testBodyWeightCategoryId, value: 81.0, - date: DateTime.utc(2021, 01, 10, 10, 0), + date: DateTime(2021, 01, 10, 10, 0), notes: '', ); @@ -43,7 +43,7 @@ final testWeightEntryLb = MeasurementEntry( id: '3', categoryId: testBodyWeightCategoryId, value: 176.4, - date: DateTime.utc(2021, 01, 20, 8, 0), + date: DateTime(2021, 01, 20, 8, 0), notes: '', extraData: const {'unit': 'lb'}, ); diff --git a/test_data/measurements.dart b/test_data/measurements.dart index 4c6595675..b090f3181 100644 --- a/test_data/measurements.dart +++ b/test_data/measurements.dart @@ -78,7 +78,7 @@ final testMeasurementEntry8 = MeasurementEntry( notes: '', ); -final testNeasurementEntry9 = MeasurementEntry( +final testMeasurementEntry9 = MeasurementEntry( id: 'e1', categoryId: 'sys', date: DateTime(2026, 1, 1), @@ -86,7 +86,7 @@ final testNeasurementEntry9 = MeasurementEntry( notes: '', ); -final testNeasurementEntry10 = MeasurementEntry( +final testMeasurementEntry10 = MeasurementEntry( id: 'e2', categoryId: 'dia', date: DateTime(2026, 1, 1), @@ -160,7 +160,67 @@ Map> getMeasurementEntries() { /// The entries of [getBloodPressureGroup], keyed by component id. Map> getBloodPressureEntries() { return { - 'sys': [testNeasurementEntry9], - 'dia': [testNeasurementEntry10], + 'sys': [testMeasurementEntry9], + 'dia': [testMeasurementEntry10], }; } + +/// [count] daily entries of [categoryId], newest first, the newest on the +/// calendar day of [end] and at its time of day. +/// +/// The days are counted on the calendar, so a range across a DST switch keeps +/// one entry per day. [value] gets the number of days back, the default is a +/// flat 100. +List entriesEndingAt( + DateTime end, + int count, { + String categoryId = '1', + num Function(int daysBack)? value, +}) => [ + for (var daysBack = 0; daysBack < count; daysBack++) + MeasurementEntry( + id: '$categoryId-$daysBack', + categoryId: categoryId, + date: DateTime(end.year, end.month, end.day - daysBack, end.hour, end.minute), + value: value?.call(daysBack) ?? 100, + notes: '', + ), +]; + +const _sleepComponents = { + MetricType.sleepTotal: ('total', 'Total sleep'), + MetricType.sleepLight: ('light', 'Light sleep'), + MetricType.sleepDeep: ('deep', 'Deep sleep'), + MetricType.sleepRem: ('rem', 'REM sleep'), + MetricType.sleepAwake: ('awake', 'Awake'), +}; + +/// A sleep group as the health importer writes it, with [components] as its +/// children in that order. A component's id is its short name (`total`, +/// `deep`, `rem`, ...), its unit minutes. +MeasurementCategory getSleepGroup({ + String id = 'sleep', + List components = const [ + MetricType.sleepTotal, + MetricType.sleepDeep, + MetricType.sleepRem, + ], +}) { + return MeasurementCategory( + id: id, + name: 'Sleep', + unit: 'min', + metricType: MetricType.sleep, + children: [ + for (final (order, type) in components.indexed) + MeasurementCategory( + id: _sleepComponents[type]!.$1, + name: _sleepComponents[type]!.$2, + unit: 'min', + metricType: type, + parentId: id, + order: order, + ), + ], + ); +}