mirror of
https://github.com/kuhyx/diet-guard.git
synced 2026-11-21 17:42:17 +01:00
Some checks failed
Meals logged on the phone stopped reaching the PC, so the gate kept locking for slots that were already logged and the only way through was to spam "nothing". The PC's fetch was never broken: it was faithfully pulling a Firebase that did not contain the phone's meals. The phone had no working publish backstop on either transport: - `checkAndNotify` gated its sync on `due.isNotEmpty`. Logging every meal promptly means nothing is ever due, so the ~15-min periodic task never published. It was a notification job that happened to sync, not a sync timer. It now syncs on every tick it is asked to, then computes due slots from the merged result, so a meal pulled from another device suppresses a nag instead of triggering one. - `backgroundSyncPush` never called `initSyncDeviceId()`. A fresh isolate has its own static state, so `currentSyncDeviceId` fell back to the compile-time 'phone' constant and published to `devices/phone/` rather than the persisted uuid -- which then makes the next foreground push see `unchanged` and skip writing the uuid directory entirely. Separately, on the "Fetch from sync" path itself: `FirebaseSyncError` and `FirebaseAuthError` are siblings of `GitHubSyncError` under `RemoteSyncError`, not subclasses, so every per-request failure of the *primary* backend escaped `pull_shared_log`'s catch tuple and raised a traceback out of a helper documented to fail closed with a reason string. `ConfigError` needed the same treatment by a different route: it subclasses `Exception` directly, so it is outside `RemoteSyncError` too, and is now translated at `_client_for_run`. The PAT is no longer mandatory either. Firebase is primary, but `_read_token` ran before the client was ever built, so a Firebase-only machine could not sync at all -- the commits that fixed this touched only the Dart side. A stalled sync was invisible: the config gates returned silently and `openFirebase` swallowed every error. `dart:developer`'s `log()` does not reach logcat on a release build (verified on device), so logging alone would not have surfaced it. `SyncHealth` records each tick's outcome and the log screen shows a banner when publishing has actually stopped. Also make the real-Tk probes bypass the window manager. A tiling WM retiles a managed toplevel instead of honouring the requested geometry, so `winfo_height` reported 0/1px and the layout and focus-ring assertions failed on noise rather than on any regression -- 8 failures on the dev machine that only passed under Xvfb. `overrideredirect` makes the measurement deterministic with or without a WM; the probes still detect a genuine overflow at 1366x300. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RT8X32S9yDLW1Xf1PDq8z7
215 lines
7.7 KiB
Dart
215 lines
7.7 KiB
Dart
// `checkAndNotify` is the scheduler-independent half of the periodic
|
|
// check; `backgroundCheckCallbackDispatcher` itself is integration-only
|
|
// (real WorkManager isolate, manual on-device smoke test) per the project
|
|
// plan, and is excluded from coverage.
|
|
|
|
import 'dart:convert';
|
|
import 'dart:io';
|
|
|
|
import 'package:diet_guard_app/models/nutrition.dart';
|
|
import 'package:diet_guard_app/services/app_settings_service.dart';
|
|
import 'package:diet_guard_app/services/budget_history_service.dart';
|
|
import 'package:diet_guard_app/services/document_store_io.dart';
|
|
import 'package:diet_guard_app/services/due_slot_check.dart';
|
|
import 'package:diet_guard_app/services/foodbank_service.dart';
|
|
import 'package:diet_guard_app/services/log_storage_service.dart';
|
|
import 'package:diet_guard_app/services/notification_backend_io.dart';
|
|
import 'package:diet_guard_app/services/notification_service.dart';
|
|
import 'package:flutter/services.dart';
|
|
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
|
import 'package:flutter_test/flutter_test.dart';
|
|
import 'package:http/http.dart' as http;
|
|
import 'package:http/testing.dart';
|
|
import 'package:shared_preferences/shared_preferences.dart';
|
|
|
|
import '../fake_notifications.dart';
|
|
import '../fake_secure_storage.dart';
|
|
|
|
const _manual = Nutrition(
|
|
kcal: 200,
|
|
proteinG: 10,
|
|
carbsG: 20,
|
|
fatG: 5,
|
|
grams: 100,
|
|
source: 'manual',
|
|
);
|
|
|
|
void main() {
|
|
TestWidgetsFlutterBinding.ensureInitialized();
|
|
late Directory tempDir;
|
|
late List<MethodCall> notificationLog;
|
|
|
|
setUp(() async {
|
|
tempDir = await Directory.systemTemp.createTemp('diet_guard_bg_check_');
|
|
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
|
|
// The due-slot pull reuses backgroundSyncPush, which re-inits these two;
|
|
// pre-seeding the singletons keeps that off the real path_provider
|
|
// channel, exactly as background_sync_service_test.dart does.
|
|
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
|
|
AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir));
|
|
BudgetHistoryService.resetForTesting(
|
|
store: FileDocumentStore(tempDir),
|
|
);
|
|
SharedPreferences.setMockInitialValues({});
|
|
installFakeSecureStorage();
|
|
notificationLog = installFakeAndroidNotifications();
|
|
NotificationService.resetForTesting(
|
|
backend: LocalNotificationsBackend(FlutterLocalNotificationsPlugin()),
|
|
);
|
|
});
|
|
|
|
tearDown(() async {
|
|
LogStorageService.resetForTesting();
|
|
FoodBankService.resetForTesting();
|
|
AppSettingsService.resetForTesting();
|
|
BudgetHistoryService.resetForTesting();
|
|
NotificationService.resetForTesting();
|
|
await tempDir.delete(recursive: true);
|
|
});
|
|
|
|
test(
|
|
'shows due-and-unlogged slots, cancels logged and upcoming ones',
|
|
() async {
|
|
await LogStorageService.instance.logMeal('lunch', _manual, slot: 12);
|
|
|
|
await checkAndNotify(now: DateTime(2026, 1, 1, 16));
|
|
|
|
final shown = notificationLog
|
|
.where((c) => c.method == 'show')
|
|
.map((c) => (c.arguments as Map)['id'])
|
|
.toSet();
|
|
final cancelled = notificationLog
|
|
.where((c) => c.method == 'cancel')
|
|
.map((c) => (c.arguments as Map)['id'])
|
|
.toSet();
|
|
expect(shown, {8, 16});
|
|
expect(cancelled, {12, 20});
|
|
},
|
|
);
|
|
|
|
test('cancels everything when every due slot is logged', () async {
|
|
await LogStorageService.instance.logMeal('breakfast', _manual, slot: 8);
|
|
|
|
await checkAndNotify(now: DateTime(2026, 1, 1, 8));
|
|
|
|
expect(notificationLog.where((c) => c.method == 'show'), isEmpty);
|
|
expect(notificationLog.where((c) => c.method == 'cancel'), hasLength(4));
|
|
});
|
|
|
|
test('uses the real clock when now is omitted', () async {
|
|
// Just exercises the `now ?? DateTime.now()` branch without asserting
|
|
// on specific slots (which depend on the actual time the test runs).
|
|
await checkAndNotify();
|
|
expect(
|
|
notificationLog.where(
|
|
(c) => c.method == 'show' || c.method == 'cancel',
|
|
),
|
|
isNotEmpty,
|
|
);
|
|
});
|
|
|
|
test('still syncs when nothing is due', () async {
|
|
await LogStorageService.instance.logMeal('breakfast', _manual, slot: 8);
|
|
SharedPreferences.setMockInitialValues({
|
|
'sync.owner': 'o',
|
|
'sync.repo': 'r',
|
|
});
|
|
installFakeSecureStorage(initial: {'sync.token': 't'});
|
|
var requests = 0;
|
|
final mock = MockClient((req) async {
|
|
requests++;
|
|
return http.Response('', 404);
|
|
});
|
|
|
|
await checkAndNotify(now: DateTime(2026, 1, 1, 8), httpClient: mock);
|
|
|
|
// Regression guard. This asserted `requests == 0` -- "nothing due, so
|
|
// never touch the network" -- which is precisely the bug: logging every
|
|
// meal promptly on the phone left nothing ever due, so this periodic task
|
|
// never published and the PC kept locking for slots that WERE logged.
|
|
// This is the phone's only unconditional publish path; it must always run.
|
|
expect(requests, greaterThan(0));
|
|
});
|
|
|
|
test('pullWhenDue false skips the network even with a slot due', () async {
|
|
SharedPreferences.setMockInitialValues({
|
|
'sync.owner': 'o',
|
|
'sync.repo': 'r',
|
|
});
|
|
installFakeSecureStorage(initial: {'sync.token': 't'});
|
|
var requests = 0;
|
|
final mock = MockClient((req) async {
|
|
requests++;
|
|
return http.Response('', 404);
|
|
});
|
|
|
|
await checkAndNotify(
|
|
now: DateTime(2026, 1, 1, 16),
|
|
httpClient: mock,
|
|
pullWhenDue: false,
|
|
);
|
|
|
|
expect(requests, 0);
|
|
// Still reconciles notifications from the local log alone.
|
|
expect(
|
|
notificationLog.where((c) => c.method == 'show'),
|
|
isNotEmpty,
|
|
);
|
|
});
|
|
|
|
test('a meal pulled from another device cancels its reminder', () async {
|
|
SharedPreferences.setMockInitialValues({
|
|
'sync.owner': 'o',
|
|
'sync.repo': 'r',
|
|
});
|
|
installFakeSecureStorage(initial: {'sync.token': 't'});
|
|
// Must be *today* in the real clock's terms: `now` only steers which
|
|
// slots are due, while "which day's entries count" comes from the
|
|
// system date inside loggedSlotsToday.
|
|
final today = DateTime.now();
|
|
final day =
|
|
'${today.year.toString().padLeft(4, '0')}-'
|
|
'${today.month.toString().padLeft(2, '0')}-'
|
|
'${today.day.toString().padLeft(2, '0')}';
|
|
// The PC pushed a 12:00 meal this device has never seen locally.
|
|
final remote =
|
|
'{"pc-entry":{"id":"pc-entry","fields":{"body":[{"time":'
|
|
'"${day}T12:30:00+01:00","desc":"pc lunch","kcal":500,'
|
|
'"protein_g":30,"carbs_g":50,"fat_g":15,"grams":300,'
|
|
'"source":"manual","slot":12,"day":"$day"},'
|
|
'"${day}T11:30:00.000Z-0000-pc"]},"deleted":false,'
|
|
'"deleted_hlc":null}}';
|
|
final mock = MockClient((req) async {
|
|
if (req.method == 'PUT') return http.Response('{}', 200);
|
|
if (req.method == 'GET' && req.url.pathSegments.length == 3) {
|
|
return http.Response('{}', 200);
|
|
}
|
|
if (req.url.path.endsWith('/devices')) {
|
|
return http.Response('[{"name":"pc","type":"dir"}]', 200);
|
|
}
|
|
if (req.url.path.endsWith('/devices/pc/food_log.json')) {
|
|
// The Contents API returns base64 in a `content` field, not raw JSON.
|
|
return http.Response(
|
|
jsonEncode({'content': base64.encode(utf8.encode(remote))}),
|
|
200,
|
|
);
|
|
}
|
|
return http.Response('', 404);
|
|
});
|
|
|
|
await checkAndNotify(
|
|
now: DateTime(today.year, today.month, today.day, 12),
|
|
httpClient: mock,
|
|
);
|
|
|
|
// This is the false alarm the fix exists to kill: 12:00 was unlogged
|
|
// locally, so the pre-fix code fired a reminder for a meal that was
|
|
// already logged on the PC.
|
|
final shown = notificationLog
|
|
.where((c) => c.method == 'show')
|
|
.map((c) => (c.arguments as Map)['id'])
|
|
.toSet();
|
|
expect(shown, isNot(contains(12)));
|
|
});
|
|
}
|