π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Prune low-value test inventories
Manav Rathidf4a2e73c5f2
diff --git a/mobile/apps/auth/test/services/auth_theme_preferences_test.dart b/mobile/apps/auth/test/services/auth_theme_preferences_test.dartindex e2ceeee38b..bad4a5a6d0 100644--- a/mobile/apps/auth/test/services/auth_theme_preferences_test.dart+++ b/mobile/apps/auth/test/services/auth_theme_preferences_test.dart@@ -11,38 +11,26 @@ const _authThemeModeKey = "ente_auth_theme_mode";const _adaptiveThemePrefKey = "adaptive_theme_preferences";void main() {- setUp(() {- SharedPreferencesAsyncPlatform.instance =- InMemorySharedPreferencesAsync.empty();- SharedPreferences.setMockInitialValues({});- });+ setUp(_resetPreferences);test("returns system when no theme preference exists", () async {expect(await AuthThemePreferences.getThemeMode(), ThemeMode.system);});test("reads Auth theme preference using Flutter ThemeMode index", () async {- await _setAuthThemeModeIndex(ThemeMode.system.index);- expect(await AuthThemePreferences.getThemeMode(), ThemeMode.system);-- await _setAuthThemeModeIndex(ThemeMode.light.index);- expect(await AuthThemePreferences.getThemeMode(), ThemeMode.light);-- await _setAuthThemeModeIndex(ThemeMode.dark.index);- expect(await AuthThemePreferences.getThemeMode(), ThemeMode.dark);+ for (final mode in ThemeMode.values) {+ await _setAuthThemeModeIndex(mode.index);+ expect(await AuthThemePreferences.getThemeMode(), mode);+ }});test("persists Auth theme preference using Flutter ThemeMode index",() async {- await AuthThemePreferences.setThemeMode(ThemeMode.system);- expect(await _getAuthThemeModeIndex(), ThemeMode.system.index);-- await AuthThemePreferences.setThemeMode(ThemeMode.light);- expect(await _getAuthThemeModeIndex(), ThemeMode.light.index);-- await AuthThemePreferences.setThemeMode(ThemeMode.dark);- expect(await _getAuthThemeModeIndex(), ThemeMode.dark.index);+ for (final mode in ThemeMode.values) {+ await AuthThemePreferences.setThemeMode(mode);+ expect(await _getAuthThemeModeIndex(), mode.index);+ }},);@@ -72,25 +60,16 @@ void main() {test("converts adaptive theme indices to Flutter ThemeMode indices",() async {- await _setAsyncAdaptiveThemeModeIndex(0);- expect(await AuthThemePreferences.getThemeMode(), ThemeMode.light);- expect(await _getAuthThemeModeIndex(), ThemeMode.light.index);-- SharedPreferencesAsyncPlatform.instance =- InMemorySharedPreferencesAsync.empty();- SharedPreferences.setMockInitialValues({});-- await _setAsyncAdaptiveThemeModeIndex(1);- expect(await AuthThemePreferences.getThemeMode(), ThemeMode.dark);- expect(await _getAuthThemeModeIndex(), ThemeMode.dark.index);-- SharedPreferencesAsyncPlatform.instance =- InMemorySharedPreferencesAsync.empty();- SharedPreferences.setMockInitialValues({});-- await _setAsyncAdaptiveThemeModeIndex(2);- expect(await AuthThemePreferences.getThemeMode(), ThemeMode.system);- expect(await _getAuthThemeModeIndex(), ThemeMode.system.index);+ for (final (adaptiveIndex, mode) in const [+ (0, ThemeMode.light),+ (1, ThemeMode.dark),+ (2, ThemeMode.system),+ ]) {+ _resetPreferences();+ await _setAsyncAdaptiveThemeModeIndex(adaptiveIndex);+ expect(await AuthThemePreferences.getThemeMode(), mode);+ expect(await _getAuthThemeModeIndex(), mode.index);+ }},);@@ -103,6 +82,12 @@ void main() {});}+void _resetPreferences() {+ SharedPreferencesAsyncPlatform.instance =+ InMemorySharedPreferencesAsync.empty();+ SharedPreferences.setMockInitialValues({});+}+Future<void> _setAuthThemeModeIndex(int themeModeIndex) async {final prefs = await SharedPreferences.getInstance();await prefs.setInt(_authThemeModeKey, themeModeIndex);diff --git a/mobile/apps/auth/test/ui/settings/data/import/import_page_test.dart b/mobile/apps/auth/test/ui/settings/data/import/import_page_test.dartdeleted file mode 100644index 0497d126df..0000000000--- a/mobile/apps/auth/test/ui/settings/data/import/import_page_test.dart+++ /dev/null@@ -1,39 +0,0 @@-import 'package:ente_auth/ui/settings/data/import_page.dart';-import 'package:ente_components/ente_components.dart';-import 'package:ente_strings/ente_strings.dart';-import 'package:flutter/material.dart';-import 'package:flutter_test/flutter_test.dart';--void main() {- testWidgets('plain text source opens an Ente instruction sheet', (- tester,- ) async {- await tester.pumpWidget(- MaterialApp(- theme: ComponentTheme.lightTheme(app: ComponentApp.auth),- localizationsDelegates: StringsLocalizations.localizationsDelegates,- supportedLocales: StringsLocalizations.supportedLocales,- home: const ImportCodePage(),- ),- );-- await tester.tap(find.text('Plain text'));- await tester.pumpAndSettle();-- expect(find.text('Select file'), findsOneWidget);- expect(find.byTooltip('Cancel'), findsOneWidget);- expect(- find.byWidgetPredicate(- (widget) =>- widget is Semantics &&- widget.properties.identifier ==- 'auth_import_instruction_plain_text',- ),- findsOneWidget,- );-- await tester.tap(find.byTooltip('Cancel'));- await tester.pumpAndSettle();- expect(find.text('Select file'), findsNothing);- });-}diff --git a/mobile/apps/auth/test/ui/settings/data/import/proton_import_parser_test.dart b/mobile/apps/auth/test/ui/settings/data/import/proton_import_parser_test.dartindex dcc6e3668e..f62fa74e68 100644--- a/mobile/apps/auth/test/ui/settings/data/import/proton_import_parser_test.dart+++ b/mobile/apps/auth/test/ui/settings/data/import/proton_import_parser_test.dart@@ -10,67 +10,29 @@ void main() {test('parses plaintext Proton exports from fixture', () async {final codes = await _loadPlaintextFixtureCodes();- expect(codes, hasLength(4));- _assertCode(- codes[0],- type: Type.totp,- issuer: '.env',- account: '[email protected]',- secret: 'MI4GCOJSGIZTKLJSGMZWKLJUGEZDQLJYG5STILJSMUYDIYTCMQ3TSOJRGI',- algorithm: Algorithm.sha1,- digits: 6,- period: 30,- rawData: _expectedStoredTotpRawData(+ const expectedCodes = <_ExpectedCode>[+ (issuer: '.env',account: '[email protected]',secret: 'MI4GCOJSGIZTKLJSGMZWKLJUGEZDQLJYG5STILJSMUYDIYTCMQ3TSOJRGI',),- );- _assertCode(- codes[1],- type: Type.totp,- issuer: '/e/',- account: '[email protected]',- secret: '554VBDOGJRLDG2JV',- algorithm: Algorithm.sha1,- digits: 6,- period: 30,- rawData: _expectedStoredTotpRawData(- issuer: '/e/',- account: '[email protected]',- secret: '554VBDOGJRLDG2JV',- ),- );- _assertCode(- codes[2],- type: Type.totp,- issuer: 'ente',- account: '[email protected]',- secret: 'PIBTGMBYQYVSLN5PVZYQUTKYHOBRYYT7',- algorithm: Algorithm.sha1,- digits: 6,- period: 30,- rawData: _expectedStoredTotpRawData(+ (issuer: '/e/', account: '[email protected]', secret: '554VBDOGJRLDG2JV'),+ (issuer: 'ente',account: '[email protected]',secret: 'PIBTGMBYQYVSLN5PVZYQUTKYHOBRYYT7',),- );- _assertCode(- codes[3],- type: Type.totp,- issuer: 'reddit',- account: '[email protected]',- secret: 'J4YFC3TZKVYWCVCNIVBWIV2GHFAXUNDF',- algorithm: Algorithm.sha1,- digits: 6,- period: 30,- rawData: _expectedStoredTotpRawData(+ (issuer: 'reddit',account: '[email protected]',secret: 'J4YFC3TZKVYWCVCNIVBWIV2GHFAXUNDF',),- );+ ];++ expect(codes, hasLength(expectedCodes.length));+ for (var index = 0; index < expectedCodes.length; index++) {+ _expectCode(codes[index], expectedCodes[index]);+ }});test('decrypts password protected Proton exports from fixture', () async {@@ -123,25 +85,22 @@ Future<List<Code>> _loadPlaintextFixtureCodes() async {return parseProtonExport(exportJson);}-void _assertCode(- Code code, {- required Type type,- required String issuer,- required String account,- required String secret,- required Algorithm algorithm,- required int digits,- required int period,- required String rawData,-}) {- expect(code.type, type);- expect(code.issuer, issuer);- expect(code.account, account);- expect(code.secret, secret);- expect(code.algorithm, algorithm);- expect(code.digits, digits);- expect(code.period, period);- expect(code.rawData, rawData);+void _expectCode(Code code, _ExpectedCode expected) {+ expect(code.type, Type.totp);+ expect(code.issuer, expected.issuer);+ expect(code.account, expected.account);+ expect(code.secret, expected.secret);+ expect(code.algorithm, Algorithm.sha1);+ expect(code.digits, 6);+ expect(code.period, 30);+ expect(+ code.rawData,+ _expectedStoredTotpRawData(+ issuer: expected.issuer,+ account: expected.account,+ secret: expected.secret,+ ),+ );}File _fixture(String name) =>@@ -163,3 +122,5 @@ String _expectedStoredTotpRawData({final code = Code.fromOTPAuthUrl(otpUrl);return jsonDecode(code.toOTPAuthUrlFormat()) as String;}++typedef _ExpectedCode = ({String issuer, String account, String secret});diff --git a/mobile/apps/auth/test/ui/utils/icon_utils_test.dart b/mobile/apps/auth/test/ui/utils/icon_utils_test.dartindex f2b00726cf..28fec8fc79 100644--- a/mobile/apps/auth/test/ui/utils/icon_utils_test.dart+++ b/mobile/apps/auth/test/ui/utils/icon_utils_test.dart@@ -47,12 +47,6 @@ void main() {final slug = icon['slug']?.toString();final canonicalPath = 'assets/custom-icons/icons/${slug ?? titleKey}.svg';_expectAssetExists(canonicalPath, missingAssets);-- for (final altName- in (icon['altNames'] as List<dynamic>? ?? const <dynamic>[])) {- final altPath = 'assets/custom-icons/icons/${slug ?? titleKey}.svg';- _expectAssetExists('$altPath for alias $altName', missingAssets);- }}expect(missingAssets, isEmpty);@@ -60,8 +54,7 @@ void main() {}void _expectAssetExists(String assetPath, List<String> missingAssets) {- final actualPath = assetPath.split(' for alias ').first;- final asset = File(actualPath);+ final asset = File(assetPath);if (!asset.existsSync()) {missingAssets.add(assetPath);} else if (asset.lengthSync() == 0) {diff --git a/mobile/apps/photos/test/services/memories/photo_selector_test.dart b/mobile/apps/photos/test/services/memories/photo_selector_test.dartindex cbc811aa0e..97568aa7ea 100644--- a/mobile/apps/photos/test/services/memories/photo_selector_test.dart+++ b/mobile/apps/photos/test/services/memories/photo_selector_test.dart@@ -173,71 +173,6 @@ void main() {});group('PhotoSelector.bestSelection (multi year)', () {- test('represents each year', () async {- final memories = <Memory>[];- final embeddings = <EmbeddingVector>[];- int id = 0;- for (final year in [2020, 2021, 2022]) {- for (int i = 0; i < 10; i++) {- final fileID = id++;- memories.add(- _mem(- _file(- uploadedFileID: fileID,- creationTime: _timeInYear(year, hours: i),- ),- ),- );- embeddings.add(_emb(fileID));- }- }- final result = await PhotoSelector.bestSelection(- memories,- isLocalGalleryMode: false,- mlEnabled: true,- fileIdToFaces: {},- faceIDsToPersonID: {},- fileIDToImageEmbedding: _embMap(embeddings),- clipPositiveTextVector: _positiveTextVector,- );- final yearsRepresented = result.map((m) {- return DateTime.fromMicrosecondsSinceEpoch(m.file.creationTime!).year;- }).toSet();- expect(yearsRepresented, contains(2020));- expect(yearsRepresented, contains(2021));- expect(yearsRepresented, contains(2022));- });-- test('adjusts targetSize for many years', () async {- final memories = <Memory>[];- final embeddings = <EmbeddingVector>[];- int id = 0;- for (int year = 2016; year <= 2022; year++) {- for (int i = 0; i < 5; i++) {- final fileID = id++;- memories.add(- _mem(- _file(- uploadedFileID: fileID,- creationTime: _timeInYear(year, hours: i),- ),- ),- );- embeddings.add(_emb(fileID));- }- }- final result = await PhotoSelector.bestSelection(- memories,- isLocalGalleryMode: false,- mlEnabled: true,- fileIdToFaces: {},- faceIDsToPersonID: {},- fileIDToImageEmbedding: _embMap(embeddings),- clipPositiveTextVector: _positiveTextVector,- );- expect(result.length, greaterThan(10));- });-test('still filters close-in-time photos when expanded target matches count',() async {diff --git a/mobile/apps/photos/test/services/rituals_service_test.dart b/mobile/apps/photos/test/services/rituals_service_test.dartindex b5cdbfd3eb..8a6cdc1015 100644--- a/mobile/apps/photos/test/services/rituals_service_test.dart+++ b/mobile/apps/photos/test/services/rituals_service_test.dart@@ -4,82 +4,21 @@ import 'package:photos/services/rituals/rituals_service.dart';void main() {group('RitualsService.currentScheduledStreakFromDayKeys', () {test('keeps streak when today is enabled but incomplete', () {- final service = RitualsService.instance;final todayMidnight = DateTime(2025, 6, 15);- final daysOfWeek = List<bool>.filled(7, true);- final dayKeys = <int>{};-- for (var offset = 1; offset <= 9; offset++) {- dayKeys.add(- DateTime(- todayMidnight.year,- todayMidnight.month,- todayMidnight.day - offset,- ).millisecondsSinceEpoch,- );- }-- final streak = service.currentScheduledStreakFromDayKeys(- dayKeys,- daysOfWeek,- todayMidnight: todayMidnight,- );-- expect(streak, 9);+ expect(_streak(todayMidnight, _offsets(1, 9)), 9);});test('increments streak after completing today', () {- final service = RitualsService.instance;final todayMidnight = DateTime(2025, 6, 15);- final daysOfWeek = List<bool>.filled(7, true);- final dayKeys = <int>{todayMidnight.millisecondsSinceEpoch};-- for (var offset = 1; offset <= 9; offset++) {- dayKeys.add(- DateTime(- todayMidnight.year,- todayMidnight.month,- todayMidnight.day - offset,- ).millisecondsSinceEpoch,- );- }-- final streak = service.currentScheduledStreakFromDayKeys(- dayKeys,- daysOfWeek,- todayMidnight: todayMidnight,- );-- expect(streak, 10);+ expect(_streak(todayMidnight, [0, ..._offsets(1, 9)]), 10);});test('resets streak when a previous enabled day was missed', () {- final service = RitualsService.instance;final todayMidnight = DateTime(2025, 6, 15);- final daysOfWeek = List<bool>.filled(7, true);- final dayKeys = <int>{};-- for (var offset = 2; offset <= 10; offset++) {- dayKeys.add(- DateTime(- todayMidnight.year,- todayMidnight.month,- todayMidnight.day - offset,- ).millisecondsSinceEpoch,- );- }-- final streak = service.currentScheduledStreakFromDayKeys(- dayKeys,- daysOfWeek,- todayMidnight: todayMidnight,- );-- expect(streak, 0);+ expect(_streak(todayMidnight, _offsets(2, 10)), 0);});test('skips disabled days while keeping streak', () {- final service = RitualsService.instance;final todayMidnight = DateTime(2025, 6, 16); // Mondayfinal daysOfWeek = <bool>[false, // Sunday@@ -90,22 +29,28 @@ void main() {true, // Fridayfalse, // Saturday];-- final dayKeys = <int>{- DateTime(2025, 6, 13).millisecondsSinceEpoch, // Friday- DateTime(2025, 6, 12).millisecondsSinceEpoch, // Thursday- DateTime(2025, 6, 11).millisecondsSinceEpoch, // Wednesday- DateTime(2025, 6, 10).millisecondsSinceEpoch, // Tuesday- DateTime(2025, 6, 9).millisecondsSinceEpoch, // Monday- };-- final streak = service.currentScheduledStreakFromDayKeys(- dayKeys,- daysOfWeek,- todayMidnight: todayMidnight,- );-- expect(streak, 5);+ expect(_streak(todayMidnight, _offsets(3, 7), daysOfWeek), 5);});});}++int _streak(DateTime today, List<int> completedOffsets, [List<bool>? days]) {+ final dayKeys = completedOffsets+ .map(+ (offset) => DateTime(+ today.year,+ today.month,+ today.day - offset,+ ).millisecondsSinceEpoch,+ )+ .toSet();+ return RitualsService.instance.currentScheduledStreakFromDayKeys(+ dayKeys,+ days ?? List<bool>.filled(7, true),+ todayMidnight: today,+ );+}++List<int> _offsets(int first, int last) => [+ for (var offset = first; offset <= last; offset++) offset,+];diff --git a/mobile/apps/photos/test/ui/components/buttons/button_widget_test.dart b/mobile/apps/photos/test/ui/components/buttons/button_widget_test.dartindex 5e300f1180..bdfb0fa707 100644--- a/mobile/apps/photos/test/ui/components/buttons/button_widget_test.dart+++ b/mobile/apps/photos/test/ui/components/buttons/button_widget_test.dart@@ -5,7 +5,6 @@ import "package:ente_strings/ente_strings.dart";import "package:photos/models/button_result.dart";import "package:photos/ui/components/buttons/button_widget.dart";import "package:photos/ui/components/models/button_type.dart";-import "package:photos/utils/dialog_util.dart";void main() {group("ButtonWidget", () {@@ -47,46 +46,6 @@ void main() {expect(result, isNull);expect(find.text("Cancel"), findsOneWidget);});-- testWidgets("action sheet buttons return their selected action", (- tester,- ) async {- ButtonResult? result;-- await tester.pumpWidget(- MaterialApp(- theme: darkThemeData,- localizationsDelegates: StringsLocalizations.localizationsDelegates,- supportedLocales: StringsLocalizations.supportedLocales,- home: Builder(- builder: (context) {- return Scaffold(- body: TextButton(- onPressed: () async {- result = await showChoiceActionSheet(- context,- title: "Clean Uncategorized",- body: "Remove duplicate album entries",- firstButtonLabel: "Confirm",- );- },- child: const Text("Open sheet"),- ),- );- },- ),- ),- );-- await tester.tap(find.text("Open sheet"));- await tester.pumpAndSettle();-- await tester.tap(find.text("Confirm"));- await tester.pumpAndSettle();-- expect(result?.action, ButtonAction.first);- expect(find.text("Open sheet"), findsOneWidget);- });});}diff --git a/mobile/apps/photos/test/ui/family/family_dashboard_test.dart b/mobile/apps/photos/test/ui/family/family_dashboard_test.dartindex f67ecb5e1e..7c39f050fd 100644--- a/mobile/apps/photos/test/ui/family/family_dashboard_test.dart+++ b/mobile/apps/photos/test/ui/family/family_dashboard_test.dart@@ -2,7 +2,6 @@ import 'package:ente_components/ente_components.dart';import 'package:ente_contacts/contacts.dart' as contacts;import 'package:flutter/material.dart';import 'package:flutter_test/flutter_test.dart';-import 'package:hugeicons/hugeicons.dart';import 'package:photos/ente_theme_data.dart';import 'package:photos/gateways/billing/models/subscription.dart';import 'package:photos/gateways/storage_bonus/models/bonus.dart';@@ -10,7 +9,6 @@ import 'package:ente_strings/ente_strings.dart';import 'package:photos/models/user_details.dart';import 'package:photos/ui/family/family_dashboard.dart';import 'package:photos/ui/viewer/people/person_face_widget.dart';-import 'package:photos/utils/avatar_util.dart';void main() {testWidgets(@@ -74,50 +72,6 @@ void main() {expect(find.text('Saved member'), findsNWidgets(2));expect(find.text('[email protected]'), findsOneWidget);expect(find.textContaining('5 albums shared'), findsOneWidget);- final avatars = tester- .widgetList<AvatarComponent>(find.byType(AvatarComponent))- .where((avatar) => avatar.image == null)- .toList();- expect(avatars, hasLength(3));- expect(- avatars.map((avatar) => avatar.color),- everyElement(- isIn(const [- AvatarComponentColor.yellow,- AvatarComponentColor.green,- AvatarComponentColor.orange,- AvatarComponentColor.pink,- AvatarComponentColor.purple,- AvatarComponentColor.blue,- AvatarComponentColor.cyan,- AvatarComponentColor.black,- ]),- ),- );- expect(avatars.map((avatar) => avatar.seed), everyElement(isNull));- final currentUserAvatar = avatars.singleWhere(- (avatar) => avatar.semanticLabel == 'Current user',- );- expect(currentUserAvatar.color, isIn(avatarComponentIdentityPalette));- final savedMemberAvatar = avatars.singleWhere(- (avatar) => avatar.semanticLabel == 'Saved member',- );- expect(savedMemberAvatar.initials, 'SM');- expect(- savedMemberAvatar.color,- avatarComponentColorForIdentity(- avatarIdentityKey(- email: savedMember.email,- userID: savedMember.userID,- ),- ),- );- final crown = tester- .widgetList<HugeIcon>(find.byType(HugeIcon))- .singleWhere(- (icon) => identical(icon.icon, HugeIcons.strokeRoundedCrown02),- );- expect(crown.icon, HugeIcons.strokeRoundedCrown02);expect(find.bySemanticsLabel(RegExp(r'Admin')), findsOneWidget);semantics.dispose();@@ -163,26 +117,6 @@ void main() {find.byType(PersonFaceWidget),);expect(personAvatar.personId, 'person-42');- final ringFinder = find.ancestor(- of: find.byType(PersonFaceWidget),- matching: find.byWidgetPredicate(- (widget) =>- widget is DecoratedBox &&- widget.position == DecorationPosition.foreground &&- widget.decoration is BoxDecoration &&- (widget.decoration as BoxDecoration).shape == BoxShape.circle,- ),- );- expect(ringFinder, findsOneWidget);- final ring = tester.widget<DecoratedBox>(ringFinder);- final border = (ring.decoration as BoxDecoration).border! as Border;- expect(- border.top.color,- avatarComponentColorValue(- tester.element(find.byType(PersonFaceWidget)),- familyMemberAvatarComponentColor(member),- ),- );await tester.tap(find.byType(MenuComponent));expect(selectedDisplayName, 'Current person');diff --git a/mobile/apps/photos/test/utils/date_query_parsing_test.dart b/mobile/apps/photos/test/utils/date_query_parsing_test.dartindex 26495a0b3a..a4935177c0 100644--- a/mobile/apps/photos/test/utils/date_query_parsing_test.dart+++ b/mobile/apps/photos/test/utils/date_query_parsing_test.dart@@ -2,314 +2,57 @@ import 'package:photos/services/date_parse_service.dart';import 'package:test/test.dart';void main() {- final DateParseService dateParseService = DateParseService.instance;-- group('Natural Language Date Parsing', () {- test('should parse "today" correctly', () {- final DateTime now = DateTime.now();- final PartialDate expectedDate = PartialDate(- day: now.day,- month: now.month,- year: now.year,- );- final PartialDate parsedDate = dateParseService.parse('today');-- expect(- parsedDate.day,- expectedDate.day,- reason: 'Day mismatch for today',- );- expect(- parsedDate.month,- expectedDate.month,- reason: 'Month mismatch for today',- );- expect(- parsedDate.year,- expectedDate.year,- reason: 'Year mismatch for today',- );- });-- test('should parse "tomorrow" correctly', () {- final DateTime tomorrow = DateTime.now().add(const Duration(days: 1));- final PartialDate expectedDate = PartialDate(- day: tomorrow.day,- month: tomorrow.month,- year: tomorrow.year,- );- final PartialDate parsedDate = dateParseService.parse('tomorrow');-- expect(- parsedDate.day,- expectedDate.day,- reason: 'Day mismatch for tomorrow',- );- expect(- parsedDate.month,- expectedDate.month,- reason: 'Month mismatch for tomorrow',- );- expect(- parsedDate.year,- expectedDate.year,- reason: 'Year mismatch for tomorrow',- );- });-- test('should parse "yesterday" correctly', () {- final DateTime yesterday = DateTime.now().subtract(- const Duration(days: 1),- );- final PartialDate expectedDate = PartialDate(- day: yesterday.day,- month: yesterday.month,- year: yesterday.year,- );- final PartialDate parsedDate = dateParseService.parse('yesterday');-- expect(- parsedDate.day,- expectedDate.day,- reason: 'Day mismatch for yesterday',- );- expect(- parsedDate.month,- expectedDate.month,- reason: 'Month mismatch for yesterday',- );- expect(- parsedDate.year,- expectedDate.year,- reason: 'Year mismatch for yesterday',- );- });-- test('should parse full month name "February 2025"', () {- final PartialDate parsedDate = dateParseService.parse('February 2025');- expect(parsedDate.day, isNull);- expect(parsedDate.month, 2);- expect(parsedDate.year, 2025);- });-- test('should parse abbreviated month name "Feb 2025"', () {- final PartialDate parsedDate = dateParseService.parse('Feb 2025');- expect(parsedDate.day, isNull);- expect(parsedDate.month, 2);- expect(parsedDate.year, 2025);- });-- test('should parse partial month-year "03-2024"', () {- final PartialDate parsedDate = dateParseService.parse('03-2024');- expect(parsedDate.day, isNull);- expect(parsedDate.month, 3);- expect(parsedDate.year, 2024);- });-- test('should parse partial month/year "03/2025"', () {- final PartialDate parsedDate = dateParseService.parse('03/2025');- expect(parsedDate.day, isNull);- expect(parsedDate.month, 3);- expect(parsedDate.year, 2025);- });-- test('should parse partial month name "Febr 2025"', () {- final PartialDate parsedDate = dateParseService.parse('Febr 2025');- expect(parsedDate.day, isNull);- expect(parsedDate.month, 2);- expect(parsedDate.year, 2025);- });-- test('should parse ordinal number "25th Jan 2024"', () {- final PartialDate parsedDate = dateParseService.parse('25th Jan 2024');- expect(parsedDate.day, 25);- expect(parsedDate.month, 1);- expect(parsedDate.year, 2024);- });-- test('should parse ordinal number "22nd Feb"', () {- final PartialDate parsedDate = dateParseService.parse('22nd Feb');- expect(parsedDate.day, 22);- expect(parsedDate.month, 2);- expect(parsedDate.year, isNull);- });-- test('should parse ordinal number dd mm format "23 03"', () {- final PartialDate parsedDate = dateParseService.parse('23 03');- expect(parsedDate.day, 23);- expect(parsedDate.month, 3);- expect(parsedDate.year, isNull);- });-- test('should parse ordinal number "24 04 2024"', () {- final PartialDate parsedDate = dateParseService.parse('24 04 2024');- expect(parsedDate.day, 24);- expect(parsedDate.month, 4);- expect(parsedDate.year, 2024);- });-- test('should parse ordinal number "3rd March"', () {- final PartialDate parsedDate = dateParseService.parse('3rd March');- expect(parsedDate.day, 3);- expect(parsedDate.month, 3);- expect(parsedDate.year, isNull);- });-- test('should parse "25th Feb" (generic date)', () {- final PartialDate parsedDate = dateParseService.parse('25th Feb');- expect(parsedDate.day, 25);- expect(parsedDate.month, 2);- expect(parsedDate.year, isNull);- });-- test('should parse "25th of February 2025"', () {- final PartialDate parsedDate = dateParseService.parse(- '25th of February 2025',- );- expect(parsedDate.day, 25);- expect(parsedDate.month, 2);- expect(parsedDate.year, 2025);- });- });-- group('Structured Date Format Support', () {- test('should parse ISO format "2025-02-25"', () {- final PartialDate parsedDate = dateParseService.parse('2025-02-25');- expect(parsedDate.day, 25);- expect(parsedDate.month, 2);- expect(parsedDate.year, 2025);- });-- test('should parse ISO format "2025/02/25"', () {- final PartialDate parsedDate = dateParseService.parse('2025/02/25');- expect(parsedDate.day, 25);- expect(parsedDate.month, 2);- expect(parsedDate.year, 2025);- });-- test('should parse standard MM/DD/YYYY format "02/25/2025"', () {- final PartialDate parsedDate = dateParseService.parse('02/25/2025');- expect(parsedDate.day, 25);- expect(parsedDate.month, 2);- expect(parsedDate.year, 2025);- });-- test('should parse standard DD/MM/YYYY format "25/02/2025"', () {- final PartialDate parsedDate = dateParseService.parse('25/02/2025');- expect(parsedDate.day, 25);- expect(parsedDate.month, 2);- expect(parsedDate.year, 2025);- });-- test('should parse ambiguous "01/02/2024" as DD/MM/YYYY (Feb 1)', () {- final PartialDate parsedDate = dateParseService.parse('01/02/2024');- expect(parsedDate.day, 1);- expect(parsedDate.month, 2);- expect(parsedDate.year, 2024);- });-- test('should parse dot notation "25.02.2025"', () {- final PartialDate parsedDate = dateParseService.parse('25.02.2025');- expect(parsedDate.day, 25);- expect(parsedDate.month, 2);- expect(parsedDate.year, 2025);- });-- test('should parse dot notation with two-digit year "25.02.25"', () {- final PartialDate parsedDate = dateParseService.parse('25.02.25');- expect(parsedDate.day, 25);- expect(parsedDate.month, 2);- expect(parsedDate.year, 2025);- });-- test('should parse compact format "20250225"', () {- final PartialDate parsedDate = dateParseService.parse('20250225');- expect(parsedDate.day, 25);- expect(parsedDate.month, 2);- expect(parsedDate.year, 2025);- });-- test(- 'should parse short MM/DD format "02/25" (no year, handled by tokenized)',- () {- final PartialDate parsedDate = dateParseService.parse('02/25');- expect(parsedDate.day, 25);- expect(parsedDate.month, 2);- expect(parsedDate.year, isNull);- },- );-- test(- 'should parse short DD/MM format "25/02" (no year, handled by tokenized)',- () {- final PartialDate parsedDate = dateParseService.parse('25/02');- expect(parsedDate.day, 25);- expect(parsedDate.month, 2);- expect(parsedDate.year, isNull);- },- );-- test('should parse two-digit year "25/02/25"', () {- final PartialDate parsedDate = dateParseService.parse('25/02/25');- expect(parsedDate.day, 25);- expect(parsedDate.month, 2);- expect(parsedDate.year, 2025);- });-- test('should parse two-digit year "01/01/01" as 2001', () {- final PartialDate parsedDate = dateParseService.parse('01/01/01');- expect(parsedDate.day, 1);- expect(parsedDate.month, 1);- expect(parsedDate.year, 2001);- });-- test('should parse two-digit year "01/01/99" as 1999', () {- final PartialDate parsedDate = dateParseService.parse('01/01/99');- expect(parsedDate.day, 1);- expect(parsedDate.month, 1);- expect(parsedDate.year, 1999);- });- });-- group('Smart Query Types', () {- test('should parse year-only query "2025"', () {- final PartialDate parsedDate = dateParseService.parse('2025');- expect(parsedDate.day, isNull);- expect(parsedDate.month, isNull);- expect(parsedDate.year, 2025);- });- });-- group('Invalid Date Queries', () {- test(- 'should parse "February 30000" as month-only (invalid year ignored)',- () {- final PartialDate parsedDate = dateParseService.parse('February 30000');- expect(parsedDate.day, isNull);- expect(parsedDate.month, 2);+ final parse = DateParseService.instance.parse;++ group('relative dates', () {+ for (final (query, offset) in [+ ('today', 0),+ ('tomorrow', 1),+ ('yesterday', -1),+ ]) {+ test(query, () {+ final date = DateTime.now().add(Duration(days: offset));expect(- parsedDate.year,- isNull,- reason: 'Year 30000 is out of range and should be ignored',+ parse(query),+ PartialDate(day: date.day, month: date.month, year: date.year),);- },- );-- test('should return null for invalid day/month in tokenized parsing', () {- final PartialDate parsedDate = dateParseService.parse('32 Jan 2024');- expect(parsedDate.day, isNull, reason: 'Day should be null for 32');- expect(parsedDate.month, 1);- expect(parsedDate.year, 2024);-- final PartialDate parsedDate2 = dateParseService.parse('Jan 13 2024');- expect(parsedDate2.day, 13);- expect(parsedDate2.month, 1);- expect(parsedDate2.year, 2024);+ });+ }+ });- final PartialDate parsedDate3 = dateParseService.parse('Feb 0 2024');- expect(parsedDate3.day, isNull, reason: 'Day should be null for 0');- expect(parsedDate3.month, 2);- expect(parsedDate3.year, 2024);- });+ group('fixed dates', () {+ for (final (query, expected) in const [+ ('February 2025', PartialDate(month: 2, year: 2025)),+ ('Feb 2025', PartialDate(month: 2, year: 2025)),+ ('03-2024', PartialDate(month: 3, year: 2024)),+ ('03/2025', PartialDate(month: 3, year: 2025)),+ ('Febr 2025', PartialDate(month: 2, year: 2025)),+ ('25th Jan 2024', PartialDate(day: 25, month: 1, year: 2024)),+ ('22nd Feb', PartialDate(day: 22, month: 2)),+ ('23 03', PartialDate(day: 23, month: 3)),+ ('24 04 2024', PartialDate(day: 24, month: 4, year: 2024)),+ ('3rd March', PartialDate(day: 3, month: 3)),+ ('25th of February 2025', PartialDate(day: 25, month: 2, year: 2025)),+ ('2025-02-25', PartialDate(day: 25, month: 2, year: 2025)),+ ('2025/02/25', PartialDate(day: 25, month: 2, year: 2025)),+ ('02/25/2025', PartialDate(day: 25, month: 2, year: 2025)),+ ('25/02/2025', PartialDate(day: 25, month: 2, year: 2025)),+ ('01/02/2024', PartialDate(day: 1, month: 2, year: 2024)),+ ('25.02.2025', PartialDate(day: 25, month: 2, year: 2025)),+ ('25.02.25', PartialDate(day: 25, month: 2, year: 2025)),+ ('20250225', PartialDate(day: 25, month: 2, year: 2025)),+ ('02/25', PartialDate(day: 25, month: 2)),+ ('25/02', PartialDate(day: 25, month: 2)),+ ('25/02/25', PartialDate(day: 25, month: 2, year: 2025)),+ ('01/01/01', PartialDate(day: 1, month: 1, year: 2001)),+ ('01/01/99', PartialDate(day: 1, month: 1, year: 1999)),+ ('2025', PartialDate(year: 2025)),+ ('February 30000', PartialDate(month: 2)),+ ('32 Jan 2024', PartialDate(month: 1, year: 2024)),+ ('Jan 13 2024', PartialDate(day: 13, month: 1, year: 2024)),+ ('Feb 0 2024', PartialDate(month: 2, year: 2024)),+ ]) {+ test(query, () => expect(parse(query), expected));+ }});}diff --git a/mobile/apps/photos/test/utils/exif_util_test.dart b/mobile/apps/photos/test/utils/exif_util_test.dartindex 96b18062e4..db1e4b7093 100644--- a/mobile/apps/photos/test/utils/exif_util_test.dart+++ b/mobile/apps/photos/test/utils/exif_util_test.dart@@ -4,245 +4,179 @@ import "package:test/test.dart";void main() {group("getDateTimeInDeviceTimezone", () {- test("parses standard EXIF date time", () {- final parsed = getDateTimeInDeviceTimezone("2025:01:30 08:59:50", null);-- expect(parsed.dateTime, "2025-01-30T08:59:50.000");- expect(parsed.offsetTime, isNull);- expect(parsed.time.year, 2025);- expect(parsed.time.month, 1);- expect(parsed.time.day, 30);- expect(parsed.time.hour, 8);- expect(parsed.time.minute, 59);- expect(parsed.time.second, 50);- });-- test("parses standard EXIF date time with fractional seconds", () {- final parsed = getDateTimeInDeviceTimezone(+ for (final (name, input, offset, dateTime, offsetTime, time) in [+ (+ "standard EXIF date time",+ "2025:01:30 08:59:50",+ null,+ "2025-01-30T08:59:50.000",+ null,+ DateTime(2025, 1, 30, 8, 59, 50),+ ),+ (+ "fractional EXIF seconds","2026:04:01 15:25:27.945",null,- );-- expect(parsed.dateTime, "2026-04-01T15:25:27.945");- expect(parsed.offsetTime, isNull);- expect(parsed.time, DateTime(2026, 4, 1, 15, 25, 27, 945));- });-- test("parses standard EXIF date time with separate offset", () {- final parsed = getDateTimeInDeviceTimezone(+ "2026-04-01T15:25:27.945",+ null,+ DateTime(2026, 4, 1, 15, 25, 27, 945),+ ),+ (+ "separate EXIF offset","2025:01:30 08:59:50","+01:00",- );-- expect(parsed.dateTime, "2025-01-30T08:59:50.000");- expect(parsed.offsetTime, "+01:00");- expect(parsed.time.toUtc(), DateTime.utc(2025, 1, 30, 7, 59, 50));- });-- test("parses standard EXIF date time with compact separate offset", () {- final parsed = getDateTimeInDeviceTimezone(+ "2025-01-30T08:59:50.000",+ "+01:00",+ DateTime.utc(2025, 1, 30, 7, 59, 50),+ ),+ (+ "compact separate EXIF offset","2025:01:30 08:59:50","+0530",- );-- expect(parsed.dateTime, "2025-01-30T08:59:50.000");- expect(parsed.offsetTime, "+05:30");- expect(parsed.time.toUtc(), DateTime.utc(2025, 1, 30, 3, 29, 50));- });-- test("drops invalid separate offset for standard EXIF date time", () {- final parsed = getDateTimeInDeviceTimezone(+ "2025-01-30T08:59:50.000",+ "+05:30",+ DateTime.utc(2025, 1, 30, 3, 29, 50),+ ),+ (+ "invalid separate EXIF offset","2025:01:30 08:59:50"," : ",- );-- expect(parsed.dateTime, "2025-01-30T08:59:50.000");- expect(parsed.offsetTime, isNull);- expect(parsed.time, DateTime(2025, 1, 30, 8, 59, 50));- });-- test("drops invalid separate offset for fractional EXIF date time", () {- final parsed = getDateTimeInDeviceTimezone(+ "2025-01-30T08:59:50.000",+ null,+ DateTime(2025, 1, 30, 8, 59, 50),+ ),+ (+ "invalid fractional EXIF offset","2026:04:01 15:25:27.945","CDT",- );-- expect(parsed.dateTime, "2026-04-01T15:25:27.945");- expect(parsed.offsetTime, isNull);- expect(parsed.time, DateTime(2026, 4, 1, 15, 25, 27, 945));- });-- test("parses ISO date time with numeric offset", () {- final parsed = getDateTimeInDeviceTimezone(+ "2026-04-01T15:25:27.945",+ null,+ DateTime(2026, 4, 1, 15, 25, 27, 945),+ ),+ (+ "ISO numeric offset","2025-01-30T08:59:50+01:00",null,- );-- expect(parsed.dateTime, "2025-01-30T08:59:50.000");- expect(parsed.offsetTime, "+01:00");- expect(parsed.time.toUtc(), DateTime.utc(2025, 1, 30, 7, 59, 50));- });-- test("parses ISO date time with compact numeric offset", () {- final parsed = getDateTimeInDeviceTimezone(+ "2025-01-30T08:59:50.000",+ "+01:00",+ DateTime.utc(2025, 1, 30, 7, 59, 50),+ ),+ (+ "ISO compact numeric offset","2025-01-30T08:59:50+0530",null,- );-- expect(parsed.dateTime, "2025-01-30T08:59:50.000");- expect(parsed.offsetTime, "+05:30");- expect(parsed.time.toUtc(), DateTime.utc(2025, 1, 30, 3, 29, 50));- });-- test("parses ISO date time with half-hour numeric offset", () {- final parsed = getDateTimeInDeviceTimezone(+ "2025-01-30T08:59:50.000",+ "+05:30",+ DateTime.utc(2025, 1, 30, 3, 29, 50),+ ),+ (+ "ISO half-hour offset","2024-04-01T19:17:29+05:30",null,- );-- expect(parsed.dateTime, "2024-04-01T19:17:29.000");- expect(parsed.offsetTime, "+05:30");- expect(parsed.time.toUtc(), DateTime.utc(2024, 4, 1, 13, 47, 29));- });-- test("parses ISO date time with separate numeric offset", () {- final parsed = getDateTimeInDeviceTimezone(+ "2024-04-01T19:17:29.000",+ "+05:30",+ DateTime.utc(2024, 4, 1, 13, 47, 29),+ ),+ (+ "ISO separate numeric offset","2025-01-30T08:59:50","+01:00",- );-- expect(parsed.dateTime, "2025-01-30T08:59:50.000");- expect(parsed.offsetTime, "+01:00");- expect(parsed.time.toUtc(), DateTime.utc(2025, 1, 30, 7, 59, 50));- });-- test("parses ISO date time with compact separate numeric offset", () {- final parsed = getDateTimeInDeviceTimezone(+ "2025-01-30T08:59:50.000",+ "+01:00",+ DateTime.utc(2025, 1, 30, 7, 59, 50),+ ),+ (+ "ISO compact separate numeric offset","2025-01-30T08:59:50","+0530",- );-- expect(parsed.dateTime, "2025-01-30T08:59:50.000");- expect(parsed.offsetTime, "+05:30");- expect(parsed.time.toUtc(), DateTime.utc(2025, 1, 30, 3, 29, 50));- });-- test("drops invalid separate offset for ISO date time", () {- final parsed = getDateTimeInDeviceTimezone("2025-01-30T08:59:50", "CDT");-- expect(parsed.dateTime, "2025-01-30T08:59:50.000");- expect(parsed.offsetTime, isNull);- expect(parsed.time, DateTime(2025, 1, 30, 8, 59, 50));- });-- test("parses ISO date time with Z offset", () {- final parsed = getDateTimeInDeviceTimezone("2026-04-20T00:00:00Z", null);-- expect(parsed.dateTime, "2026-04-20T00:00:00.000");- expect(parsed.offsetTime, "Z");- expect(parsed.time.toUtc(), DateTime.utc(2026, 4, 20));- });-- test("parses ISO date time with space separator and no offset", () {- final parsed = getDateTimeInDeviceTimezone("2025-11-12 15:12:01", null);-- expect(parsed.dateTime, "2025-11-12T15:12:01.000");- expect(parsed.offsetTime, isNull);- expect(parsed.time.year, 2025);- expect(parsed.time.month, 11);- expect(parsed.time.day, 12);- expect(parsed.time.hour, 15);- expect(parsed.time.minute, 12);- expect(parsed.time.second, 1);- expect(parsed.time.isUtc, isFalse);- });-- test("parses date time with colon-separated milliseconds", () {- final parsed = getDateTimeInDeviceTimezone(+ "2025-01-30T08:59:50.000",+ "+05:30",+ DateTime.utc(2025, 1, 30, 3, 29, 50),+ ),+ (+ "invalid separate ISO offset",+ "2025-01-30T08:59:50",+ "CDT",+ "2025-01-30T08:59:50.000",+ null,+ DateTime(2025, 1, 30, 8, 59, 50),+ ),+ (+ "ISO Z offset",+ "2026-04-20T00:00:00Z",+ null,+ "2026-04-20T00:00:00.000",+ "Z",+ DateTime.utc(2026, 4, 20),+ ),+ (+ "ISO space separator",+ "2025-11-12 15:12:01",+ null,+ "2025-11-12T15:12:01.000",+ null,+ DateTime(2025, 11, 12, 15, 12, 1),+ ),+ (+ "colon-separated milliseconds","2019-11-28 14:38:40:794",null,- );-- expect(parsed.dateTime, "2019-11-28T14:38:40.794");- expect(parsed.offsetTime, isNull);- expect(parsed.time.year, 2019);- expect(parsed.time.month, 11);- expect(parsed.time.day, 28);- expect(parsed.time.hour, 14);- expect(parsed.time.minute, 38);- expect(parsed.time.second, 40);- expect(parsed.time.millisecond, 794);- });-- test("does not guess timezone abbreviations", () {- expect(- () => getDateTimeInDeviceTimezone("2024-09-07T16:29:28CDT", null),- throwsFormatException,- );- });-- test("rejects trailing data in standard EXIF date time", () {- expect(- () => getDateTimeInDeviceTimezone("2024:09:07 16:29:28CDT", null),- throwsFormatException,- );- expect(- () => getDateTimeInDeviceTimezone("2024:09:07 16:29:28+05:30", null),- throwsFormatException,- );- });+ "2019-11-28T14:38:40.794",+ null,+ DateTime(2019, 11, 28, 14, 38, 40, 794),+ ),+ ]) {+ test(name, () {+ final parsed = getDateTimeInDeviceTimezone(input, offset);++ expect(parsed.dateTime, dateTime);+ expect(parsed.offsetTime, offsetTime);+ expect(time.isUtc ? parsed.time.toUtc() : parsed.time, time);+ });+ }++ for (final input in [+ "2024-09-07T16:29:28CDT",+ "2024:09:07 16:29:28CDT",+ "2024:09:07 16:29:28+05:30",+ "2025:02:30 08:00:00.945",+ "2025-02-30T08:00:00Z",+ "2025-01-30T24:00:00+01:00",+ "2025-01-30T08:00:00+99:99",+ ]) {+ test("rejects $input", () {+ expect(+ () => getDateTimeInDeviceTimezone(input, null),+ throwsFormatException,+ );+ });+ }+ });- test("rejects invalid standard EXIF date time components", () {- expect(- () => getDateTimeInDeviceTimezone("2025:02:30 08:00:00.945", null),- throwsFormatException,- );+ test("ignores invalid date values from file metadata", () async {+ final parsed = await tryParseExifDateTime(null, {+ kDateTimeOriginal: _ifdTag(+ const IfdNone(),+ printable: "2025:12:13 14:24:60",+ ),});- test("rejects invalid ISO date time components", () {- expect(- () => getDateTimeInDeviceTimezone("2025-02-30T08:00:00Z", null),- throwsFormatException,- );- expect(- () => getDateTimeInDeviceTimezone("2025-01-30T24:00:00+01:00", null),- throwsFormatException,- );- expect(- () => getDateTimeInDeviceTimezone("2025-01-30T08:00:00+99:99", null),- throwsFormatException,- );- });+ expect(parsed, isNull);});- group("tryParseExifDateTime", () {- test("ignores invalid date values from file metadata", () async {- final parsed = await tryParseExifDateTime(null, {- kDateTimeOriginal: _ifdTag(- const IfdNone(),- printable: "2025:12:13 14:24:60",- ),- });-- expect(parsed, isNull);+ test("parses integer GPS coordinate parts", () {+ final gpsData = gpsDataFromExif({+ "GPS GPSLatitude": _ifdTag(const IfdInts([40, 26, 46])),+ "GPS GPSLatitudeRef": _ifdTag(const IfdInts([0]), printable: "N"),+ "GPS GPSLongitude": _ifdTag(const IfdInts([79, 58, 56])),+ "GPS GPSLongitudeRef": _ifdTag(const IfdInts([0]), printable: "W"),});- });-- group("gpsDataFromExif", () {- test("parses integer GPS coordinate parts", () {- final gpsData = gpsDataFromExif({- "GPS GPSLatitude": _ifdTag(const IfdInts([40, 26, 46])),- "GPS GPSLatitudeRef": _ifdTag(const IfdInts([0]), printable: "N"),- "GPS GPSLongitude": _ifdTag(const IfdInts([79, 58, 56])),- "GPS GPSLongitudeRef": _ifdTag(const IfdInts([0]), printable: "W"),- });- final location = gpsData.toLocationObj();+ final location = gpsData.toLocationObj();- expect(location, isNotNull);- expect(location!.latitude, closeTo(40.446111, 0.000001));- expect(location.longitude, closeTo(-79.982222, 0.000001));- });+ expect(location, isNotNull);+ expect(location!.latitude, closeTo(40.446111, 0.000001));+ expect(location.longitude, closeTo(-79.982222, 0.000001));});}diff --git a/mobile/apps/photos/test/utils/parsing_loc_from_exif_test.dart b/mobile/apps/photos/test/utils/parsing_loc_from_exif_test.dartindex 51e8870c40..93ac486eaa 100644--- a/mobile/apps/photos/test/utils/parsing_loc_from_exif_test.dart+++ b/mobile/apps/photos/test/utils/parsing_loc_from_exif_test.dart@@ -3,122 +3,107 @@ import "package:test/test.dart";void main() {group('toLocationObj', () {- test('returns null if lat or long are null', () {- final gpsData = GPSData(null, null, null, null);- expect(gpsData.toLocationObj(), isNull);-- final gpsDataWithLatOnly = GPSData(null, [1, 2, 3], null, null);- expect(gpsDataWithLatOnly.toLocationObj(), isNull);-- final gpsDataWithLongOnly = GPSData(null, null, null, [1, 2, 3]);- expect(gpsDataWithLongOnly.toLocationObj(), isNull);+ test('rejects incomplete coordinates and invalid references', () {+ for (final gpsData in [+ GPSData(null, null, null, null),+ GPSData(null, [1, 2, 3], null, null),+ GPSData(null, null, null, [1, 2, 3]),+ GPSData(null, [1, 2], null, [1, 2, 3]),+ GPSData(null, [1, 2, 3], null, [1, 2]),+ GPSData(null, [1, 2], null, [1, 2]),+ GPSData("A", [1, 2, 3], "xyz", [1, 2, 3]),+ ]) {+ expect(gpsData.toLocationObj(), isNull);+ }});- test('returns null if lat or long have less than 3 elements', () {- final gpsData1 = GPSData(null, [1, 2], null, [1, 2, 3]);- expect(gpsData1.toLocationObj(), isNull);-- final gpsData2 = GPSData(null, [1, 2, 3], null, [1, 2]);- expect(gpsData2.toLocationObj(), isNull);-- final gpsData3 = GPSData(null, [1, 2], null, [1, 2]);- expect(gpsData3.toLocationObj(), isNull);- });+ for (final (name, latRef, lat, longRef, long, expectedLat, expectedLong)+ in const [+ (+ 'north east',+ 'N',+ [40.0, 26.0, 46.84],+ 'E',+ [79.0, 58.0, 56.33],+ 40.446344,+ 79.982313,+ ),+ (+ 'north west',+ 'N',+ [40.0, 26.0, 46.84],+ 'W',+ [79.0, 58.0, 56.33],+ 40.446344,+ -79.982313,+ ),+ (+ 'south east',+ 'S',+ [40.0, 26.0, 46.84],+ 'E',+ [79.0, 58.0, 56.33],+ -40.446344,+ 79.982313,+ ),+ (+ 'south west',+ 'S',+ [40.0, 26.0, 46.84],+ 'W',+ [79.0, 58.0, 56.33],+ -40.446344,+ -79.982313,+ ),+ (+ 'unsigned without references',+ null,+ [40.0, 26.0, 46.84],+ null,+ [79.0, 58.0, 56.33],+ 40.446344,+ 79.982313,+ ),+ (+ 'negative latitude without references',+ null,+ [-40.0, 26.0, 46.84],+ null,+ [79.0, 58.0, 56.33],+ -40.446344,+ 79.982313,+ ),+ (+ 'negative longitude without references',+ null,+ [40.0, 26.0, 46.84],+ null,+ [-79.0, 58.0, 56.33],+ 40.446344,+ -79.982313,+ ),+ (+ 'negative minutes without references',+ null,+ [40.0, -26.0, 46.84],+ null,+ [79.0, -58.0, 56.33],+ -40.446344,+ -79.982313,+ ),+ ]) {+ test(name, () {+ final location = GPSData(+ latRef,+ [...lat],+ longRef,+ [...long],+ ).toLocationObj();- test('returns null if latRef or longRef is of invalid format', () {- final gpsData1 = GPSData("A", [1, 2, 3], "xyz", [1, 2, 3]);- expect(gpsData1.toLocationObj(), isNull);- });-- void testParsingLocation(- String? latRef,- List<double> lat,- String? longRef,- List<double> long,- double expectedLat,- double expectedLong,- ) {- final gpsData = GPSData(latRef, lat, longRef, long);- final location = gpsData.toLocationObj();- expect(location, isNotNull);- expect(location!.latitude, closeTo(expectedLat, 0.00001));- expect(location.longitude, closeTo(expectedLong, 0.00001));+ expect(location, isNotNull);+ expect(location!.latitude, closeTo(expectedLat, 0.00001));+ expect(location.longitude, closeTo(expectedLong, 0.00001));+ });}-- test(- 'converts coordinates with different latRef and longRef combinations',- () {- testParsingLocation(- "N",- [40, 26, 46.84],- "E",- [79, 58, 56.33],- 40.446344,- 79.982313,- );- testParsingLocation(- "N",- [40, 26, 46.84],- "W",- [79, 58, 56.33],- 40.446344,- -79.982313,- );- testParsingLocation(- "S",- [40, 26, 46.84],- "E",- [79, 58, 56.33],- -40.446344,- 79.982313,- );- testParsingLocation(- "S",- [40, 26, 46.84],- "W",- [79, 58, 56.33],- -40.446344,- -79.982313,- );- },- );-- test(- 'converts coordinates with missing latRef and longRef but with signed lat and long',- () {- testParsingLocation(- null,- [40, 26, 46.84],- null,- [79, 58, 56.33],- 40.446344,- 79.982313,- );- testParsingLocation(- null,- [-40, 26, 46.84],- null,- [79, 58, 56.33],- -40.446344,- 79.982313,- );- testParsingLocation(- null,- [40, 26, 46.84],- null,- [-79, 58, 56.33],- 40.446344,- -79.982313,- );- testParsingLocation(- null,- [40, -26, 46.84],- null,- [79, -58, 56.33],- -40.446344,- -79.982313,- );- },- );});}diff --git a/mobile/packages/ente_components/test/components/slider_stepper_test.dart b/mobile/packages/ente_components/test/components/slider_stepper_test.dartdeleted file mode 100644index cd9cbd4df0..0000000000--- a/mobile/packages/ente_components/test/components/slider_stepper_test.dart+++ /dev/null@@ -1,24 +0,0 @@-import "package:ente_components/ente_components.dart";-import "package:flutter/material.dart";-import "package:flutter/material.dart" as material show Slider;-import "package:flutter_test/flutter_test.dart";--void main() {- testWidgets("SliderComponent clamps its rendered value", (tester) async {- await tester.pumpWidget(- _wrap(SliderComponent(value: 12, min: 0, max: 10, onChanged: (_) {})),- );-- expect(- tester.widget<material.Slider>(find.byType(material.Slider)).value,- 10,- );- });-}--Widget _wrap(Widget child) {- return MaterialApp(- theme: ComponentTheme.lightTheme(),- home: Scaffold(body: Center(child: child)),- );-}diff --git a/mobile/packages/lock_screen/test/auth_util_test.dart b/mobile/packages/lock_screen/test/auth_util_test.dartindex 555eb1f587..10415d9cf8 100644--- a/mobile/packages/lock_screen/test/auth_util_test.dart+++ b/mobile/packages/lock_screen/test/auth_util_test.dart@@ -6,156 +6,142 @@ import 'package:local_auth/local_auth.dart';void main() {group("windowsLocalAuthenticationExceptionForError", () {- test("maps Windows not-enrolled errors to setup guidance", () {- final exception = windowsLocalAuthenticationExceptionForError(- PlatformException(+ final cases = <_WindowsCase>[+ (+ name: "not enrolled",+ error: PlatformException(code: "NotEnrolled",message: "No biometrics enrolled on this device.",),- );-- expect(exception, isNotNull);- expect(exception!.issue, WindowsLocalAuthIssue.notConfigured);- expect(exception.userMessage, contains("Windows Hello"));- expect(exception.userMessage, contains("PIN"));- });-- test("maps Windows hardware errors to app lock fallback guidance", () {- final exception = windowsLocalAuthenticationExceptionForError(- PlatformException(+ issue: WindowsLocalAuthIssue.notConfigured,+ messages: ["Windows Hello", "PIN"],+ ),+ (+ name: "no hardware",+ error: PlatformException(code: "NoHardware",message: "No biometric hardware found",),- );-- expect(exception, isNotNull);- expect(exception!.issue, WindowsLocalAuthIssue.noHardware);- expect(exception.userMessage, contains("App lock"));- });-- test("maps LocalAuthException codes", () {- final exception = windowsLocalAuthenticationExceptionForError(- const LocalAuthException(+ issue: WindowsLocalAuthIssue.noHardware,+ messages: ["App lock"],+ ),+ (+ name: "local auth not enrolled",+ error: const LocalAuthException(code: LocalAuthExceptionCode.noBiometricsEnrolled,),- );-- expect(exception, isNotNull);- expect(exception!.issue, WindowsLocalAuthIssue.notConfigured);- });-- test("ignores unrelated platform exceptions", () {- final exception = windowsLocalAuthenticationExceptionForError(- PlatformException(code: "UserCanceled"),- );-- expect(exception, isNull);- });+ issue: WindowsLocalAuthIssue.notConfigured,+ messages: [],+ ),+ (+ name: "unrelated platform exception",+ error: PlatformException(code: "UserCanceled"),+ issue: null,+ messages: [],+ ),+ ];++ for (final fixture in cases) {+ test(fixture.name, () {+ final exception = windowsLocalAuthenticationExceptionForError(+ fixture.error,+ );+ expect(exception?.issue, fixture.issue);+ for (final message in fixture.messages) {+ expect(exception?.userMessage, contains(message));+ }+ });+ }});group("isExpectedLocalAuthFailure", () {- test("treats user-driven cancellations as expected failures", () {- expect(- isExpectedLocalAuthFailure(- const LocalAuthException(code: LocalAuthExceptionCode.userCanceled),- ),- isTrue,- );- expect(- isExpectedLocalAuthFailure(- const LocalAuthException(code: LocalAuthExceptionCode.systemCanceled),- ),- isTrue,- );- expect(- isExpectedLocalAuthFailure(- const LocalAuthException(- code: LocalAuthExceptionCode.userRequestedFallback,- ),- ),- isTrue,- );- });-- test("does not hide setup or device errors", () {- expect(- isExpectedLocalAuthFailure(- const LocalAuthException(- code: LocalAuthExceptionCode.noCredentialsSet,- ),- ),- isFalse,- );- expect(- isExpectedLocalAuthFailure(- const LocalAuthException(code: LocalAuthExceptionCode.deviceError),- ),- isFalse,- );- });+ for (final (code, expected) in const [+ (LocalAuthExceptionCode.userCanceled, true),+ (LocalAuthExceptionCode.systemCanceled, true),+ (LocalAuthExceptionCode.userRequestedFallback, true),+ (LocalAuthExceptionCode.noCredentialsSet, false),+ (LocalAuthExceptionCode.deviceError, false),+ ]) {+ test(code.name, () {+ expect(+ isExpectedLocalAuthFailure(LocalAuthException(code: code)),+ expected,+ );+ });+ }});group("localAuthenticationUnavailableExceptionForError", () {- test("maps missing credentials to setup guidance", () {- final exception = localAuthenticationUnavailableExceptionForError(- const LocalAuthException(code: LocalAuthExceptionCode.noCredentialsSet),- );-- expect(exception, isNotNull);- expect(exception!.issue, LocalAuthUnavailableIssue.notConfigured);- expect(exception.userMessage, contains("System authentication"));- expect(exception.userMessage, contains("PIN/password"));- });-- test("maps hardware and device errors", () {- expect(- localAuthenticationUnavailableExceptionForError(- const LocalAuthException(- code: LocalAuthExceptionCode.noBiometricHardware,- ),- )!.issue,- LocalAuthUnavailableIssue.noHardware,- );- expect(- localAuthenticationUnavailableExceptionForError(- const LocalAuthException(code: LocalAuthExceptionCode.deviceError),- )!.issue,- LocalAuthUnavailableIssue.unavailable,- );- });-- test("ignores expected user failures", () {- final exception = localAuthenticationUnavailableExceptionForError(- const LocalAuthException(code: LocalAuthExceptionCode.userCanceled),- );-- expect(exception, isNull);- });+ const cases = <_UnavailableCase>[+ (+ name: "missing credentials",+ code: LocalAuthExceptionCode.noCredentialsSet,+ issue: LocalAuthUnavailableIssue.notConfigured,+ messages: ["System authentication", "PIN/password"],+ ),+ (+ name: "no hardware",+ code: LocalAuthExceptionCode.noBiometricHardware,+ issue: LocalAuthUnavailableIssue.noHardware,+ messages: [],+ ),+ (+ name: "device error",+ code: LocalAuthExceptionCode.deviceError,+ issue: LocalAuthUnavailableIssue.unavailable,+ messages: [],+ ),+ (+ name: "user cancellation",+ code: LocalAuthExceptionCode.userCanceled,+ issue: null,+ messages: [],+ ),+ ];++ for (final fixture in cases) {+ test(fixture.name, () {+ final exception = localAuthenticationUnavailableExceptionForError(+ LocalAuthException(code: fixture.code),+ );+ expect(exception?.issue, fixture.issue);+ for (final message in fixture.messages) {+ expect(exception?.userMessage, contains(message));+ }+ });+ }});group("shouldShowLinuxSystemAuthSetupGuide", () {- test("routes Linux setup-required failures to the guide dialog", () {- expect(- shouldShowLinuxSystemAuthSetupGuide(- const LocalAuthenticationUnavailableException(- issue: LocalAuthUnavailableIssue.linuxSetupRequired,- code: "noCredentialsSet",- ),- ),- isTrue,- );- });-- test("keeps generic local auth failures on toast guidance", () {- expect(- shouldShowLinuxSystemAuthSetupGuide(- const LocalAuthenticationUnavailableException(- issue: LocalAuthUnavailableIssue.notConfigured,- code: "noCredentialsSet",+ for (final (issue, expected) in const [+ (LocalAuthUnavailableIssue.linuxSetupRequired, true),+ (LocalAuthUnavailableIssue.notConfigured, false),+ ]) {+ test(issue.name, () {+ expect(+ shouldShowLinuxSystemAuthSetupGuide(+ LocalAuthenticationUnavailableException(+ issue: issue,+ code: "noCredentialsSet",+ ),),- ),- isFalse,- );- });+ expected,+ );+ });+ }});}++typedef _WindowsCase = ({+ String name,+ Object error,+ WindowsLocalAuthIssue? issue,+ List<String> messages,+});++typedef _UnavailableCase = ({+ String name,+ LocalAuthExceptionCode code,+ LocalAuthUnavailableIssue? issue,+ List<String> messages,+});diff --git a/server/ente/paste_test.go b/server/ente/paste_test.goindex dd72c6e209..168fab75db 100644--- a/server/ente/paste_test.go+++ b/server/ente/paste_test.go@@ -18,92 +18,53 @@ func newValidPasteRequest() CreatePasteRequest {}}-func TestCreatePasteRequestValidate_Valid(t *testing.T) {- req := newValidPasteRequest()- if err := req.Validate(1024); err != nil {- t.Fatalf("expected valid request, got error: %v", err)+func TestCreatePasteRequestValidate(t *testing.T) {+ tests := []struct {+ name string+ mutate func(*CreatePasteRequest)+ wantErr bool+ }{+ {name: "interactive parameters"},+ {name: "moderate parameters", mutate: func(req *CreatePasteRequest) {+ req.KdfMemLimit = pasteKdfMemLimitModerate+ req.KdfOpsLimit = pasteKdfOpsLimitModerate+ }},+ {name: "oversized payload", wantErr: true, mutate: func(req *CreatePasteRequest) {+ req.EncryptedData = strings.Repeat("a", 1025)+ }},+ {name: "oversized decryption header", wantErr: true, mutate: func(req *CreatePasteRequest) {+ req.DecryptionHeader = strings.Repeat("a", pasteDecryptionHeaderMaxLength+1)+ }},+ {name: "oversized encrypted paste key", wantErr: true, mutate: func(req *CreatePasteRequest) {+ req.EncryptedPasteKey = strings.Repeat("a", pasteEncryptedPasteKeyMaxLength+1)+ }},+ {name: "oversized encrypted paste key nonce", wantErr: true, mutate: func(req *CreatePasteRequest) {+ req.EncryptedPasteKeyNonce = strings.Repeat("a", pasteEncryptedPasteKeyNonceMaxLength+1)+ }},+ {name: "oversized KDF nonce", wantErr: true, mutate: func(req *CreatePasteRequest) {+ req.KdfNonce = strings.Repeat("a", pasteKdfNonceMaxLength+1)+ }},+ {name: "invalid KDF nonce encoding", wantErr: true, mutate: func(req *CreatePasteRequest) {+ req.KdfNonce = "not-base64@@@"+ }},+ {name: "invalid KDF nonce length", wantErr: true, mutate: func(req *CreatePasteRequest) {+ req.KdfNonce = base64.StdEncoding.EncodeToString(make([]byte, 8))+ }},+ {name: "invalid KDF cost", wantErr: true, mutate: func(req *CreatePasteRequest) {+ req.KdfMemLimit = pasteKdfMemLimitInteractive * 2+ req.KdfOpsLimit = pasteKdfOpsLimitInteractive * 2+ }},}-}--func TestCreatePasteRequestValidate_ValidModerateKdfParams(t *testing.T) {- req := newValidPasteRequest()- req.KdfMemLimit = pasteKdfMemLimitModerate- req.KdfOpsLimit = pasteKdfOpsLimitModerate-- if err := req.Validate(1024); err != nil {- t.Fatalf("expected valid request, got error: %v", err)- }-}--func TestCreatePasteRequestValidate_RejectsOversizedEncryptedPayload(t *testing.T) {- req := newValidPasteRequest()- req.EncryptedData = strings.Repeat("a", 1025)-- if err := req.Validate(1024); err == nil {- t.Fatal("expected oversized encrypted payload to be rejected")- }-}--func TestCreatePasteRequestValidate_RejectsOversizedDecryptionHeader(t *testing.T) {- req := newValidPasteRequest()- req.DecryptionHeader = strings.Repeat("a", pasteDecryptionHeaderMaxLength+1)-- if err := req.Validate(1024); err == nil {- t.Fatal("expected oversized decryption header to be rejected")- }-}--func TestCreatePasteRequestValidate_RejectsOversizedEncryptedPasteKey(t *testing.T) {- req := newValidPasteRequest()- req.EncryptedPasteKey = strings.Repeat("a", pasteEncryptedPasteKeyMaxLength+1)-- if err := req.Validate(1024); err == nil {- t.Fatal("expected oversized encrypted paste key to be rejected")- }-}--func TestCreatePasteRequestValidate_RejectsOversizedEncryptedPasteKeyNonce(t *testing.T) {- req := newValidPasteRequest()- req.EncryptedPasteKeyNonce = strings.Repeat("a", pasteEncryptedPasteKeyNonceMaxLength+1)-- if err := req.Validate(1024); err == nil {- t.Fatal("expected oversized encrypted paste key nonce to be rejected")- }-}--func TestCreatePasteRequestValidate_RejectsOversizedKdfNonce(t *testing.T) {- req := newValidPasteRequest()- req.KdfNonce = strings.Repeat("a", pasteKdfNonceMaxLength+1)-- if err := req.Validate(1024); err == nil {- t.Fatal("expected oversized kdf nonce to be rejected")- }-}--func TestCreatePasteRequestValidate_RejectsInvalidKdfNonceEncoding(t *testing.T) {- req := newValidPasteRequest()- req.KdfNonce = "not-base64@@@"-- if err := req.Validate(1024); err == nil {- t.Fatal("expected invalid kdf nonce encoding to be rejected")- }-}--func TestCreatePasteRequestValidate_RejectsUnexpectedKdfNonceLength(t *testing.T) {- req := newValidPasteRequest()- req.KdfNonce = base64.StdEncoding.EncodeToString(make([]byte, 8))-- if err := req.Validate(1024); err == nil {- t.Fatal("expected invalid kdf nonce length to be rejected")- }-}--func TestCreatePasteRequestValidate_RejectsInvalidKdfCostParams(t *testing.T) {- req := newValidPasteRequest()- req.KdfMemLimit = pasteKdfMemLimitInteractive * 2- req.KdfOpsLimit = pasteKdfOpsLimitInteractive * 2- if err := req.Validate(1024); err == nil {- t.Fatal("expected invalid kdf cost params to be rejected")+ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ req := newValidPasteRequest()+ if test.mutate != nil {+ test.mutate(&req)+ }+ if err := req.Validate(1024); (err != nil) != test.wantErr {+ t.Fatalf("Validate() error = %v, wantErr %t", err, test.wantErr)+ }+ })}}diff --git a/server/ente/user_test.go b/server/ente/user_test.goindex 2b786ac37e..a5fe90f9cf 100644--- a/server/ente/user_test.go+++ b/server/ente/user_test.go@@ -11,64 +11,37 @@ const (validArgonOpsLimit = 32)-func TestSetUserAttributesRequestValidate_RejectsUnexpectedKDFStrength(t *testing.T) {- req := SetUserAttributesRequest{- KeyAttributes: KeyAttributes{- MemLimit: validArgonMemLimit,- OpsLimit: validArgonOpsLimit - 1,- },+func TestKeyRequestValidation(t *testing.T) {+ validators := []struct {+ name string+ validate func(memLimit, opsLimit int64) error+ }{+ {name: "set attributes", validate: func(memLimit, opsLimit int64) error {+ return (&SetUserAttributesRequest{KeyAttributes: KeyAttributes{+ MemLimit: memLimit,+ OpsLimit: opsLimit,+ }}).Validate()+ }},+ {name: "update keys", validate: func(memLimit, opsLimit int64) error {+ return (&UpdateKeysRequest{MemLimit: memLimit, OpsLimit: opsLimit}).Validate()+ }},}- assertBadRequestMessage(t, req.Validate(), "Unexpected KDF strength")-}--func TestSetUserAttributesRequestValidate_AllowsMinimumMemory(t *testing.T) {- req := SetUserAttributesRequest{- KeyAttributes: KeyAttributes{- MemLimit: 128 * 1024 * 1024,- OpsLimit: validArgonOpsLimit,- },- }-- require.NoError(t, req.Validate())-}--func TestSetUserAttributesRequestValidate_RejectsLowMemoryLimit(t *testing.T) {- req := SetUserAttributesRequest{- KeyAttributes: KeyAttributes{- MemLimit: 64 * 1024 * 1024,- OpsLimit: 64,- },- }-- assertBadRequestMessage(t, req.Validate(), "memory limit must be at least 128MB")-}--func TestUpdateKeysRequestValidate_RejectsUnexpectedKDFStrength(t *testing.T) {- req := UpdateKeysRequest{- MemLimit: validArgonMemLimit,- OpsLimit: validArgonOpsLimit - 1,+ for _, validator := range validators {+ t.Run(validator.name, func(t *testing.T) {+ assertBadRequestMessage(+ t,+ validator.validate(validArgonMemLimit, validArgonOpsLimit-1),+ "Unexpected KDF strength",+ )+ require.NoError(t, validator.validate(validArgonMemLimit, validArgonOpsLimit))+ assertBadRequestMessage(+ t,+ validator.validate(64*1024*1024, 64),+ "memory limit must be at least 128MB",+ )+ })}-- assertBadRequestMessage(t, req.Validate(), "Unexpected KDF strength")-}--func TestUpdateKeysRequestValidate_AllowsMinimumMemory(t *testing.T) {- req := UpdateKeysRequest{- MemLimit: 128 * 1024 * 1024,- OpsLimit: validArgonOpsLimit,- }-- require.NoError(t, req.Validate())-}--func TestUpdateKeysRequestValidate_RejectsLowMemoryLimit(t *testing.T) {- req := UpdateKeysRequest{- MemLimit: 64 * 1024 * 1024,- OpsLimit: 64,- }-- assertBadRequestMessage(t, req.Validate(), "memory limit must be at least 128MB")}func assertBadRequestMessage(t *testing.T, err error, wantMessage string) {diff --git a/server/pkg/controller/legacy_kit/controller_test.go b/server/pkg/controller/legacy_kit/controller_test.goindex 8ac2c2cc8e..bc0eefae29 100644--- a/server/pkg/controller/legacy_kit/controller_test.go+++ b/server/pkg/controller/legacy_kit/controller_test.go@@ -2,52 +2,14 @@ package legacy_kitimport ("testing"- "time""github.com/ente/museum/ente"legacykitrepo "github.com/ente/museum/pkg/repo/legacy_kit"timeutil "github.com/ente/museum/pkg/utils/time""github.com/google/uuid"- "github.com/spf13/viper""github.com/stretchr/testify/require")-func TestLegacyURLUsesDefaultWhenUnset(t *testing.T) {- previousURL := viper.GetString("apps.legacy")- viper.Set("apps.legacy", "")- t.Cleanup(func() {- viper.Set("apps.legacy", previousURL)- })-- require.Equal(t, defaultLegacyURL, legacyURL())-}--func TestLegacyURLUsesConfiguredURLWithoutTrailingSlash(t *testing.T) {- previousURL := viper.GetString("apps.legacy")- viper.Set("apps.legacy", " http://localhost:3013/ ")- t.Cleanup(func() {- viper.Set("apps.legacy", previousURL)- })-- require.Equal(t, "http://localhost:3013", legacyURL())-}--func TestToRecoverySessionReturnsRemainingWaitTime(t *testing.T) {- row := &legacykitrepo.RecoverySessionRow{- ID: uuid.New(),- KitID: uuid.New(),- Status: ente.LegacyKitRecoveryStatusWaiting,- WaitTill: timeutil.MicrosecondsAfterHours(1),- CreatedAt: timeutil.Microseconds(),- }-- session := toRecoverySession(row)-- require.Equal(t, ente.LegacyKitRecoveryStatusWaiting, session.Status)- require.Greater(t, session.WaitTill, int64(0))- require.LessOrEqual(t, session.WaitTill, time.Hour.Microseconds())-}-func TestToRecoverySessionMarksExpiredWaitingSessionReady(t *testing.T) {row := &legacykitrepo.RecoverySessionRow{ID: uuid.New(),diff --git a/server/pkg/controller/user/inactive_user_orchestrator_test.go b/server/pkg/controller/user/inactive_user_orchestrator_test.goindex dc4e9d7913..8c1321cb80 100644--- a/server/pkg/controller/user/inactive_user_orchestrator_test.go+++ b/server/pkg/controller/user/inactive_user_orchestrator_test.go@@ -1,7 +1,6 @@package userimport (- "strings""testing""github.com/ente/museum/pkg/repo"@@ -115,92 +114,6 @@ func TestNextInactivityEmailStage(t *testing.T) {}}-func TestHasAnyStageSuccess(t *testing.T) {- stats := newInactiveUserRunStats()- if hasAnyStageSuccess(stats.SuccessByStage) {- t.Fatal("expected no stage success")- }-- stats.SuccessByStage[inactivityEmailStageWarn7d] = 1- if !hasAnyStageSuccess(stats.SuccessByStage) {- t.Fatal("expected stage success to be detected")- }-}--func TestHasInactiveUserRunSummaryActivity(t *testing.T) {- stats := newInactiveUserRunStats()- if hasInactiveUserRunSummaryActivity(stats) {- t.Fatal("expected no summary activity")- }-- stats.PausedLegacyContact = 1- if !hasInactiveUserRunSummaryActivity(stats) {- t.Fatal("expected paused legacy contact to count as summary activity")- }-- stats.PausedLegacyContact = 0- stats.SuccessByStage[inactivityEmailStageWarn2m] = 1- if !hasInactiveUserRunSummaryActivity(stats) {- t.Fatal("expected stage success to count as summary activity")- }-}--func TestBuildInactiveUserRunSummary(t *testing.T) {- stats := newInactiveUserRunStats()- stats.ProcessedUsers = 12- stats.SentEmails = 3- stats.SuccessByStage[inactivityEmailStageWarn2m] = 2- stats.SuccessByStage[inactivityEmailStageWarn1m] = 1- stats.FailureByStage[inactivityEmailStageWarn7d] = 4- stats.PreStageFailures = 2- stats.PausedLegacyContact = 6-- summary := buildInactiveUserRunSummary(stats, 0)-- mustContain := []string{- "Inactive user run summary (1970-01-01T00:00:00Z)",- "processed=12",- "sent=3",- "success={warn_2m=2, warn_1m=1}",- "failures={warn_7d=4}",- "pre_stage_failures=2",- "paused_legacy_contact=6",- }-- for _, fragment := range mustContain {- if !strings.Contains(summary, fragment) {- t.Fatalf("summary missing fragment %q: %s", fragment, summary)- }- }-- mustNotContain := []string{- "warn_7d=0",- "warn_1d=0",- "confirm_13m=0",- "warn_2m=0",- "warn_1m=0",- "sent=0",- "pre_stage_failures=0",- }- for _, fragment := range mustNotContain {- if strings.Contains(summary, fragment) {- t.Fatalf("summary contains zero-value fragment %q: %s", fragment, summary)- }- }-}--func TestBuildInactiveUserRunSummaryForPausedOnlyRun(t *testing.T) {- stats := newInactiveUserRunStats()- stats.ProcessedUsers = 12- stats.PausedLegacyContact = 2-- summary := buildInactiveUserRunSummary(stats, 0)- want := "Inactive user run summary (1970-01-01T00:00:00Z): processed=12 | paused_legacy_contact=2"- if summary != want {- t.Fatalf("unexpected summary: got %q want %q", summary, want)- }-}-func TestProcessCandidateBatchRecoversPanics(t *testing.T) {orchestrator := &InactiveUserOrchestrator{}candidates := []repo.UserInactivityCandidate{diff --git a/server/pkg/middleware/collection_link_test.go b/server/pkg/middleware/collection_link_test.goindex 04ecf4b181..62b7aa56e5 100644--- a/server/pkg/middleware/collection_link_test.go+++ b/server/pkg/middleware/collection_link_test.go@@ -22,24 +22,6 @@ func TestShouldCheckCollectionLinkDeviceLimit(t *testing.T) {require.False(t, shouldCheckCollectionLinkDeviceLimit("/public-collection/verify-password"))}-func TestCapFreeUserDeviceLimit(t *testing.T) {- for _, test := range []struct {- name string- deviceLimit int- want int- }{- {name: "invalid negative limit", deviceLimit: -1, want: 10},- {name: "unlimited", deviceLimit: 0, want: 10},- {name: "legacy free limit", deviceLimit: 5, want: 5},- {name: "current free limit", deviceLimit: 10, want: 10},- {name: "paid limit", deviceLimit: 25, want: 10},- } {- t.Run(test.name, func(t *testing.T) {- require.Equal(t, test.want, capFreeUserDeviceLimit(test.deviceLimit))- })- }-}-func TestCollectionLinkCacheIsScopedToOrigin(t *testing.T) {const (accessToken = "access-token"diff --git a/server/pkg/utils/recover/wrap_test.go b/server/pkg/utils/recover/wrap_test.goindex 80585436eb..bb168301eb 100644--- a/server/pkg/utils/recover/wrap_test.go+++ b/server/pkg/utils/recover/wrap_test.go@@ -1,52 +1,14 @@package recoverimport (- "errors""testing")-func TestInt64ToInt64RecoverWrapper(t *testing.T) {-- type args struct {- input int64- fn Int64ToInt64DataFn- output *int64- expectedOutput int64- }- var expectedResult int64-- tests := []struct {- name string- args args- wantErr bool- }{- {- "success",- args{input: 1, fn: func(userID int64) (int64, error) { return 5, nil }, output: &expectedResult, expectedOutput: 5},- false,- },- {- "err",- args{input: 1, fn: func(userID int64) (int64, error) { return 0, errors.New("testErr") }, output: nil, expectedOutput: 0},- true,- },- {- "panic_err",- args{input: 1, fn: func(userID int64) (int64, error) { panic("panic err") }, output: nil, expectedOutput: 0},- true,- },- }- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- err := Int64ToInt64RecoverWrapper(tt.args.input, tt.args.fn, tt.args.output)- if (err != nil) != tt.wantErr {- t.Errorf("Int64ToInt64RecoverWrapper() error = %v, wantErr %v", err, tt.wantErr)- }- if err == nil {- if *tt.args.output != tt.args.expectedOutput {- t.Errorf("Int64ToInt64RecoverWrapper() output = %v, expectedOutput %v", *tt.args.output, tt.args.expectedOutput)- }- }- })+func TestInt64ToInt64RecoverWrapperConvertsPanicToError(t *testing.T) {+ err := Int64ToInt64RecoverWrapper(1, func(int64) (int64, error) {+ panic("panic err")+ }, nil)+ if err == nil {+ t.Fatal("expected panic to become an error")}}diff --git a/server/space/controller/assets_test.go b/server/space/controller/assets_test.goindex bff2cd8fcb..0ccc8317b3 100644--- a/server/space/controller/assets_test.go+++ b/server/space/controller/assets_test.go@@ -19,64 +19,33 @@ func (b testSpaceAssetBuckets) IsBucketActive(bucketID string) bool {return b[bucketID]}-func TestPresignUploadRejectsOversizedPost(t *testing.T) {- controller := &AssetsController{}- ctx := context.Background()- space := &spacerepo.SpaceRecord{SpaceID: "space-1"}-- _, err := controller.PresignUpload(ctx, space, models.PresignUploadRequest{- Size: maxPostUploadBytes + 1,- ContentMD5: "XUFAKrxLKna5cZ2REBfFkg==",- })-- require.Error(t, err)- require.Contains(t, err.Error(), strconv.FormatInt(maxPostUploadBytes, 10))-}--func TestPresignUploadRejectsOversizedAvatar(t *testing.T) {- controller := &AssetsController{}- ctx := context.Background()- space := &spacerepo.SpaceRecord{SpaceID: "space-1"}- purpose := uploadPurposeAvatar-- _, err := controller.PresignUpload(ctx, space, models.PresignUploadRequest{- Size: maxAvatarUploadBytes + 1,- ContentMD5: "XUFAKrxLKna5cZ2REBfFkg==",- Purpose: &purpose,- })-- require.Error(t, err)- require.Contains(t, err.Error(), strconv.FormatInt(maxAvatarUploadBytes, 10))-}--func TestPresignUploadRejectsOversizedCover(t *testing.T) {- controller := &AssetsController{}- ctx := context.Background()- space := &spacerepo.SpaceRecord{SpaceID: "space-1"}- purpose := uploadPurposeCover-- _, err := controller.PresignUpload(ctx, space, models.PresignUploadRequest{- Size: maxCoverUploadBytes + 1,- ContentMD5: "XUFAKrxLKna5cZ2REBfFkg==",- Purpose: &purpose,- })-- require.Error(t, err)- require.Contains(t, err.Error(), strconv.FormatInt(maxCoverUploadBytes, 10))-}--func TestMaxUploadBytesForPurpose(t *testing.T) {- postLimit, err := maxUploadBytesForPurpose(uploadPurposePost)- require.NoError(t, err)- require.Equal(t, maxPostUploadBytes, postLimit)-- avatarLimit, err := maxUploadBytesForPurpose(uploadPurposeAvatar)- require.NoError(t, err)- require.Equal(t, maxAvatarUploadBytes, avatarLimit)-- coverLimit, err := maxUploadBytesForPurpose(uploadPurposeCover)- require.NoError(t, err)- require.Equal(t, maxCoverUploadBytes, coverLimit)+func TestPresignUploadRejectsOversizedAssets(t *testing.T) {+ for _, test := range []struct {+ purpose string+ limit int64+ }{+ {purpose: uploadPurposePost, limit: maxPostUploadBytes},+ {purpose: uploadPurposeAvatar, limit: maxAvatarUploadBytes},+ {purpose: uploadPurposeCover, limit: maxCoverUploadBytes},+ } {+ t.Run(test.purpose, func(t *testing.T) {+ request := models.PresignUploadRequest{+ Size: test.limit + 1,+ ContentMD5: "XUFAKrxLKna5cZ2REBfFkg==",+ }+ if test.purpose != uploadPurposePost {+ request.Purpose = &test.purpose+ }++ _, err := (&AssetsController{}).PresignUpload(+ context.Background(),+ &spacerepo.SpaceRecord{SpaceID: "space-1"},+ request,+ )+ require.Error(t, err)+ require.Contains(t, err.Error(), strconv.FormatInt(test.limit, 10))+ })+ }}func TestNormalizeContentMD5(t *testing.T) {