Files
sure/mobile/test/widgets/privacy_mode_test.dart
ghost 401cd6ab08 feat(mobile): privacy mode to mask money values (#2386)
* feat(mobile): add privacy mode to mask money values

Adds an app-wide "privacy mode" so users can hide monetary amounts from
over-the-shoulder view.

- PrivacyProvider (ChangeNotifier) backed by PreferencesService, so the
  choice persists across launches and every money widget rebuilds on
  toggle.
- MoneyMasker.mask() collapses an amount's numeric portion into a short
  fixed run of bullets while keeping the currency symbol and sign
  (e.g. CA$1,234.56 -> CA$••••). A fixed run avoids leaking the value's
  magnitude and reads cleanly without stray separators. Currency- and
  locale-agnostic — it operates on already-formatted strings.
- Masking applied at every money render site: net worth + per-currency
  totals + breakdown sheet (NetWorthCard), account balances (AccountCard,
  AccountDetailHeader, transaction form account selector), and transaction
  amounts (transactions list, recent transactions, calendar).
- Two entry points: a "Hide amounts" switch in Settings -> Security, and a
  quick eye toggle in the top bar (visible on every tab).

Tests: MoneyMasker unit tests (fixed-run mask, magnitude hidden, symbol/
sign kept, passthrough, idempotent) + a widget test asserting the net
worth masks/unmasks as the provider flips; account_card_test updated to
provide the new provider. flutter analyze: no new issues; full suite
(123) green.

* fix(mobile): address privacy-mode review feedback

- Startup masking (Codex P1): read the privacy preference in main() before
  runApp and seed PrivacyProvider with it, so the first frame already has
  the correct value — money is never briefly rendered unmasked for a user
  who enabled "Hide amounts". Provider stays fail-closed otherwise: starts
  masked, SureApp's no-arg default is masked, and a failed read keeps it
  masked. A late-completing initial load no longer clobbers an explicit
  user toggle.
- setHidden() reverts the in-memory state (and logs) if persistence fails,
  keeping the UI consistent with what's actually stored.
- Mask the cash-balance detail chip in AccountDetailHeader (was leaking
  the cash position in privacy mode).
- Privacy top-bar toggle gets a "Toggle privacy" tooltip + icon semantic
  label for accessibility (kept as an InkWell to match the adjacent
  settings control).
- Tests: assert fail-closed initial state; assert the exact masked count;
  test the persistence round-trip (set -> reload); add
  PreferencesService.resetForTest() and reset between tests so the cached
  singleton can't leak state.

125 tests pass; flutter analyze: no new issues.

* refactor(mobile): thread hideAmounts through calendar tiles

Per review: the calendar tile builders read PrivacyProvider via
context.read, relying implicitly on the parent build()'s context.watch to
rebuild them — fragile if a tile is later extracted or wrapped in a
RepaintBoundary. Pass hideAmounts down explicitly instead, matching the
recent_transactions_screen pattern:

- build() (context.watch) -> _buildCalendar -> _buildDayCell
- _showTransactionsDialog reads once when the modal opens ->
  _buildTransactionTile

No more context.read inside tile methods. 125 tests pass; analyze clean.

* fix(mobile): watch PrivacyProvider inside calendar dialog builder

Moving the hideAmounts read inside the showDialog builder and switching
from context.read to context.watch ensures the dialog re-masks transaction
amounts if the user toggles privacy mode while the dialog is open.
2026-06-30 06:49:05 +02:00

100 lines
3.6 KiB
Dart

import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sure_mobile/providers/privacy_provider.dart';
import 'package:sure_mobile/services/preferences_service.dart';
import 'package:sure_mobile/widgets/net_worth_card.dart';
void main() {
setUp(() {
// PrivacyProvider persists through SharedPreferences; mock it so the
// provider can load/save without the platform channel, and reset the
// cached PreferencesService so state never leaks between tests.
SharedPreferences.setMockInitialValues({});
PreferencesService.resetForTest();
});
Widget harness(PrivacyProvider privacy) {
return ChangeNotifierProvider<PrivacyProvider>.value(
value: privacy,
child: MaterialApp(
home: Scaffold(
body: NetWorthCard(
assetTotalsByCurrency: const {'USD': 29669.71},
liabilityTotalsByCurrency: const {},
currentFilter: AccountFilter.all,
onFilterChanged: (_) {},
formatAmount: (currency, amount) =>
'\$${amount.toStringAsFixed(2)}',
netWorthFormatted: r'$29,669.71',
),
),
),
);
}
// PrivacyProvider starts masked (fail-closed) and reveals only once the async
// preference load completes, so pump a few frames to let it hydrate.
Future<void> settleLoad(WidgetTester tester) async {
for (var i = 0; i < 8; i++) {
await tester.pump(const Duration(milliseconds: 10));
}
}
testWidgets('starts masked (fail-closed) before the preference loads',
(tester) async {
final provider = PrivacyProvider();
// Checked synchronously, before the async load can turn the event loop:
// the provider masks by default until the stored value is known.
expect(provider.hidden, isTrue);
// Let the load settle so the widget tree and any pending work complete.
await tester.pumpWidget(harness(provider));
await settleLoad(tester);
});
testWidgets('net worth is visible after hydration when privacy mode is off',
(tester) async {
await tester.pumpWidget(harness(PrivacyProvider()));
await settleLoad(tester);
expect(find.text(r'$29,669.71'), findsOneWidget);
expect(find.text(r'$••••'), findsNothing);
});
testWidgets('toggling privacy mode masks the net worth', (tester) async {
final privacy = PrivacyProvider();
await tester.pumpWidget(harness(privacy));
await settleLoad(tester);
await privacy.setHidden(true);
await tester.pump();
// The real value is gone, and both amounts the harness renders — the
// net-worth headline and the single USD asset total — collapse to the same
// fixed mask, so exactly two appear.
expect(find.text(r'$29,669.71'), findsNothing);
expect(find.text(r'$••••'), findsNWidgets(2));
});
testWidgets('hidden state persists across provider instances',
(tester) async {
// First provider enables privacy mode, which persists the choice.
final first = PrivacyProvider();
await tester.pumpWidget(harness(first));
await settleLoad(tester);
await first.setHidden(true);
await tester.pump();
// A fresh provider reading the same persisted store loads "hidden" and
// masks from the start.
await tester.pumpWidget(harness(PrivacyProvider()));
await settleLoad(tester);
// Net-worth headline + the single USD asset total both mask.
expect(find.text(r'$29,669.71'), findsNothing);
expect(find.text(r'$••••'), findsNWidgets(2));
});
}