From 8df72293b554dbd575b236aff29b30e9c033983e Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Mon, 10 Aug 2026 09:46:27 +0200 Subject: [PATCH] Test the persistence base layer --- lib/database/powersync/powersync.dart | 97 ++++++++-------- test/core/uuid_test.dart | 41 +++++++ .../date_only_text_converter_test.dart | 68 +++++++++++ .../exercise_image_style_converter_test.dart | 43 +++++++ .../time_of_day_converter_test.dart | 45 ++++++++ .../utc_datetime_converter_test.dart | 60 ++++++++++ .../workout_impression_converter_test.dart | 43 +++++++ test/database/powersync/powersync_test.dart | 105 +++++++++++++++++ test/powersync/connector_test.dart | 78 ++++++++++++- test/powersync/schema_test.dart | 108 ++++++++++++++++++ 10 files changed, 637 insertions(+), 51 deletions(-) create mode 100644 test/core/uuid_test.dart create mode 100644 test/database/converters/date_only_text_converter_test.dart create mode 100644 test/database/converters/exercise_image_style_converter_test.dart create mode 100644 test/database/converters/time_of_day_converter_test.dart create mode 100644 test/database/converters/utc_datetime_converter_test.dart create mode 100644 test/database/converters/workout_impression_converter_test.dart create mode 100644 test/database/powersync/powersync_test.dart create mode 100644 test/powersync/schema_test.dart diff --git a/lib/database/powersync/powersync.dart b/lib/database/powersync/powersync.dart index edeeafcf4..ef9b48690 100644 --- a/lib/database/powersync/powersync.dart +++ b/lib/database/powersync/powersync.dart @@ -140,17 +140,52 @@ Future powerSyncInstance(Ref ref) async { /// /// Skips all work when the raw tables already exist, so warm restarts don't /// take a write lock on the DB. +/// `CREATE TABLE` statement per raw table, keyed by table name. +/// +/// Not STRICT: keep SQLite's type affinity behaviour so PowerSync's inferred +/// inserts can bind values as they arrive from the JSON wire protocol without +/// us having to coerce types up front. +/// +/// `id` is INTEGER, not the PowerSync-conventional TEXT, so it matches the +/// Drift `IntColumn id` and the integer `exercise_id` FK: the catalogue join +/// is then native INTEGER == INTEGER instead of relying on TEXT-vs-INTEGER +/// affinity coercion. PowerSync's string oplog id coerces to INTEGER on insert +/// (safe: Django exercise PKs are always numeric). +@visibleForTesting +const rawTableStatements = { + 'exercises_exercise': ''' + CREATE TABLE IF NOT EXISTS exercises_exercise( + id INTEGER NOT NULL PRIMARY KEY, + uuid TEXT, + category_id INTEGER, + variation_group TEXT, + created TEXT, + last_update TEXT + ) + ''', + 'exercises_translation': ''' + CREATE TABLE IF NOT EXISTS exercises_translation( + id INTEGER NOT NULL PRIMARY KEY, + uuid TEXT, + language_id INTEGER, + exercise_id INTEGER, + description TEXT, + name TEXT, + created TEXT, + last_update TEXT + ) + ''', +}; + +const _rawTableIndexStatements = [ + 'CREATE INDEX IF NOT EXISTS exercises_exercise__category ON exercises_exercise(category_id)', + 'CREATE INDEX IF NOT EXISTS exercises_exercise__variation ON exercises_exercise(variation_group)', + 'CREATE INDEX IF NOT EXISTS exercises_translation__language ON exercises_translation(language_id)', + 'CREATE INDEX IF NOT EXISTS exercises_translation__exercise ON exercises_translation(exercise_id)', +]; + Future _createRawTables(PowerSyncDatabase db) async { - // Not STRICT: keep SQLite's type affinity behaviour so PowerSync's - // inferred inserts can bind values as they arrive from the JSON wire - // protocol without us having to coerce types up front. - // - // `id` is INTEGER, not the PowerSync-conventional TEXT, so it matches the - // Drift `IntColumn id` and the integer `exercise_id` FK: the catalogue join - // is then native INTEGER == INTEGER instead of relying on TEXT-vs-INTEGER - // affinity coercion. PowerSync's string oplog id coerces to INTEGER on insert - // (safe: Django exercise PKs are always numeric). - const rawTables = ['exercises_exercise', 'exercises_translation']; + final rawTables = rawTableStatements.keys.toList(); final existing = await db.getAll( 'SELECT name FROM sqlite_master ' 'WHERE type = ? AND name IN (${rawTables.map((_) => '?').join(', ')})', @@ -162,45 +197,9 @@ Future _createRawTables(PowerSyncDatabase db) async { } await db.writeTransaction((tx) async { - await tx.execute(''' - CREATE TABLE IF NOT EXISTS exercises_exercise( - id INTEGER NOT NULL PRIMARY KEY, - uuid TEXT, - category_id INTEGER, - variation_group TEXT, - created TEXT, - last_update TEXT - ) - '''); - await tx.execute( - 'CREATE INDEX IF NOT EXISTS exercises_exercise__category ' - 'ON exercises_exercise(category_id)', - ); - await tx.execute( - 'CREATE INDEX IF NOT EXISTS exercises_exercise__variation ' - 'ON exercises_exercise(variation_group)', - ); - - await tx.execute(''' - CREATE TABLE IF NOT EXISTS exercises_translation( - id INTEGER NOT NULL PRIMARY KEY, - uuid TEXT, - language_id INTEGER, - exercise_id INTEGER, - description TEXT, - name TEXT, - created TEXT, - last_update TEXT - ) - '''); - await tx.execute( - 'CREATE INDEX IF NOT EXISTS exercises_translation__language ' - 'ON exercises_translation(language_id)', - ); - await tx.execute( - 'CREATE INDEX IF NOT EXISTS exercises_translation__exercise ' - 'ON exercises_translation(exercise_id)', - ); + for (final statement in [...rawTableStatements.values, ..._rawTableIndexStatements]) { + await tx.execute(statement); + } }); } diff --git a/test/core/uuid_test.dart b/test/core/uuid_test.dart new file mode 100644 index 000000000..9926f31d0 --- /dev/null +++ b/test/core/uuid_test.dart @@ -0,0 +1,41 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 - 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:flutter_test/flutter_test.dart'; +import 'package:wger/core/uuid.dart'; + +void main() { + test('generates lowercase hex in the canonical 8-4-4-4-12 shape', () { + expect(uuidV4(), matches(RegExp(r'^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$'))); + }); + + test('sets the version and variant bits of a v4 UUID', () { + for (var i = 0; i < 200; i++) { + final parts = uuidV4().split('-'); + + expect(parts[2][0], '4', reason: 'version nibble'); + expect('89ab', contains(parts[3][0]), reason: 'RFC 4122 variant'); + } + }); + + test('does not repeat itself', () { + final seen = {for (var i = 0; i < 1000; i++) uuidV4()}; + + expect(seen, hasLength(1000)); + }); +} diff --git a/test/database/converters/date_only_text_converter_test.dart b/test/database/converters/date_only_text_converter_test.dart new file mode 100644 index 000000000..a0eb96fac --- /dev/null +++ b/test/database/converters/date_only_text_converter_test.dart @@ -0,0 +1,68 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 - 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:flutter_test/flutter_test.dart'; +import 'package:wger/database/converters/date_only_text_converter.dart'; + +void main() { + const converter = DateOnlyTextConverter(); + + group('toSql', () { + test('writes the calendar day zero-padded', () { + expect(converter.toSql(DateTime(2026, 3, 7)), '2026-03-07'); + }); + + test('drops the time of day', () { + expect(converter.toSql(DateTime(2026, 3, 7, 23, 59, 59)), '2026-03-07'); + }); + + test('writes the day the value represents in its own zone', () { + expect(converter.toSql(DateTime.utc(2026, 3, 7)), '2026-03-07'); + }); + }); + + group('fromSql', () { + test('parses a bare date into UTC midnight', () { + final read = converter.fromSql('2026-03-07'); + + expect(read, DateTime.utc(2026, 3, 7)); + expect(read.isUtc, isTrue); + }); + + test('takes the leading day of a legacy full timestamp', () { + // Rows written before this converter carry a full ISO timestamp + expect(converter.fromSql('2026-03-07T00:00:00.000Z'), DateTime.utc(2026, 3, 7)); + }); + }); + + test('a locally written day and the same day synced back compare equal', () { + // The regression this converter exists for: a `.equals()` lookup on a date + // column has to match whether the row was written here or came from the + // server, which sends a bare `YYYY-MM-DD` + final writtenLocally = converter.toSql(DateTime(2026, 3, 7, 18, 45)); + final syncedBack = converter.toSql(converter.fromSql('2026-03-07')); + + expect(writtenLocally, syncedBack); + }); + + test('a round trip keeps the calendar day', () { + final read = converter.fromSql(converter.toSql(DateTime(2026, 12, 31, 22))); + + expect([read.year, read.month, read.day], [2026, 12, 31]); + }); +} diff --git a/test/database/converters/exercise_image_style_converter_test.dart b/test/database/converters/exercise_image_style_converter_test.dart new file mode 100644 index 000000000..cd6b1ab2c --- /dev/null +++ b/test/database/converters/exercise_image_style_converter_test.dart @@ -0,0 +1,43 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 - 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:flutter_test/flutter_test.dart'; +import 'package:wger/database/converters/exercise_image_style_converter.dart'; +import 'package:wger/features/exercises/models/image.dart'; + +void main() { + const converter = ExerciseImageStyleConverter(); + + test('maps every wire value to its enum case', () { + expect(converter.fromSql('1'), ExerciseImageStyle.lineArt); + expect(converter.fromSql('2'), ExerciseImageStyle.threeD); + expect(converter.fromSql('3'), ExerciseImageStyle.lowPoly); + expect(converter.fromSql('4'), ExerciseImageStyle.photo); + expect(converter.fromSql('5'), ExerciseImageStyle.other); + }); + + test('every enum case survives a round trip', () { + for (final style in ExerciseImageStyle.values) { + expect(converter.fromSql(converter.toSql(style)), style); + } + }); + + test('an unknown wire value throws', () { + expect(() => converter.fromSql('6'), throwsStateError); + }); +} diff --git a/test/database/converters/time_of_day_converter_test.dart b/test/database/converters/time_of_day_converter_test.dart new file mode 100644 index 000000000..635733eed --- /dev/null +++ b/test/database/converters/time_of_day_converter_test.dart @@ -0,0 +1,45 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 - 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:wger/database/converters/time_of_day_converter.dart'; + +void main() { + const converter = TimeOfDayConverter(); + + test('writes 24 hour format regardless of the device locale', () { + expect(converter.toSql(const TimeOfDay(hour: 18, minute: 5)), '18:05'); + expect(converter.toSql(const TimeOfDay(hour: 0, minute: 0)), '00:00'); + }); + + test('reads a stored time back', () { + expect(converter.fromSql('18:05'), const TimeOfDay(hour: 18, minute: 5)); + }); + + test('a round trip preserves the time', () { + const time = TimeOfDay(hour: 7, minute: 30); + + expect(converter.fromSql(converter.toSql(time)), time); + }); + + test('reads a stored time that carries seconds', () { + // Django serializes `TimeField` with seconds + expect(converter.fromSql('18:05:00'), const TimeOfDay(hour: 18, minute: 5)); + }); +} diff --git a/test/database/converters/utc_datetime_converter_test.dart b/test/database/converters/utc_datetime_converter_test.dart new file mode 100644 index 000000000..5187f025c --- /dev/null +++ b/test/database/converters/utc_datetime_converter_test.dart @@ -0,0 +1,60 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 - 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:flutter_test/flutter_test.dart'; +import 'package:wger/database/converters/utc_datetime_converter.dart'; + +// The assertions compare instants and the isUtc flag, never wall-clock +// components, so they hold in every time zone. +void main() { + const converter = UtcDateTimeConverter(); + + group('toSql', () { + test('converts a local value to UTC without moving the instant', () { + final local = DateTime(2026, 6, 15, 14, 30); + + final stored = converter.toSql(local); + + expect(stored.isUtc, isTrue); + expect(stored.isAtSameMomentAs(local), isTrue); + }); + + test('leaves a value that is already UTC untouched', () { + final utc = DateTime.utc(2026, 6, 15, 14, 30); + + expect(converter.toSql(utc), utc); + }); + }); + + group('fromSql', () { + test('returns the stored instant in the local zone', () { + final stored = DateTime.utc(2026, 6, 15, 12); + + final read = converter.fromSql(stored); + + expect(read.isUtc, isFalse); + expect(read.isAtSameMomentAs(stored), isTrue); + }); + }); + + test('a round trip preserves the instant', () { + final local = DateTime(2026, 1, 31, 23, 59, 59); + + expect(converter.fromSql(converter.toSql(local)), local); + }); +} diff --git a/test/database/converters/workout_impression_converter_test.dart b/test/database/converters/workout_impression_converter_test.dart new file mode 100644 index 000000000..f0e26257a --- /dev/null +++ b/test/database/converters/workout_impression_converter_test.dart @@ -0,0 +1,43 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 - 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:flutter_test/flutter_test.dart'; +import 'package:wger/database/converters/workout_impression_converter.dart'; +import 'package:wger/features/routines/models/session.dart'; + +void main() { + const converter = WorkoutImpressionConverter(); + + test('maps every wire value to its enum case', () { + expect(converter.fromSql('1'), WorkoutImpression.bad); + expect(converter.fromSql('2'), WorkoutImpression.neutral); + expect(converter.fromSql('3'), WorkoutImpression.good); + }); + + test('every enum case survives a round trip', () { + for (final impression in WorkoutImpression.values) { + expect(converter.fromSql(converter.toSql(impression)), impression); + } + }); + + test('an unknown wire value throws', () { + // This sits on the read path of every session, so a new server-side + // choice surfaces as a StateError rather than a silent default + expect(() => converter.fromSql('4'), throwsStateError); + }); +} diff --git a/test/database/powersync/powersync_test.dart b/test/database/powersync/powersync_test.dart new file mode 100644 index 000000000..544bbba53 --- /dev/null +++ b/test/database/powersync/powersync_test.dart @@ -0,0 +1,105 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 - 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:drift/drift.dart' show DriftSqlType; +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:wger/database/powersync/database.dart'; +import 'package:wger/database/powersync/powersync.dart'; +import 'package:wger/powersync/schema.dart'; + +import '../../helpers/in_memory_drift.dart'; + +/// PowerSync manages the JSON view tables itself, but the raw tables are +/// materialised from hand-written DDL. Nothing fails loudly when that DDL and +/// the Drift definitions drift apart: the column is simply not there, and +/// every read of it comes back empty. +void main() { + late DriftPowersyncDatabase driftDb; + + setUp(() async => driftDb = await openTestDatabase()); + tearDown(() => driftDb.close()); + + /// Column name to SQLite type, as the DDL actually creates them. + Future> columnsOf(String table) async { + final db = DriftPowersyncDatabase(NativeDatabase.memory()); + addTearDown(db.close); + + await db.customStatement(rawTableStatements[table]!); + final rows = await db.customSelect('PRAGMA table_info($table)').get(); + + return { + for (final row in rows) row.read('name'): row.read('type'), + }; + } + + test('every raw table in the schema has a statement', () { + expect( + rawTableStatements.keys.toSet(), + schema.rawTables.map((table) => table.name).toSet(), + ); + }); + + test('the created columns match the Drift definitions', () async { + for (final table in rawTableStatements.keys) { + final created = await columnsOf(table); + final driftTable = driftDb.allTables.firstWhere( + (candidate) => candidate.actualTableName == table, + ); + + expect( + created.keys.toSet(), + driftTable.$columns.map((column) => column.name).toSet(), + reason: 'the raw table $table does not carry every Drift column', + ); + } + }); + + test('the created columns use the affinity of their Drift type', () async { + // `store_date_time_values_as_text` is on, so a Drift DateTimeColumn has to + // be created as TEXT here as well + const expectedAffinity = { + DriftSqlType.string: 'TEXT', + DriftSqlType.int: 'INTEGER', + DriftSqlType.dateTime: 'TEXT', + }; + + for (final table in rawTableStatements.keys) { + final created = await columnsOf(table); + final driftTable = driftDb.allTables.firstWhere( + (candidate) => candidate.actualTableName == table, + ); + + for (final column in driftTable.$columns) { + final expected = expectedAffinity[column.type]; + expect( + expected, + isNotNull, + reason: 'no affinity defined for ${column.type} ($table.${column.name})', + ); + expect( + created[column.name], + expected, + reason: + '$table.${column.name} is created as ${created[column.name]}, ' + 'but Drift reads it as ${column.type}', + ); + } + } + }); +} diff --git a/test/powersync/connector_test.dart b/test/powersync/connector_test.dart index ede037a1b..2a2ec3bb4 100644 --- a/test/powersync/connector_test.dart +++ b/test/powersync/connector_test.dart @@ -19,6 +19,7 @@ import 'dart:convert'; import 'dart:io'; +import 'package:drift/drift.dart' show GeneratedColumnWithTypeConverter; import 'package:flutter_test/flutter_test.dart'; import 'package:http/http.dart' as http; import 'package:http/testing.dart'; @@ -26,9 +27,11 @@ import 'package:logging/logging.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'package:powersync/powersync.dart'; +import 'package:wger/database/converters/date_only_text_converter.dart'; import 'package:wger/powersync/api_client.dart'; import 'package:wger/powersync/connector.dart'; +import '../helpers/in_memory_drift.dart'; import 'connector_test.mocks.dart'; @GenerateMocks([ApiClient]) @@ -164,6 +167,35 @@ void main() { expect(out['start'], '2024-11-01'); expect(out['end'], isNull); }); + + test('trims every date-only column in the Drift schema', () async { + // The registry of date-only fields is maintained by hand, so a new + // table backed by a Django `DateField` can be forgotten, and the push + // then fails on a value the backend cannot parse. Derive the columns + // from the schema instead of listing them here again. + final db = await openTestDatabase(); + addTearDown(db.close); + + final dateOnlyColumns = <(String, String)>[]; + for (final table in db.allTables) { + for (final column in table.$columns) { + if (column is GeneratedColumnWithTypeConverter && + column.converter is DateOnlyTextConverter) { + dateOnlyColumns.add((table.actualTableName, column.name)); + } + } + } + expect(dateOnlyColumns, isNotEmpty); + + for (final (table, column) in dateOnlyColumns) { + final out = connector.genericTransform(table, {column: '2024-11-01T00:00:00.000Z'}, '1'); + expect( + out[column], + '2024-11-01', + reason: '$table.$column is not registered as a date-only field', + ); + } + }); }); }); @@ -466,14 +498,16 @@ void main() { completed = false; }); - CrudTransaction txWith(CrudEntry entry) => CrudTransaction( + CrudTransaction txWithAll(List entries) => CrudTransaction( transactionId: 1, - crud: [entry], + crud: entries, complete: ({String? writeCheckpoint}) async { completed = true; }, ); + CrudTransaction txWith(CrudEntry entry) => txWithAll([entry]); + test('uploads a put through the transform and completes on success', () async { when(api.upsert(any)).thenAnswer((_) async => http.Response('{}', 200)); @@ -519,6 +553,46 @@ void main() { expect(completed, isTrue); }); + test('a rejected op does not stop the ops behind it', () async { + // One bad op must not block the queue: the rest of the transaction is + // still sent and the transaction completes. + when(api.upsert(any)).thenAnswer( + (_) async => http.Response(json.encode({'error': 'invalid'}), 200), + ); + when(api.update(any)).thenAnswer((_) async => http.Response('{}', 200)); + + await conn.processTransaction( + txWithAll([ + CrudEntry(1, UpdateType.put, 'manager_routine', 'r1', 1, {'name': 'x'}), + CrudEntry(2, UpdateType.patch, 'manager_routine', 'r2', 1, {'name': 'y'}), + ]), + ); + + verify(api.update(any)).called(1); + expect(completed, isTrue); + }); + + test('a retryable op leaves the whole transaction queued for a replay', () async { + // The op ahead of it was already sent, so the replay re-sends it: this is + // the at-least-once delivery the backend handlers have to be idempotent + // for. + when(api.upsert(any)).thenAnswer((_) async => http.Response('{}', 200)); + when(api.update(any)).thenAnswer((_) async => http.Response('', 503)); + + await expectLater( + conn.processTransaction( + txWithAll([ + CrudEntry(1, UpdateType.put, 'manager_routine', 'r1', 1, {'name': 'x'}), + CrudEntry(2, UpdateType.patch, 'manager_routine', 'r2', 1, {'name': 'y'}), + ]), + ), + throwsA(isA()), + ); + + verify(api.upsert(any)).called(1); + expect(completed, isFalse); + }); + test('rethrows and leaves the transaction queued when the backend is unreachable', () async { when(api.upsert(any)).thenThrow(http.ClientException('Connection refused')); diff --git a/test/powersync/schema_test.dart b/test/powersync/schema_test.dart new file mode 100644 index 000000000..83b7fcc34 --- /dev/null +++ b/test/powersync/schema_test.dart @@ -0,0 +1,108 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 - 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:drift/drift.dart' as drift; +import 'package:flutter_test/flutter_test.dart'; +import 'package:powersync/powersync.dart' as ps; +import 'package:wger/database/powersync/database.dart'; +import 'package:wger/powersync/schema.dart'; + +import '../helpers/in_memory_drift.dart'; + +/// The PowerSync column type a Drift column of [type] has to be declared as. +/// +/// A mismatch does not fail loudly: the generated view returns the value in +/// the declared type, so a `ps.Column.text` behind a Drift `BoolColumn` yields +/// `'0'`, and `'0' != 0` is true in Dart, which silently flips every read. +// Drift hides the common supertype of its column types, so this takes an +// Object and matches on the exported constants. +ps.ColumnType expectedPowerSyncType(Object type) => switch (type) { + drift.DriftSqlType.string => ps.ColumnType.text, + drift.DriftSqlType.bool || + drift.DriftSqlType.int || + drift.DriftSqlType.bigInt => ps.ColumnType.integer, + drift.DriftSqlType.double => ps.ColumnType.real, + // `store_date_time_values_as_text` is on (build.yaml) + drift.DriftSqlType.dateTime => ps.ColumnType.text, + _ => throw ArgumentError('No PowerSync mapping defined for $type'), +}; + +void main() { + late DriftPowersyncDatabase db; + late Map> driftTables; + + setUp(() async { + db = await openTestDatabase(); + driftTables = {for (final table in db.allTables) table.actualTableName: table}; + }); + + tearDown(() => db.close()); + + test('the schema is not empty', () { + // Guards the loops below against silently iterating nothing + expect(schema.tables, isNotEmpty); + expect(driftTables, isNotEmpty); + }); + + test('every synced table has a Drift counterpart', () { + for (final table in schema.tables) { + expect(driftTables, contains(table.name)); + } + }); + + test('every column is declared with the type of its Drift column', () { + for (final table in schema.tables) { + final driftColumns = { + for (final column in driftTables[table.name]!.$columns) column.name: column, + }; + + for (final column in table.columns) { + final driftColumn = driftColumns[column.name]; + expect( + driftColumn, + isNotNull, + reason: '${table.name}.${column.name} has no Drift column', + ); + expect( + column.type, + expectedPowerSyncType(driftColumn!.type), + reason: + '${table.name}.${column.name} is declared as ${column.type.name}, ' + 'but Drift reads it as ${driftColumn.type}', + ); + } + } + }); + + test('every Drift column is part of the synced schema', () { + for (final table in schema.tables) { + // PowerSync stores the row id outside the payload, so it is never + // declared as a column + final expected = driftTables[table.name]!.$columns + .map((column) => column.name) + .where((name) => name != 'id') + .toSet(); + + expect( + table.columns.map((column) => column.name).toSet(), + expected, + reason: 'the view for ${table.name} would not carry every Drift column', + ); + } + }); +}