Make the weak tests prove what they claim

This commit is contained in:
Roland Geider
2026-12-03 16:35:23 +01:00
parent 5ced55c6d0
commit 9e3fb6614e
45 changed files with 735 additions and 7187 deletions

View File

@@ -109,10 +109,10 @@ void main() {
});
test('a mismatched state is rejected and still clears the pending one', () async {
await issueAppAuthState(server);
final state = await issueAppAuthState(server);
expect(await consumeAppAuthState('not-the-real-one'), isNull);
// The pending state was wiped — replaying the right value now also fails.
expect(await consumeAppAuthState('anything'), isNull);
expect(await consumeAppAuthState(state), isNull);
});
test('null and empty received values are rejected', () async {

View File

@@ -25,6 +25,18 @@ import 'package:wger/core/http_overrides.dart';
class _FakeCertificate extends Fake implements X509Certificate {}
/// Records the certificate callback the code under test installs on it.
class _RecordingHttpClient extends Fake implements HttpClient {
bool Function(X509Certificate, String, int)? callback;
@override
set badCertificateCallback(bool Function(X509Certificate, String, int)? value) =>
callback = value;
@override
void close({bool force = false}) {}
}
void main() {
final cert = _FakeCertificate();
@@ -139,11 +151,18 @@ void main() {
});
});
test('syncHttpClientFactory builds a dart:io backed client', () {
final client = WgerHttpOverrides.syncHttpClientFactory('gym.example.com')();
test('syncHttpClientFactory builds a dart:io backed client exempting the host', () {
final inner = _RecordingHttpClient();
final client = HttpOverrides.runZoned(
() => WgerHttpOverrides.syncHttpClientFactory('gym.example.com')(),
createHttpClient: (_) => inner,
);
addTearDown(client.close);
expect(client, isA<IOClient>());
expect(inner.callback, isNotNull);
expect(inner.callback!(cert, 'gym.example.com', 443), isTrue);
expect(inner.callback!(cert, 'other.example.com', 443), isFalse);
});
test('trustServer clears the host for a null, empty or hostless URL', () {

View File

@@ -16,6 +16,8 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'dart:async';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
@@ -40,6 +42,8 @@ class _FixedAuthNotifier extends AuthNotifier {
@override
Future<AuthState> build() async => _initial;
void switchTo(AuthStatus status) => state = AsyncData(AuthState(status: status));
}
@GenerateMocks([SharedPreferencesAsync, WgerBaseProvider])
@@ -227,19 +231,25 @@ void main() {
});
test('probe does not write back when the user logged out during the await', () async {
// fetch returns a valid prefix, but auth is loggedOut throughout.
// fetch returns a valid prefix, but only after the user has logged out.
// The notifier must not persist the value.
stubFetch(
responseBody: {
'results': [
{'image': 'https://wger.de/media/exercise-images/1/foo.png'},
],
},
);
final response = Completer<dynamic>();
final uri = Uri.parse('https://example/api/v2/exerciseimage/?limit=1');
when(mockBase.makeUrl(any, query: anyNamed('query'))).thenReturn(uri);
when(mockBase.fetch(uri)).thenAnswer((_) => response.future);
final container = makeContainer(authStatus: AuthStatus.loggedOut);
final container = makeContainer();
await container.read(mediaUrlPrefixProvider.future);
await container.read(mediaUrlPrefixProvider.notifier).probe();
final probe = container.read(mediaUrlPrefixProvider.notifier).probe();
(container.read(authProvider.notifier) as _FixedAuthNotifier).switchTo(AuthStatus.loggedOut);
response.complete({
'results': [
{'image': 'https://wger.de/media/exercise-images/1/foo.png'},
],
});
await probe;
await pumpEventQueue();
expect(container.read(mediaUrlPrefixProvider).asData?.value, isNull);
verifyNever(mockPrefs.setString(any, any));

View File

@@ -1,79 +1,66 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:wger/core/validators.dart';
import 'package:wger/l10n/generated/app_localizations.dart';
import 'package:wger/l10n/generated/app_localizations_en.dart';
import 'validators_test.mocks.dart';
@GenerateMocks([AppLocalizations])
void main() {
MockAppLocalizations mockI18n = MockAppLocalizations();
setUp(() {
mockI18n = MockAppLocalizations();
when(mockI18n.enterValue).thenReturn('Please enter a value');
when(mockI18n.invalidUrl).thenReturn('Invalid URL');
});
final i18n = AppLocalizationsEn();
test('Required field empty returns error', () {
final result = validateUrl('', mockI18n, required: true);
expect(result, isNotNull);
final result = validateUrl('', i18n, required: true);
expect(result, i18n.enterValue);
});
test('Optional field empty returns no error', () {
final result = validateUrl('', mockI18n, required: false);
final result = validateUrl('', i18n, required: false);
expect(result, isNull);
});
test('Invalid URL without http/https returns error', () {
final result = validateUrl('www.example.com', mockI18n);
expect(result, isNotNull);
final result = validateUrl('www.example.com', i18n);
expect(result, i18n.invalidUrl);
});
test('Invalid URL with wrong protocol returns error', () {
final result = validateUrl('gopher://', mockI18n);
expect(result, isNotNull);
final result = validateUrl('gopher://', i18n);
expect(result, i18n.invalidUrl);
});
test('Valid http URL returns no error', () {
final result = validateUrl('http://example.com', mockI18n);
final result = validateUrl('http://example.com', i18n);
expect(result, isNull);
});
test('Valid https URL returns no error', () {
final result = validateUrl('https://example.com', mockI18n);
final result = validateUrl('https://example.com', i18n);
expect(result, isNull);
});
test('Scheme-only URL with empty host returns error', () {
// Uri.parse('http://') succeeds with an empty host; the validator must
// still reject it.
expect(validateUrl('http://', mockI18n), isNotNull);
expect(validateUrl('https://', mockI18n), isNotNull);
expect(validateUrl('http://', i18n), i18n.invalidUrl);
expect(validateUrl('https://', i18n), i18n.invalidUrl);
});
group('validateDateRange', () {
setUp(() {
when(mockI18n.endBeforeStart).thenReturn('The end value cannot be before the start');
});
test('returns null when end is null', () {
expect(validateDateRange(DateTime(2024, 1, 1), null, mockI18n), isNull);
expect(validateDateRange(DateTime(2024, 1, 1), null, i18n), isNull);
});
test('returns null when end is after start', () {
expect(validateDateRange(DateTime(2024, 1, 1), DateTime(2024, 2, 1), mockI18n), isNull);
expect(validateDateRange(DateTime(2024, 1, 1), DateTime(2024, 2, 1), i18n), isNull);
});
test('returns null when end equals start', () {
final date = DateTime(2024, 1, 1);
expect(validateDateRange(date, date, mockI18n), isNull);
expect(validateDateRange(date, date, i18n), isNull);
});
test('returns an error when end is before start', () {
expect(validateDateRange(DateTime(2024, 2, 1), DateTime(2024, 1, 1), mockI18n), isNotNull);
expect(
validateDateRange(DateTime(2024, 2, 1), DateTime(2024, 1, 1), i18n),
i18n.endBeforeStart,
);
});
});
}

File diff suppressed because it is too large Load Diff

View File

@@ -60,12 +60,18 @@ void main() {
});
testWidgets('shows nothing when the value is null', (WidgetTester tester) async {
// With onCleared, so the clear button is left out for the missing value
// and not merely for want of a callback
await tester.pumpWidget(
wrap(TimeInputWidget(value: null, labelText: 'Time', onChanged: (_) {})),
wrap(
TimeInputWidget(value: null, labelText: 'Time', onChanged: (_) {}, onCleared: () {}),
),
);
await tester.pumpAndSettle();
expect(tester.widget<EditableText>(find.byType(EditableText)).controller.text, isEmpty);
expect(find.byIcon(Icons.clear), findsNothing);
expect(find.byIcon(Icons.access_time_outlined), findsOneWidget);
});
testWidgets('clear button invokes onCleared and clears the display', (
@@ -191,7 +197,7 @@ void main() {
);
await tester.pumpAndSettle();
// Straight through the two halves, whose own pickers are covered above
// Straight through the two halves' callbacks, no picker is opened here
tester.widget<DateInputWidget>(find.byType(DateInputWidget)).onChanged(DateTime(2021, 1, 5));
await tester.pumpAndSettle();
expect(reported, DateTime(2021, 1, 5, 15, 30));

View File

@@ -16,8 +16,6 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'dart:async';
import 'package:drift/drift.dart' show Value;
import 'package:flutter_test/flutter_test.dart';
import 'package:wger/database/powersync/database.dart';
@@ -78,21 +76,6 @@ void main() {
expect((await repo.watchDrift().first)!.height, isNull);
});
test('re-emits after the row changes', () async {
await seed();
final iter = StreamIterator(repo.watchDrift());
await iter.moveNext();
expect(iter.current!.weightUnitStr, 'kg');
await repo.editLocalDrift(UserProfile(id: 1, weightUnitStr: 'lb'));
await iter.moveNext();
expect(iter.current!.weightUnitStr, 'lb');
await iter.cancel();
});
});
group('editLocalDrift', () {

View File

@@ -52,48 +52,6 @@ void main() {
});
});
group('field setters', () {
test('setAuthor / name / description / language setters update state', () {
final n = container.read(addExerciseProvider.notifier);
n.setAuthor('Alice');
n.setExerciseNameEn('Bench Press');
n.setExerciseNameTrans('Bankdrücken');
n.setDescriptionEn('English desc');
n.setDescriptionTrans('Deutsche Beschreibung');
n.setLanguageEn(testEnglish);
n.setLanguageTranslation(testGerman);
n.setAlternateNamesEn(['Chest Press']);
n.setAlternateNamesTrans(['Flachbankdrücken']);
final state = container.read(addExerciseProvider);
expect(state.author, 'Alice');
expect(state.exerciseNameEn, 'Bench Press');
expect(state.exerciseNameTrans, 'Bankdrücken');
expect(state.descriptionEn, 'English desc');
expect(state.descriptionTrans, 'Deutsche Beschreibung');
expect(state.languageEn, testEnglish);
expect(state.languageTranslation, testGerman);
expect(state.alternateNamesEn, ['Chest Press']);
expect(state.alternateNamesTrans, ['Flachbankdrücken']);
});
test('category, equipment, muscles setters update state', () {
final n = container.read(addExerciseProvider.notifier);
n.setCategory(testCategoryArms);
n.setEquipment([testEquipmentBench, testEquipmentDumbbell]);
n.setPrimaryMuscles([tMuscle1]);
n.setSecondaryMuscles([tMuscle2, tMuscle3]);
final state = container.read(addExerciseProvider);
expect(state.category, testCategoryArms);
expect(state.equipment, [testEquipmentBench, testEquipmentDumbbell]);
expect(state.primaryMuscles, [tMuscle1]);
expect(state.secondaryMuscles, [tMuscle2, tMuscle3]);
});
});
group('variation setters, mutual exclusion', () {
test('setVariationGroup clears variationConnectToExercise', () {
final n = container.read(addExerciseProvider.notifier);
@@ -151,77 +109,14 @@ void main() {
expect(container.read(addExerciseProvider).exerciseImages, [image1]);
});
test('stores an image with all license fields set', () {
final file = File('/tmp/licensed.jpg');
test('clear drops the attached images', () {
final n = container.read(addExerciseProvider.notifier);
n.addExerciseImages([image1, image2]);
container.read(addExerciseProvider.notifier).addExerciseImages([
ExerciseSubmissionImage(
imageFile: file,
title: 'Test Title',
author: 'Test Author',
authorUrl: 'https://test.com/author',
sourceUrl: 'https://source.com',
derivativeSourceUrl: 'https://derivative.com',
type: ImageType.lowPoly,
),
]);
final images = container.read(addExerciseProvider).exerciseImages;
expect(images.length, 1);
expect(images.first.imageFile.path, file.path);
});
test('accepts an image with only some metadata fields set', () {
container.read(addExerciseProvider.notifier).addExerciseImages([
ExerciseSubmissionImage(
imageFile: File('/tmp/partial.jpg'),
title: 'Only Title',
type: ImageType.threeD,
),
]);
expect(container.read(addExerciseProvider).exerciseImages.length, 1);
});
test('addExerciseImages with an empty list leaves the state empty', () {
container.read(addExerciseProvider.notifier).addExerciseImages([]);
n.clear();
expect(container.read(addExerciseProvider).exerciseImages, isEmpty);
});
test('clear on an empty image list is a no-op', () {
container.read(addExerciseProvider.notifier).clear();
expect(container.read(addExerciseProvider).exerciseImages, isEmpty);
});
test('accepts very long metadata strings', () {
final longString = 'a' * 1000;
container.read(addExerciseProvider.notifier).addExerciseImages([
ExerciseSubmissionImage(
imageFile: File('/tmp/long.jpg'),
title: longString,
author: longString,
authorUrl: 'https://example.com/$longString',
),
]);
expect(container.read(addExerciseProvider).exerciseImages.length, 1);
});
test('accepts special characters in metadata', () {
container.read(addExerciseProvider.notifier).addExerciseImages([
ExerciseSubmissionImage(
imageFile: File('/tmp/special.jpg'),
title: 'Title with émojis 🎉 and spëcial çhars',
author: 'Autör with ümlauts',
authorUrl: 'https://example.com/path?query=value&another=value',
),
]);
expect(container.read(addExerciseProvider).exerciseImages.length, 1);
});
});
group('clear', () {
@@ -348,7 +243,7 @@ void main() {
expect(container.read(addExerciseProvider).exerciseImages, hasLength(1));
});
test('passes the same payload that exerciseApiObject builds', () async {
test('submits the payload built from the wizard state', () async {
final n = container.read(addExerciseProvider.notifier);
n.setAuthor('Alice');
n.setExerciseNameEn('Bench Press');
@@ -356,18 +251,18 @@ void main() {
n.setLanguageEn(testEnglish);
n.setCategory(testCategoryArms);
n.setPrimaryMuscles([tMuscle1]);
// Snapshot the API object before submitting (the notifier clears state
// afterwards).
final expected = container.read(addExerciseProvider).exerciseApiObject;
when(mockRepo.submit(any)).thenAnswer((_) async => 1);
await n.postExerciseToServer();
final captured = verify(mockRepo.submit(captureAny)).captured.single as ExerciseSubmissionApi;
expect(captured.author, expected.author);
expect(captured.category, expected.category);
expect(captured.translations, hasLength(expected.translations.length));
expect(captured.author, 'Alice');
expect(captured.category, testCategoryArms.id);
expect(captured.muscles, [tMuscle1.id]);
expect(captured.translations, hasLength(1));
expect(captured.translations.single.name, 'Bench Press');
expect(captured.translations.single.descriptionSource, 'English desc');
expect(captured.translations.single.language, testEnglish.id);
});
});
}

View File

@@ -16,6 +16,8 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
@@ -46,15 +48,49 @@ void main() {
author: 'Alice',
category: 1,
muscles: [1],
musclesSecondary: [],
equipment: [],
translations: [],
musclesSecondary: [2, 3],
equipment: [4],
variationGroup: 'chest',
variationConnectTo: 99,
translations: [
ExerciseTranslationSubmissionApi(
name: 'Bench Press',
descriptionSource: 'Lie down and press.',
language: 2,
author: 'Alice',
aliases: [ExerciseAliasSubmissionApi(alias: 'Chest Press')],
),
],
);
final id = await repo.submit(payload);
expect(id, 42);
verify(mockBase.post(payload.toJson(), uri)).called(1);
final captured = verify(mockBase.post(captureAny, uri)).captured.single;
// Round-trip through JSON like WgerBaseProvider.post does, so the nested
// translations show their wire names too
final body = jsonDecode(jsonEncode(captured)) as Map<String, dynamic>;
expect(body, {
'category': 1,
'muscles': [1],
'muscles_secondary': [2, 3],
'equipment': [4],
'license_author': 'Alice',
'variation_group': 'chest',
'variations_connect_to': 99,
'translations': [
{
'name': 'Bench Press',
'description_source': 'Lie down and press.',
'language': 2,
'license_author': 'Alice',
'aliases': [
{'alias': 'Chest Press'},
],
'comments': [],
},
],
});
});
});

View File

@@ -23,21 +23,6 @@ import '../../../../test_data/exercises.dart';
void main() {
group('AddExerciseState defaults', () {
test('starts with empty author, no language, no category', () {
const state = AddExerciseState();
expect(state.author, '');
expect(state.languageEn, isNull);
expect(state.languageTranslation, isNull);
expect(state.category, isNull);
expect(state.equipment, isEmpty);
expect(state.primaryMuscles, isEmpty);
expect(state.secondaryMuscles, isEmpty);
expect(state.alternateNamesEn, isEmpty);
expect(state.alternateNamesTrans, isEmpty);
expect(state.exerciseImages, isEmpty);
});
test('newVariation reflects whether variationConnectToExercise is set', () {
const noVariation = AddExerciseState();
const withVariation = AddExerciseState(variationConnectToExercise: 42);
@@ -113,15 +98,4 @@ void main() {
);
});
});
group('copyWith', () {
test('replaces only the named fields', () {
const original = AddExerciseState(author: 'Alice', exerciseNameEn: 'Press');
final copy = original.copyWith(author: 'Bob');
expect(copy.author, 'Bob');
expect(copy.exerciseNameEn, 'Press');
});
});
}

View File

@@ -1,117 +1,129 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
import 'package:wger/core/search_options.dart';
import 'package:wger/core/shared_preferences.dart';
import 'package:wger/features/exercises/models/category.dart';
import 'package:wger/features/exercises/models/exercise_filters.dart';
import 'package:wger/features/exercises/providers/exercise_filters_riverpod.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
setUp(() {
SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty();
});
test('default values are correct on first load', () async {
final container = ProviderContainer.test();
final filters = await container.read(exerciseFiltersProvider.future);
expect(filters.searchLanguage, SearchLanguage.currentAndEnglish);
expect(filters.searchMode, ExerciseSearchMode.fulltext);
expect(filters.selectedCategories, isEmpty);
});
test('chooseLanguage updates provider and saves to SharedPreferences', () async {
final container = ProviderContainer.test();
await container.read(exerciseFiltersProvider.future);
final notifier = container.read(exerciseFiltersProvider.notifier);
await notifier.chooseLanguage(SearchLanguage.all);
final filters = await container.read(exerciseFiltersProvider.future);
expect(filters.searchLanguage, SearchLanguage.all);
expect(
await PreferenceHelper.instance.getExerciseSearchLanguage(),
SearchLanguage.all,
);
});
test('chooseSearchMode updates provider and saves to SharedPreferences', () async {
final container = ProviderContainer.test();
await container.read(exerciseFiltersProvider.future);
final notifier = container.read(exerciseFiltersProvider.notifier);
await notifier.chooseSearchMode(ExerciseSearchMode.exact);
final filters = await container.read(exerciseFiltersProvider.future);
expect(filters.searchMode, ExerciseSearchMode.exact);
expect(
await PreferenceHelper.instance.getExerciseSearchMode(),
ExerciseSearchMode.exact,
);
});
test('toggleCategory adds and removes categories without persisting them', () async {
final container = ProviderContainer.test();
await container.read(exerciseFiltersProvider.future);
final notifier = container.read(exerciseFiltersProvider.notifier);
const abs = ExerciseCategory(id: 1, name: 'Abs');
const arms = ExerciseCategory(id: 2, name: 'Arms');
// Add two categories
notifier.toggleCategory(abs);
notifier.toggleCategory(arms);
var filters = await container.read(exerciseFiltersProvider.future);
expect(filters.selectedCategories, {abs, arms});
// Tapping an already-selected category removes it
notifier.toggleCategory(abs);
filters = await container.read(exerciseFiltersProvider.future);
expect(filters.selectedCategories, {arms});
// clearCategories empties the set
notifier.clearCategories();
filters = await container.read(exerciseFiltersProvider.future);
expect(filters.selectedCategories, isEmpty);
});
test('resetAll clears the category selection', () async {
final container = ProviderContainer.test();
await container.read(exerciseFiltersProvider.future);
final notifier = container.read(exerciseFiltersProvider.notifier);
notifier.toggleCategory(const ExerciseCategory(id: 1, name: 'Abs'));
await notifier.resetAll();
final filters = await container.read(exerciseFiltersProvider.future);
expect(filters.selectedCategories, isEmpty);
});
test('settings persist across provider container restart', () async {
// create container, set values, destroy, create new container
final container1 = ProviderContainer.test();
await container1.read(exerciseFiltersProvider.future);
await container1
.read(exerciseFiltersProvider.notifier)
.chooseLanguage(
SearchLanguage.current,
);
await container1
.read(exerciseFiltersProvider.notifier)
.chooseSearchMode(
ExerciseSearchMode.exact,
);
container1.dispose();
// New container
final container2 = ProviderContainer.test();
final filters = await container2.read(exerciseFiltersProvider.future);
expect(filters.searchLanguage, SearchLanguage.current);
expect(filters.searchMode, ExerciseSearchMode.exact);
});
}
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
import 'package:wger/core/search_options.dart';
import 'package:wger/core/shared_preferences.dart';
import 'package:wger/features/exercises/models/category.dart';
import 'package:wger/features/exercises/models/exercise_filters.dart';
import 'package:wger/features/exercises/providers/exercise_filters_riverpod.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
setUp(() {
SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty();
});
test('default values are correct on first load', () async {
final container = ProviderContainer.test();
final filters = await container.read(exerciseFiltersProvider.future);
expect(filters.searchLanguage, SearchLanguage.currentAndEnglish);
expect(filters.searchMode, ExerciseSearchMode.fulltext);
expect(filters.selectedCategories, isEmpty);
});
test('chooseLanguage updates provider and saves to SharedPreferences', () async {
final container = ProviderContainer.test();
await container.read(exerciseFiltersProvider.future);
final notifier = container.read(exerciseFiltersProvider.notifier);
await notifier.chooseLanguage(SearchLanguage.all);
final filters = await container.read(exerciseFiltersProvider.future);
expect(filters.searchLanguage, SearchLanguage.all);
expect(
await PreferenceHelper.instance.getExerciseSearchLanguage(),
SearchLanguage.all,
);
});
test('chooseSearchMode updates provider and saves to SharedPreferences', () async {
final container = ProviderContainer.test();
await container.read(exerciseFiltersProvider.future);
final notifier = container.read(exerciseFiltersProvider.notifier);
await notifier.chooseSearchMode(ExerciseSearchMode.exact);
final filters = await container.read(exerciseFiltersProvider.future);
expect(filters.searchMode, ExerciseSearchMode.exact);
expect(
await PreferenceHelper.instance.getExerciseSearchMode(),
ExerciseSearchMode.exact,
);
});
test('toggleCategory adds and removes categories without persisting them', () async {
final container = ProviderContainer.test();
await container.read(exerciseFiltersProvider.future);
final notifier = container.read(exerciseFiltersProvider.notifier);
const abs = ExerciseCategory(id: 1, name: 'Abs');
const arms = ExerciseCategory(id: 2, name: 'Arms');
// Add two categories
notifier.toggleCategory(abs);
notifier.toggleCategory(arms);
var filters = await container.read(exerciseFiltersProvider.future);
expect(filters.selectedCategories, {abs, arms});
// Tapping an already-selected category removes it
notifier.toggleCategory(abs);
filters = await container.read(exerciseFiltersProvider.future);
expect(filters.selectedCategories, {arms});
// clearCategories empties the set
notifier.clearCategories();
filters = await container.read(exerciseFiltersProvider.future);
expect(filters.selectedCategories, isEmpty);
});
test('resetAll clears the category selection and persists the defaults', () async {
final container = ProviderContainer.test();
await container.read(exerciseFiltersProvider.future);
final notifier = container.read(exerciseFiltersProvider.notifier);
await notifier.chooseLanguage(SearchLanguage.all);
await notifier.chooseSearchMode(ExerciseSearchMode.exact);
notifier.toggleCategory(const ExerciseCategory(id: 1, name: 'Abs'));
await notifier.resetAll();
final filters = await container.read(exerciseFiltersProvider.future);
expect(filters.selectedCategories, isEmpty);
expect(filters.searchLanguage, SearchLanguage.currentAndEnglish);
expect(filters.searchMode, ExerciseSearchMode.fulltext);
expect(
await PreferenceHelper.instance.getExerciseSearchLanguage(),
SearchLanguage.currentAndEnglish,
);
expect(
await PreferenceHelper.instance.getExerciseSearchMode(),
ExerciseSearchMode.fulltext,
);
});
test('settings persist across provider container restart', () async {
// create container, set values, destroy, create new container
final container1 = ProviderContainer.test();
await container1.read(exerciseFiltersProvider.future);
await container1
.read(exerciseFiltersProvider.notifier)
.chooseLanguage(
SearchLanguage.current,
);
await container1
.read(exerciseFiltersProvider.notifier)
.chooseSearchMode(
ExerciseSearchMode.exact,
);
container1.dispose();
// New container
final container2 = ProviderContainer.test();
final filters = await container2.read(exerciseFiltersProvider.future);
expect(filters.searchLanguage, SearchLanguage.current);
expect(filters.searchMode, ExerciseSearchMode.exact);
});
}

View File

@@ -502,39 +502,4 @@ void main() {
expect(await repo.searchExerciseServerWithSearchMode('bench'), [7, 9]);
});
});
group('reference-data watchers', () {
test('watchCategoriesDrift emits the seeded categories', () async {
await seedCategory(testCategoryArms.id, 'Arms');
await seedCategory(testCategoryLegs.id, 'Legs');
final categories = await repo.watchCategoriesDrift().first;
expect(categories.map((c) => c.id).toSet(), {testCategoryArms.id, testCategoryLegs.id});
});
test('watchEquipmentDrift emits the seeded equipment', () async {
await seedEquipment(testEquipmentBench.id, 'Bench');
final equipment = await repo.watchEquipmentDrift().first;
expect(equipment.single.id, testEquipmentBench.id);
});
test('watchMusclesDrift emits the seeded muscles', () async {
await seedMuscle(tMuscle1.id, 'Pec');
final muscles = await repo.watchMusclesDrift().first;
expect(muscles.single.id, tMuscle1.id);
});
test('watchLanguagesDrift emits the seeded languages', () async {
await seedLanguage(testEnglish.id, 'en', 'English');
final languages = await repo.watchLanguagesDrift().first;
expect(languages.single.id, testEnglish.id);
});
});
}

View File

@@ -16,6 +16,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:material_ui/material_ui.dart';
import 'package:mockito/annotations.dart';
@@ -28,7 +29,9 @@ import 'package:wger/features/exercises/models/category.dart';
import 'package:wger/features/exercises/models/equipment.dart';
import 'package:wger/features/exercises/models/exercise.dart';
import 'package:wger/features/exercises/models/muscle.dart';
import 'package:wger/features/exercises/providers/add_exercise_notifier.dart';
import 'package:wger/features/exercises/providers/add_exercise_repository.dart';
import 'package:wger/features/exercises/providers/add_exercise_state.dart';
import 'package:wger/features/exercises/providers/exercise_repository.dart';
import 'package:wger/features/exercises/providers/exercises_notifier.dart';
import 'package:wger/features/exercises/screens/add_exercise_screen.dart';
@@ -97,6 +100,9 @@ void main() {
);
}
AddExerciseState wizardState(WidgetTester tester) =>
ProviderScope.containerOf(tester.element(find.byType(Stepper))).read(addExerciseProvider);
int currentStep(WidgetTester tester) => tester.widget<Stepper>(find.byType(Stepper)).currentStep;
AppLocalizations l10nOf(WidgetTester tester) =>
@@ -171,49 +177,41 @@ void main() {
await tester.pumpWidget(createExerciseScreen());
await tester.pumpAndSettle();
final context = tester.element(find.byType(Stepper));
final l10n = AppLocalizations.of(context);
// Author is prefilled, so the category is the only other required field
await pickFromDropdown(tester, const Key('category-dropdown'), testCategoryArms.name);
await tapNext(tester);
final nextButton = find.widgetWithText(ElevatedButton, l10n.next).first;
expect(nextButton, findsOneWidget);
await tester.ensureVisible(nextButton);
await tester.pumpAndSettle();
await tester.tap(nextButton);
await tester.pumpAndSettle();
final stepper = tester.widget<Stepper>(find.byType(Stepper));
expect(stepper.currentStep, equals(0));
expect(currentStep(tester), 0);
expect(
find.descendant(
of: fieldOf(Step1Basics, 0),
matching: find.text(l10nOf(tester).enterValue),
),
findsOneWidget,
);
expect(find.text(l10nOf(tester).selectEntry), findsNothing);
});
testWidgets('User can enter exercise name in text field', (tester) async {
testWidgets('Typing the exercise name stores it in the wizard state', (tester) async {
setTrustworthy(true);
await tester.pumpWidget(createExerciseScreen());
await tester.pumpAndSettle();
final nameField = find.byType(TextFormField).first;
expect(nameField, findsOneWidget);
await tester.enterText(nameField, 'Bench Press');
await tester.enterText(fieldOf(Step1Basics, 0), 'Bench Press');
await tester.pump();
expect(find.text('Bench Press'), findsOneWidget);
expect(wizardState(tester).exerciseNameEn, 'Bench Press');
});
testWidgets('Alternative names field accepts multiple lines of text', (tester) async {
testWidgets('Alternative names field stores one name per line', (tester) async {
setTrustworthy(true);
await tester.pumpWidget(createExerciseScreen());
await tester.pumpAndSettle();
final textFields = find.byType(TextFormField);
expect(textFields, findsWidgets);
final alternativeNamesField = textFields.at(1);
await tester.enterText(alternativeNamesField, 'Chest Press\nFlat Bench Press');
await tester.enterText(fieldOf(Step1Basics, 1), 'Chest Press\nFlat Bench Press');
await tester.pump();
expect(find.text('Chest Press\nFlat Bench Press'), findsOneWidget);
expect(wizardState(tester).alternateNamesEn, ['Chest Press', 'Flat Bench Press']);
});
testWidgets('Category dropdown is required for form submission', (tester) async {
@@ -221,22 +219,14 @@ void main() {
await tester.pumpWidget(createExerciseScreen());
await tester.pumpAndSettle();
final nameField = find.byType(TextFormField).first;
await tester.enterText(nameField, 'Test Exercise');
// Name typed and author prefilled, so only the category is missing
await tester.enterText(fieldOf(Step1Basics, 0), 'Test Exercise');
await tester.pump();
await tapNext(tester);
final context = tester.element(find.byType(Stepper));
final l10n = AppLocalizations.of(context);
final nextButton = find.widgetWithText(ElevatedButton, l10n.next).first;
await tester.ensureVisible(nextButton);
await tester.pumpAndSettle();
await tester.tap(nextButton);
await tester.pumpAndSettle();
final stepper = tester.widget<Stepper>(find.byType(Stepper));
expect(stepper.currentStep, equals(0));
expect(currentStep(tester), 0);
expect(find.text(l10nOf(tester).selectEntry), findsOneWidget);
expect(find.text(l10nOf(tester).enterValue), findsNothing);
});
});
@@ -280,17 +270,14 @@ void main() {
// --------------------------------------------------------------------------
group('Dropdown Selection Tests', () {
testWidgets('Category selection widgets exist in form', (tester) async {
testWidgets('Picking a category stores it in the wizard state', (tester) async {
setTrustworthy(true);
await tester.pumpWidget(createExerciseScreen());
await tester.pumpAndSettle();
expect(find.byType(AddExerciseStepper), findsOneWidget);
expect(find.byType(Stepper), findsOneWidget);
await pickFromDropdown(tester, const Key('category-dropdown'), testCategoryArms.name);
final stepper = tester.widget<Stepper>(find.byType(Stepper));
expect(stepper.steps.length, equals(6));
expect(stepper.steps[0].content.runtimeType.toString(), contains('Step1Basics'));
expect(wizardState(tester).category, testCategoryArms);
});
testWidgets('Form contains multiple selection fields', (tester) async {
@@ -336,18 +323,14 @@ void main() {
expect(find.byType(Stepper), findsNothing);
});
testWidgets('Verified users can access all form fields', (tester) async {
testWidgets('Verified users get the form instead of the warning', (tester) async {
setTrustworthy(true);
await tester.pumpWidget(createExerciseScreen());
await tester.pumpAndSettle();
expect(find.byType(EmailNotVerified), findsNothing);
expect(find.byType(AddExerciseStepper), findsOneWidget);
expect(find.byType(Stepper), findsOneWidget);
expect(find.byType(TextFormField), findsWidgets);
final stepper = tester.widget<Stepper>(find.byType(Stepper));
expect(stepper.steps.length, equals(6));
});
testWidgets('Email verification warning displays correct message', (tester) async {

View File

@@ -16,8 +16,6 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:wger/core/network/base_provider.dart';
@@ -75,21 +73,6 @@ void main() {
expect(emitted.first.date.month, 5);
expect(emitted.last.date, DateTime.utc(2021, 2, 22));
});
test('re-emits after a row is added', () async {
final stream = repo.watchAllDrift();
final iter = StreamIterator(stream);
await iter.moveNext();
expect(iter.current, isEmpty);
await seed([getTestImages().first]);
await iter.moveNext();
expect(iter.current, hasLength(1));
await iter.cancel();
});
});
group('editLocalDrift', () {
@@ -125,14 +108,6 @@ void main() {
final rows = await readAll();
expect(rows.map((r) => r.id).toSet(), {1, 3, 4});
});
test('on a non-existent id is a no-op', () async {
await seed([getTestImages().first]);
await repo.deleteLocalDrift(999);
expect(await readAll(), hasLength(1));
});
});
// Note: addImageServer and editImageServer are not unit-tested here. Both

View File

@@ -21,9 +21,11 @@ import 'package:material_ui/material_ui.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:network_image_mock/network_image_mock.dart';
import 'package:wger/core/form_screen.dart';
import 'package:wger/core/network/network_provider.dart';
import 'package:wger/features/gallery/providers/gallery_repository.dart';
import 'package:wger/features/gallery/screens/gallery_screen.dart';
import 'package:wger/features/gallery/widgets/forms.dart';
import '../../../../test_data/gallery.dart';
import '../../../helpers/pump_app.dart';
@@ -48,9 +50,22 @@ void main() {
galleryRepositoryProvider.overrideWithValue(mockGalleryRepository),
],
locale: Locale(locale),
routes: {FormScreen.routeName: (_) => const FormScreen()},
);
}
testWidgets('Add button opens the image form when online', (WidgetTester tester) async {
await mockNetworkImagesFor(() => tester.pumpWidget(renderGalleryScreen()));
await tester.pumpAndSettle();
final fab = tester.widget<FloatingActionButton>(find.byType(FloatingActionButton));
expect(fab.onPressed, isNotNull);
await tester.tap(find.byType(FloatingActionButton));
await tester.pumpAndSettle();
expect(find.byType(ImageForm), findsOneWidget);
});
testWidgets('Add button is disabled when offline', (WidgetTester tester) async {
// Adding an image is a binary REST upload, so it needs connectivity.
await mockNetworkImagesFor(

View File

@@ -63,17 +63,22 @@ void main() {
expect(find.text('A very cool image from the gym'), findsOneWidget);
expect(find.byKey(const Key(SUBMIT_BUTTON_KEY_NAME)), findsOneWidget);
// Date can only be edited via the datepicker
// Date can only be edited via the datepicker, which opens on the image's month (May 2021)
await tester.tap(find.byKey(const Key('field-date')));
await tester.pump();
await tester.pumpAndSettle();
await tester.tap(find.text('15'));
await tester.tap(find.text('OK'));
await tester.tap(find.text('15'), warnIfMissed: false);
await tester.pumpAndSettle();
await tester.pump();
await tester.tap(find.byKey(const Key(SUBMIT_BUTTON_KEY_NAME)));
await tester.pump();
verifyNever(mockGalleryRepository.addImageServer(any, any));
verify(mockGalleryRepository.editLocalDrift(any));
final saved =
verify(mockGalleryRepository.editLocalDrift(captureAny)).captured.single as GalleryImage;
expect(saved.id, 1);
expect(saved.date, DateTime(2021, 5, 15));
expect(saved.description, 'A very cool image from the gym');
});
testWidgets('Test opening the form for a new image', (WidgetTester tester) async {

View File

@@ -138,23 +138,6 @@ void main() {
});
}
group('HealthSyncState', () {
test('default state has sync disabled', () {
const state = HealthSyncState();
expect(state.isEnabled, false);
expect(state.isSyncing, false);
expect(state.lastSyncCount, 0);
});
test('copyWith updates individual fields', () {
const state = HealthSyncState();
final updated = state.copyWith(isEnabled: true, lastSyncCount: 5);
expect(updated.isEnabled, true);
expect(updated.isSyncing, false);
expect(updated.lastSyncCount, 5);
});
});
group('enableSync', () {
test('returns null and stays disabled when permissions are denied', () async {
await PreferenceHelper.instance.setHealthSyncEnabled(false);

View File

@@ -16,6 +16,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:clock/clock.dart';
import 'package:collection/collection.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:material_ui/material_ui.dart';
@@ -444,26 +445,26 @@ void main() {
});
group('chartSeriesFor', () {
test('cuts both series at the range, after averaging over all points', () {
// The points reach back beyond the range so the first ones in it average
// Six weeks of daily points, one at noon each day up to today. The
// points reach back beyond the range so the first ones in it average
// the days before them instead of starting over at the cutoff
final points = [
for (var day = 0; day < 20; day++)
MeasurementChartEntry(
day.isEven ? 70 : 80,
DateTime.now().subtract(Duration(days: 19 - day)),
),
for (var day = 0; day < 40; day++)
MeasurementChartEntry(day.isEven ? 70 : 80, DateTime(2026, 3, 15 - 39 + day, 12)),
];
final (:entries, :average) = chartSeriesFor(
points,
ChartRange.lastMonth,
const ChartSettings(),
final (:entries, :average) = withClock(
Clock.fixed(DateTime(2026, 3, 15, 18)),
() => chartSeriesFor(points, ChartRange.lastWeek, const ChartSettings()),
);
expect(entries, hasLength(20));
expect(average, hasLength(20));
// The last point averages a full window, not just itself
expect(average.last.value, closeTo(75, 1));
// Today and the six days before it; the day before the cutoff is out
expect(entries.map((e) => e.date), [
for (var day = 9; day <= 15; day++) DateTime(2026, 3, day, 12),
]);
expect(average.map((e) => e.date), entries.map((e) => e.date));
// The first point in range averages a full window, not just itself (80)
expect(average.first.value, closeTo(75, 1));
});
});
group('niceBinWidth', () {

View File

@@ -45,24 +45,6 @@ void main() {
mockRepo = MockMeasurementRepository();
});
test('exposes the official body weight category', () async {
container = buildContainer(getBodyWeightCategory());
container.listen(bodyWeightCategoryOnlyProvider, (_, _) {});
await pumpEventQueue();
expect(container.read(bodyWeightCategoryOnlyProvider).value?.id, testBodyWeightCategoryId);
});
test('is null while no official category has been synced', () async {
container = buildContainer(null);
container.listen(bodyWeightCategoryOnlyProvider, (_, _) {});
await pumpEventQueue();
final async = container.read(bodyWeightCategoryOnlyProvider);
expect(async.hasValue, isTrue);
expect(async.value, isNull);
});
test('asks the repository for one category instead of for all of them', () async {
// Reading every category and keeping one made any other category's entry
// rebuild the weight screen, and the sync writes five sleep rows a night

View File

@@ -401,7 +401,10 @@ void main() {
final page = await repo.watchEntries('2', limit: 10).first;
expect(page.every((e) => e.categoryId == '2'), isTrue);
expect(
page.map((e) => e.id).toSet(),
getMeasurementEntries()['2']!.map((e) => e.id).toSet(),
);
});
});

View File

@@ -178,8 +178,12 @@ void main() {
await tester.pumpAndSettle();
// From the entries list, which shows the newest first
expect(find.text('11/15/2022'), findsWidgets);
expect(find.text('11/10/2022'), findsWidgets);
expect(find.text('11/15/2022'), findsOneWidget);
expect(find.text('11/10/2022'), findsOneWidget);
expect(
tester.getTopLeft(find.text('11/15/2022')).dy,
lessThan(tester.getTopLeft(find.text('11/10/2022')).dy),
);
});
testWidgets('Tests the localization of dates - DE', (WidgetTester tester) async {
@@ -188,7 +192,11 @@ void main() {
await tester.pumpAndSettle();
// From the entries list, which shows the newest first
expect(find.text('15.11.2022'), findsWidgets);
expect(find.text('10.11.2022'), findsWidgets);
expect(find.text('15.11.2022'), findsOneWidget);
expect(find.text('10.11.2022'), findsOneWidget);
expect(
tester.getTopLeft(find.text('15.11.2022')).dy,
lessThan(tester.getTopLeft(find.text('10.11.2022')).dy),
);
});
}

View File

@@ -179,10 +179,9 @@ void main() {
await tester.pumpAndSettle();
// The ends of the bar say which is which
expect(
tester.widgetList<ListTile>(find.byType(ListTile)).every((t) => t.leading == null),
isTrue,
);
final tiles = tester.widgetList<ListTile>(find.byType(ListTile));
expect(tiles, hasLength(2));
expect(tiles.every((t) => t.leading == null), isTrue);
});
testWidgets('falls back to lines when the readings are not paired', (tester) async {
@@ -270,6 +269,7 @@ void main() {
// Total sleep is no segment of the stack, so no colour identifies it
final tiles = tester.widgetList<ListTile>(find.byType(ListTile)).toList();
expect(tiles, hasLength(3));
expect(tiles.first.leading, isNull);
expect(tiles.skip(1).every((t) => t.leading != null), isTrue);
});

View File

@@ -75,18 +75,20 @@ void main() {
await tester.pumpWidget(wrap(const MeasurementCategoryForm()));
await tester.pumpAndSettle();
// Tap save without entering any text
// Fill the unit but leave the name empty, so only the name can complain
await tester.enterText(find.byType(TextFormField).at(1), 'cm');
await tester.tap(find.byType(ElevatedButton));
await tester.pumpAndSettle();
// Check for validation errors.
final error = find.byWidgetPredicate((widget) {
if (widget is TextField) {
return widget.decoration?.errorText != null;
}
return false;
});
expect(error, findsAtLeastNWidgets(1));
expect(
find.descendant(
of: find.byType(TextFormField).first,
matching: find.text('Please enter a value'),
),
findsOneWidget,
);
expect(find.text('Please enter a value'), findsOneWidget);
verifyNever(mockRepo.addLocalDriftCategory(any));
});
testWidgets('empty unit field fails validation', (tester) async {
@@ -98,8 +100,15 @@ void main() {
await tester.tap(find.byType(ElevatedButton));
await tester.pumpAndSettle();
// still on same screen
expect(find.byType(MeasurementCategoryForm), findsOneWidget);
expect(
find.descendant(
of: find.byType(TextFormField).at(1),
matching: find.text('Please enter a value'),
),
findsOneWidget,
);
expect(find.text('Please enter a value'), findsOneWidget);
verifyNever(mockRepo.addLocalDriftCategory(any));
});
testWidgets('the metric type is not offered', (tester) async {

View File

@@ -80,8 +80,12 @@ void main() {
testWidgets('offers neither body weight nor the components', (tester) async {
// Body weight is the server's category and a component comes with its
// group, so neither is something to start here
// Tall enough for the whole list: the ListView only builds what is in
// view, and findsNothing on an unbuilt tile would prove nothing
setTestViewSize(tester, const Size(800, 5000));
await tester.pumpWidget(wrap());
await tester.pumpAndSettle();
expect(tester.state<ScrollableState>(find.byType(Scrollable)).position.maxScrollExtent, 0);
final context = tester.element(find.byType(MetricPickerSheet));
for (final hidden in [

View File

@@ -69,6 +69,16 @@ void main() {
);
}
String weightText(WidgetTester tester) => tester
.widget<EditableText>(
find.descendant(
of: find.byKey(const Key('weightInput')),
matching: find.byType(EditableText),
),
)
.controller
.text;
testWidgets('Correctly prefills and localizes the data - en', (WidgetTester tester) async {
await tester.pumpWidget(createWeightForm(entry: testWeightEntry1));
await tester.pumpAndSettle();
@@ -113,10 +123,10 @@ void main() {
await tester.pumpAndSettle();
expect(find.text('shiba inu'), findsNothing);
// Quick-change still works on the now-empty field
// Quick-change on the now-empty field has nothing to step from
await tester.tap(find.byKey(const Key('stepper-minus-0')));
await tester.pumpAndSettle();
expect(find.text('shiba inu'), findsNothing);
expect(weightText(tester), isEmpty);
});
testWidgets('Accepts a dot as decimal separator in the de locale', (WidgetTester tester) async {
@@ -129,9 +139,25 @@ void main() {
expect(find.text('81,5'), findsOneWidget);
});
testWidgets('Widget works if there is no last entry', (WidgetTester tester) async {
testWidgets('Without an entry it starts empty in kg and saves a new entry', (
WidgetTester tester,
) async {
await tester.pumpWidget(createWeightForm());
await tester.pumpAndSettle();
expect(weightText(tester), isEmpty);
expect(find.text('kg'), findsOneWidget);
await tester.enterText(find.byKey(const Key('weightInput')), '75');
await tester.tap(find.byKey(const Key(SUBMIT_BUTTON_KEY_NAME)));
await tester.pumpAndSettle();
final saved = verify(mockRepo.addLocalDrift(captureAny)).captured.single as MeasurementEntry;
expect(saved.id, isNull);
expect(saved.categoryId, testBodyWeightCategoryId);
expect(saved.value, 75);
expect(saved.extraData, {'unit': 'kg'});
verifyNever(mockRepo.updateLocalDrift(any));
});
testWidgets('Saving keeps an afternoon (PM) time intact and takes the edited notes', (

View File

@@ -17,6 +17,8 @@
*/
import 'package:flutter_test/flutter_test.dart';
import 'package:wger/features/nutrition/models/meal.dart';
import 'package:wger/features/nutrition/models/meal_item.dart';
import 'package:wger/features/nutrition/models/nutritional_goals.dart';
import 'package:wger/features/nutrition/models/nutritional_plan.dart';
import 'package:wger/features/nutrition/models/nutritional_values.dart';
@@ -108,8 +110,29 @@ void main() {
expect(meal.plannedNutritionalValues, values);
});
test('Test that the getter returns all meal items for a plan', () {
expect(plan.dedupMealItems, plan.meals[0].mealItems + plan.meals[1].mealItems);
test('dedupMealItems drops items with the same amount and ingredient', () {
final item1 = MealItem(ingredientId: 1, amount: 100);
final item2 = MealItem(ingredientId: 2, amount: 75);
final duplicate = MealItem(ingredientId: 1, amount: 100);
final otherAmount = MealItem(ingredientId: 1, amount: 50);
final otherIngredient = MealItem(ingredientId: 3, amount: 100);
final planWithDuplicates = NutritionalPlan(
description: 'duplicates',
creationDate: DateTime(2024, 5, 4),
startDate: DateTime(2024, 5, 4),
meals: [
Meal(mealItems: [item1, item2]),
Meal(mealItems: [duplicate, otherAmount, otherIngredient]),
],
);
final result = planWithDuplicates.dedupMealItems;
expect(result, hasLength(4));
expect(result[0], same(item1));
expect(result[1], same(item2));
expect(result[2], same(otherAmount));
expect(result[3], same(otherIngredient));
});
});
}

View File

@@ -16,10 +16,13 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:fake_async/fake_async.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:wger/core/network/network_provider.dart';
import 'package:wger/core/search_options.dart';
import 'package:wger/features/nutrition/models/ingredient.dart';
import 'package:wger/features/nutrition/models/ingredient_filters.dart';
import 'package:wger/features/nutrition/providers/ingredient_filters_notifier.dart';
@@ -107,71 +110,143 @@ void main() {
});
});
group('ingredientByIdProvider', () {
test('reads from the repository by id', () async {
final apple = makeIngredient(1, 'Apple');
when(mockRepo.getById(1)).thenAnswer((_) async => apple);
group('searchedIngredientsProvider', () {
const debounce = Duration(milliseconds: 350);
final container = makeContainer();
final result = await container.read(ingredientByIdProvider(1).future);
expect(result?.id, 1);
verify(mockRepo.getById(1)).called(1);
});
test('returns null when the repo returns null', () async {
when(mockRepo.getById(99)).thenAnswer((_) async => null);
final container = makeContainer();
final result = await container.read(ingredientByIdProvider(99).future);
expect(result, isNull);
});
test('concurrent reads of the same id share a single repo call', () async {
final apple = makeIngredient(1, 'Apple');
when(mockRepo.getById(1)).thenAnswer((_) async => apple);
final container = makeContainer();
final results = await Future.wait([
container.read(ingredientByIdProvider(1).future),
container.read(ingredientByIdProvider(1).future),
]);
expect(results.map((i) => i?.id), [1, 1]);
// Riverpod's per-family caching dedupes the repo call.
verify(mockRepo.getById(1)).called(1);
});
});
group('ingredientByIdStreamProvider', () {
test('emits each value the repository stream emits', () async {
final apple = makeIngredient(1, 'Apple');
final appleRenamed = makeIngredient(1, 'Apple Renamed');
void stubSearch() {
when(
mockRepo.watchById(1),
).thenAnswer((_) => Stream<Ingredient?>.fromIterable([apple, appleRenamed]));
mockRepo.search(
any,
isOnline: anyNamed('isOnline'),
searchLanguage: anyNamed('searchLanguage'),
isVegan: anyNamed('isVegan'),
isVegetarian: anyNamed('isVegetarian'),
nutriscoreMax: anyNamed('nutriscoreMax'),
),
).thenAnswer((inv) async => [makeIngredient(1, inv.positionalArguments.first as String)]);
}
final container = makeContainer();
// Explicit listen() keeps the autoDispose stream alive long enough
// to drain.
container.listen(ingredientByIdStreamProvider(1), (_, _) {});
await pumpEventQueue();
final result = container.read(ingredientByIdStreamProvider(1)).requireValue;
ProviderContainer makeSearchContainer({
required bool isOnline,
IngredientFilters filters = const IngredientFilters(searchTerm: 'apple'),
}) {
return ProviderContainer.test(
overrides: [
ingredientRepositoryProvider.overrideWithValue(mockRepo),
networkStatusProvider.overrideWithValue(isOnline),
_testFiltersProvider.overrideWith(() => _TestFilters(filters)),
ingredientFiltersSyncProvider.overrideWith((ref) => ref.watch(_testFiltersProvider)),
],
);
}
expect(result?.name, 'Apple Renamed');
verify(mockRepo.watchById(1)).called(1);
test('searches with the filter state once the debounce window elapsed', () {
fakeAsync((async) {
stubSearch();
final container = makeSearchContainer(
isOnline: true,
filters: const IngredientFilters(
searchTerm: 'banana',
searchLanguage: SearchLanguage.all,
isVegan: true,
nutriscoreMax: NutriScore.b,
),
);
container.listen(searchedIngredientsProvider, (_, _) {});
async.elapse(debounce - const Duration(milliseconds: 1));
verifyNever(
mockRepo.search(
any,
isOnline: anyNamed('isOnline'),
searchLanguage: anyNamed('searchLanguage'),
isVegan: anyNamed('isVegan'),
isVegetarian: anyNamed('isVegetarian'),
nutriscoreMax: anyNamed('nutriscoreMax'),
),
);
async.elapse(const Duration(milliseconds: 1));
verify(
mockRepo.search(
'banana',
isOnline: true,
searchLanguage: SearchLanguage.all,
isVegan: true,
isVegetarian: false,
nutriscoreMax: NutriScore.b,
),
).called(1);
expect(container.read(searchedIngredientsProvider).requireValue.single.name, 'banana');
});
});
test('emits null when no row with that id exists yet', () async {
when(mockRepo.watchById(99)).thenAnswer((_) => Stream.value(null));
test('searches offline when the network is down', () {
fakeAsync((async) {
stubSearch();
final container = makeSearchContainer(isOnline: false);
container.listen(searchedIngredientsProvider, (_, _) {});
final container = makeContainer();
container.listen(ingredientByIdStreamProvider(99), (_, _) {});
await pumpEventQueue();
final result = container.read(ingredientByIdStreamProvider(99)).requireValue;
async.elapse(debounce);
expect(result, isNull);
final isOnline = verify(
mockRepo.search(
'apple',
isOnline: captureAnyNamed('isOnline'),
searchLanguage: anyNamed('searchLanguage'),
isVegan: anyNamed('isVegan'),
isVegetarian: anyNamed('isVegetarian'),
nutriscoreMax: anyNamed('nutriscoreMax'),
),
).captured.single;
expect(isOnline, isFalse);
});
});
test('a filter change within the debounce window cancels the pending search', () {
fakeAsync((async) {
stubSearch();
final container = makeSearchContainer(
isOnline: true,
filters: const IngredientFilters(searchTerm: 'ap'),
);
container.listen(searchedIngredientsProvider, (_, _) {});
async.elapse(const Duration(milliseconds: 200));
container
.read(_testFiltersProvider.notifier)
.set(const IngredientFilters(searchTerm: 'apple'));
async.elapse(debounce);
final terms = verify(
mockRepo.search(
captureAny,
isOnline: anyNamed('isOnline'),
searchLanguage: anyNamed('searchLanguage'),
isVegan: anyNamed('isVegan'),
isVegetarian: anyNamed('isVegetarian'),
nutriscoreMax: anyNamed('nutriscoreMax'),
),
).captured;
expect(terms, ['apple']);
expect(container.read(searchedIngredientsProvider).requireValue.single.name, 'apple');
});
});
});
}
/// Holds the filter state so a test can change it while a search is pending.
final _testFiltersProvider = NotifierProvider<_TestFilters, IngredientFilters>(
() => _TestFilters(const IngredientFilters()),
);
class _TestFilters extends Notifier<IngredientFilters> {
_TestFilters(this._initial);
final IngredientFilters _initial;
@override
IngredientFilters build() => _initial;
void set(IngredientFilters filters) => state = filters;
}

View File

@@ -277,9 +277,15 @@ void main() {
final uri = Uri.https('localhost', 'api/v2/ingredientinfo/');
test('returns empty for terms <= 1 char', () async {
// Stubbed so a missing guard reaches the server instead of throwing a MissingStubError.
when(mockBase.makeUrl('ingredientinfo', query: anyNamed('query'))).thenReturn(uri);
when(
mockBase.fetch(uri, timeout: anyNamed('timeout')),
).thenAnswer((_) async => {'results': []});
expect(await repo.searchIngredientServer(''), isEmpty);
expect(await repo.searchIngredientServer('a'), isEmpty);
verifyNever(mockBase.fetch(any));
verifyNever(mockBase.fetch(any, timeout: anyNamed('timeout')));
});
test('current language: passes the languageCode in the query', () async {

View File

@@ -124,16 +124,20 @@ void main() {
await tester.pumpWidget(createHomeScreen());
await tester.pumpAndSettle();
await tester.tap(find.byIcon(Icons.delete).first);
// Delete the second plan, so a handler that always deletes the first one fails.
final tile = find.ancestor(of: find.text('test plan 2'), matching: find.byType(ListTile));
await tester.tap(find.descendant(of: tile, matching: find.byIcon(Icons.delete)));
await tester.pumpAndSettle();
// Confirmation dialog
expect(find.byType(AlertDialog), findsOneWidget);
// Confirm tap, actual delete now goes through Drift + PowerSync (not
// REST), so we don't assert on the REST mock here.
// Confirm tap, the delete goes through Drift + PowerSync (not REST).
await tester.tap(find.text('Delete'));
await tester.pumpAndSettle();
expect(find.byType(AlertDialog), findsNothing);
expect(verify(mockNutritionRepo.deleteLocalDrift(captureAny)).captured, [planUuid2]);
});
testWidgets('Test the form on the nutritional plan screen', (WidgetTester tester) async {
@@ -170,12 +174,13 @@ void main() {
);
expect(deleteButton.onPressed, isNotNull);
await tester.tap(find.byIcon(Icons.delete).first);
final tile = find.ancestor(of: find.text('test plan 1'), matching: find.byType(ListTile));
await tester.tap(find.descendant(of: tile, matching: find.byIcon(Icons.delete)));
await tester.pumpAndSettle();
expect(find.byType(AlertDialog), findsOneWidget);
await tester.tap(find.text('Delete'));
await tester.pumpAndSettle();
verify(mockNutritionRepo.deleteLocalDrift(any)).called(1);
expect(verify(mockNutritionRepo.deleteLocalDrift(captureAny)).captured, [planUuid1]);
});
testWidgets('Tests the localization of dates - EN', (WidgetTester tester) async {

View File

@@ -18,6 +18,8 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:material_ui/material_ui.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart';
import 'package:wger/features/nutrition/models/ingredient.dart';
import 'package:wger/features/nutrition/models/ingredient_image.dart';
import 'package:wger/features/nutrition/widgets/ingredient_dialogs.dart';
@@ -25,6 +27,17 @@ import 'package:wger/features/nutrition/widgets/ingredient_dialogs.dart';
import '../../../../test_data/nutritional_plans.dart';
import '../../../helpers/pump_app.dart';
/// Captures `launchUrl(...)` calls so no real browser opens.
class _FakeUrlLauncher extends Fake with MockPlatformInterfaceMixin implements UrlLauncherPlatform {
final launchedUrls = <String>[];
@override
Future<bool> launchUrl(String url, LaunchOptions options) async {
launchedUrls.add(url);
return true;
}
}
Future<void> pumpIngredientDetailsDialog(
WidgetTester tester, {
required Ingredient ingredient,
@@ -180,9 +193,14 @@ void main() {
);
testWidgets(
'tapping Open Food Facts button closes the dialog',
'tapping Open Food Facts button opens the product form and closes the dialog',
(WidgetTester tester) async {
// Arrange
final original = UrlLauncherPlatform.instance;
final fakeLauncher = _FakeUrlLauncher();
UrlLauncherPlatform.instance = fakeLauncher;
addTearDown(() => UrlLauncherPlatform.instance = original);
const snapshot = AsyncSnapshot<Ingredient?>.withData(
ConnectionState.done,
null,
@@ -207,7 +225,8 @@ void main() {
);
await tester.pumpAndSettle();
// Assert: Dialog should be closed
// Assert: the product form was opened and the dialog closed
expect(fakeLauncher.launchedUrls, ['https://world.openfoodfacts.org/cgi/product.pl']);
expect(find.byType(AlertDialog), findsNothing);
},
);

View File

@@ -123,9 +123,12 @@ void main() {
await tester.enterText(find.byKey(const Key('field-name')), 'test meal');
await tester.tap(find.byKey(const Key(SUBMIT_BUTTON_KEY_NAME)));
// Correct method was called
verify(mockRepo.editMealLocalDrift(any));
// Correct method was called, with the typed name
verifyNever(mockRepo.addMealLocalDrift(any));
final meal = verify(mockRepo.editMealLocalDrift(captureAny)).captured.single as Meal;
expect(meal.id, testMealUuid1);
expect(meal.name, 'test meal');
expect(meal.time, const TimeOfDay(hour: 17, minute: 0));
});
testWidgets('a new meal defaults to the current time', (WidgetTester tester) async {

View File

@@ -94,9 +94,11 @@ void main() {
await tester.enterText(find.byKey(const Key('field-description')), 'New description');
await tester.tap(find.byKey(const Key(SUBMIT_BUTTON_KEY_NAME)));
// Correct method was called
verify(mockRepo.editLocalDrift(any));
// Correct method was called, with the typed description
verifyNever(mockRepo.addPlanLocalDrift(any));
final saved = verify(mockRepo.editLocalDrift(captureAny)).captured.single as NutritionalPlan;
expect(saved.id, planUuid1);
expect(saved.description, 'New description');
});
testWidgets('Goal macros survive a no-op save in a comma-decimal locale', (
@@ -145,8 +147,10 @@ void main() {
await tester.enterText(find.byKey(const Key('field-description')), 'New cool plan');
await tester.tap(find.byKey(const Key(SUBMIT_BUTTON_KEY_NAME)));
// Correct method was called
// Correct method was called, with the typed description
verifyNever(mockRepo.editLocalDrift(any));
verify(mockRepo.addPlanLocalDrift(any));
final saved = verify(mockRepo.addPlanLocalDrift(captureAny)).captured.single as NutritionalPlan;
expect(saved.id, isNull);
expect(saved.description, 'New cool plan');
});
}

View File

@@ -596,48 +596,5 @@ void main() {
expect(repoRead, true);
verify(mockRepo.fetchAndSetRoutineFullServer(101)).called(1);
});
test('watching the provider triggers a single structure fetch', () async {
// Arrange
when(
mockRepo.fetchAndSetRoutineFullServer(101),
).thenAnswer((_) async => Routine(id: 101, name: 'Test routine'));
final container = ProviderContainer.test(
overrides: [
routinesRepositoryProvider.overrideWithValue(mockRepo),
...ambientOverrides(),
],
);
// Act
container.listen(routineHydrationProvider(101), (_, _) {});
await container.read(routineHydrationProvider(101).future);
// Assert
verify(mockRepo.fetchAndSetRoutineFullServer(101)).called(1);
});
test('concurrent watchers of the same routine share one fetch', () async {
// Arrange
when(
mockRepo.fetchAndSetRoutineFullServer(101),
).thenAnswer((_) async => Routine(id: 101, name: 'Test routine'));
final container = ProviderContainer.test(
overrides: [
routinesRepositoryProvider.overrideWithValue(mockRepo),
...ambientOverrides(),
],
);
// Act: two readers of the same family instance.
container.listen(routineHydrationProvider(101), (_, _) {});
await Future.wait([
container.read(routineHydrationProvider(101).future),
container.read(routineHydrationProvider(101).future),
]);
// Assert: a single shared roundtrip, not one per reader.
verify(mockRepo.fetchAndSetRoutineFullServer(101)).called(1);
});
});
}

View File

@@ -79,10 +79,6 @@ void main() {
// ---------------------------------------------------------------------------
group('Routines, Drift', () {
test('watchAllDrift emits an empty list when no routines exist', () async {
expect(await repo.watchAllDrift().first, isEmpty);
});
test('watchAllDrift sorts by start desc, then created desc', () async {
// Two routines share a start date; the newer `created` should win.
await seedRoutine(
@@ -132,26 +128,6 @@ void main() {
final emitted = await repo.watchAllDrift().first;
expect(emitted.map((r) => r.id), [2]);
});
test('watchWeightUnitsDrift emits seeded units', () async {
await db
.into(db.routineWeightUnitTable)
.insert(RoutineWeightUnitTableCompanion.insert(id: 1, name: 'kg'));
final units = await repo.watchWeightUnitsDrift().first;
expect(units.single.name, 'kg');
});
test('watchRepetitionUnitsDrift emits seeded units', () async {
await db
.into(db.routineRepetitionUnitTable)
.insert(RoutineRepetitionUnitTableCompanion.insert(id: 1, name: 'Repetitions'));
final units = await repo.watchRepetitionUnitsDrift().first;
expect(units.single.name, 'Repetitions');
});
});
group('Days, REST', () {
@@ -237,9 +213,10 @@ void main() {
when(mockBase.makeUrl('slot', id: 5)).thenReturn(uri);
when(mockBase.patch(any, uri)).thenAnswer((_) async => {});
await repo.editSlotServer(Slot.withData(id: 5, day: 1, order: 1));
await repo.editSlotServer(Slot.withData(id: 5, day: 1, order: 2, comment: 'warm up'));
verify(mockBase.patch(any, uri)).called(1);
final sent = verify(mockBase.patch(captureAny, uri)).captured.single;
expect(sent, {'day': 1, 'order': 2, 'comment': 'warm up', 'config': null});
});
test('deleteSlotServer sends DELETE for /slot/<id>/', () async {
@@ -309,7 +286,19 @@ void main() {
await repo.editSlotEntryServer(makeEntry(id: 5));
verify(mockBase.patch(any, uri)).called(1);
final sent = verify(mockBase.patch(captureAny, uri)).captured.single;
expect(sent, {
'slot': 1,
'order': 1,
'comment': '',
'type': 'normal',
'exercise': 1,
'repetition_unit': 1,
'repetition_rounding': 1,
'weight_unit': 1,
'weight_rounding': 1.25,
'config': null,
});
});
test('deleteSlotEntryServer sends DELETE for /slot-entry/<id>/', () async {
@@ -358,6 +347,16 @@ void main() {
await repo.addConfigServer(BaseConfig.firstIteration(5, 1), entry.key);
verify(mockBase.makeUrl(entry.value)).called(1);
final sent = verify(mockBase.post(captureAny, uri)).captured.single;
expect(sent, {
'slot_entry': 1,
'iteration': 1,
'value': 5,
'operation': 'r',
'step': 'abs',
'repeat': false,
'requirements': null,
});
});
}
@@ -371,7 +370,9 @@ void main() {
final result = await repo.editConfigServer(config, ConfigType.sets);
expect(result.id, 3);
verify(mockBase.patch(any, uri)).called(1);
final sent = verify(mockBase.patch(captureAny, uri)).captured.single as Map;
expect(sent['slot_entry'], 1);
expect(sent['value'], 4);
});
test('deleteConfigServer sends DELETE for /<config-path>/<id>/', () async {
@@ -424,7 +425,10 @@ void main() {
await repo.handleConfigServer(entry, 5, ConfigType.sets);
verify(mockBase.patch(any, uri)).called(1);
// The new value replaces the old 3 on the existing config
final sent = verify(mockBase.patch(captureAny, uri)).captured.single as Map;
expect(sent['value'], 5);
expect(sent['slot_entry'], 1);
});
test('value + no existing config → POST (add new)', () async {
@@ -435,7 +439,17 @@ void main() {
await repo.handleConfigServer(entry, 5, ConfigType.sets);
verify(mockBase.post(any, uri)).called(1);
// A first-iteration config for this entry, carrying the value
final sent = verify(mockBase.post(captureAny, uri)).captured.single;
expect(sent, {
'slot_entry': 1,
'iteration': 1,
'value': 5,
'operation': 'r',
'step': 'abs',
'repeat': false,
'requirements': null,
});
});
test('value=null + no existing config → no-op', () async {
@@ -479,6 +493,10 @@ void main() {
id: 325397,
name: 'Test workout',
description: 'Test workout abcd',
created: DateTime.utc(2022, 10, 10, 8, 30),
start: DateTime(2021, 12, 20),
end: DateTime(2022, 6, 6),
fitInWeek: true,
),
);
@@ -486,6 +504,20 @@ void main() {
expect(plan, isA<Routine>());
expect(plan.id, 325397);
expect(plan.description, 'Test workout abcd');
// The id is server-assigned and stays out of the payload; the dates go
// out as plain days, `created` as a UTC timestamp
final sent = verify(mockBaseProvider.post(captureAny, uri)).captured.single;
expect(sent, {
'created': '2022-10-10T08:30:00.000Z',
'name': 'Test workout',
'description': 'Test workout abcd',
'fit_in_week': true,
'is_template': false,
'is_public': false,
'start': '2021-12-20',
'end': '2022-06-06',
});
});
test('Smoke test fetchAndSetRoutineFullServer', () async {

View File

@@ -322,15 +322,6 @@ void main() {
expect(await readLogs(), isEmpty);
});
test('on a non-existent id is a no-op', () async {
final log = makeLog(sessionId: 'session-1');
await repo.addLocalDrift(log);
await repo.deleteLocalDrift('does-not-exist');
expect(await readLogs(), hasLength(1));
});
});
group('watchLogsByExerciseDrift', () {

View File

@@ -118,14 +118,6 @@ void main() {
expect(await db.select(db.workoutSessionTable).get(), isEmpty);
});
test('deleteLocalDrift on a non-existent id is a no-op', () async {
await repo.addLocalDrift(makeSession());
await repo.deleteLocalDrift('does-not-exist');
expect(await db.select(db.workoutSessionTable).get(), hasLength(1));
});
});
group('watchAllDrift', () {

View File

@@ -103,8 +103,8 @@ void main() {
expect(find.text('second day'), findsOneWidget);
expect(find.text('legs'), findsOneWidget);
expect(find.byType(Card), findsWidgets);
// expect(find.byType(Card), findsNWidgets(4));
// One card per day of the routine
expect(find.byType(Card), findsNWidgets(2));
},
tags: ['golden'],
);

View File

@@ -20,7 +20,6 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:material_ui/material_ui.dart';
import 'package:wger/features/routines/models/repetition_unit.dart';
import 'package:wger/features/routines/models/slot_entry.dart';
import 'package:wger/features/routines/providers/routines_notifier.dart';
import 'package:wger/features/routines/screens/routine_screen.dart';
import 'package:wger/features/routines/widgets/forms/repetitions.dart';
@@ -34,17 +33,6 @@ void main() {
RepetitionUnit? result;
final slotEntry = SlotEntry(
slotId: 1,
exerciseId: 1,
repetitionUnitId: 1,
repetitionRounding: 0.25,
weightUnitId: 1,
weightRounding: 0.25,
comment: 'comment',
);
slotEntry.repetitionUnitObj = unit1;
setUp(() {
result = null;
});
@@ -86,6 +74,11 @@ void main() {
await tester.pumpWidget(renderWidget());
await tester.pump();
// The passed unit is preselected, nothing is reported yet
expect(find.text('some rep unit'), findsOneWidget);
expect(find.text('another name'), findsNothing);
expect(result, isNull);
// act
await tester.tap(find.byKey(const Key('1')));
await tester.pump();

View File

@@ -22,6 +22,7 @@ void main() {
WidgetTester tester, {
WorkoutSession? session,
int routineId = 1,
int? dayId,
Function()? onSaved,
}) async {
await pumpApp(
@@ -30,6 +31,7 @@ void main() {
body: SessionForm(
routineId,
session: session,
dayId: dayId,
onSaved: onSaved,
),
),
@@ -68,7 +70,12 @@ void main() {
when(mockRepository.addLocalDrift(any)).thenAnswer(
(inv) async => inv.positionalArguments.first as WorkoutSession,
);
await pumpSessionForm(tester, onSaved: () => onSavedCalled = true);
await pumpSessionForm(
tester,
routineId: 3,
dayId: 7,
onSaved: () => onSavedCalled = true,
);
// Act
await tester.enterText(find.widgetWithText(TextFormField, 'Notes'), 'New session notes');
@@ -76,7 +83,12 @@ void main() {
await tester.pumpAndSettle();
// Assert
verify(mockRepository.addLocalDrift(any)).called(1);
final captured =
verify(mockRepository.addLocalDrift(captureAny)).captured.single as WorkoutSession;
expect(captured.id, isNull);
expect(captured.routineId, 3);
expect(captured.dayId, 7);
expect(captured.notes, 'New session notes');
expect(onSavedCalled, isTrue);
});

View File

@@ -103,9 +103,9 @@ void main() {
await tester.pumpWidget(renderWidget(simpleMode: false));
await tester.pumpAndSettle();
// Set weight
// Set weight (not 100, the fixture already prefills that)
final weightField = find.byKey(const ValueKey('field-weight'));
await tester.enterText(weightField, '100');
await tester.enterText(weightField, '105');
final maxWeightField = find.byKey(const ValueKey('field-max-weight'));
await tester.enterText(maxWeightField, '110');
@@ -165,7 +165,7 @@ void main() {
expect(capturedArgs[(0 * 3) + 1], 4);
expect(capturedArgs[(0 * 3) + 2], ConfigType.sets);
expect(capturedArgs[(1 * 3) + 1], 100);
expect(capturedArgs[(1 * 3) + 1], 105);
expect(capturedArgs[(1 * 3) + 2], ConfigType.weight);
expect(capturedArgs[(2 * 3) + 1], 110);
expect(capturedArgs[(2 * 3) + 2], ConfigType.maxWeight);

View File

@@ -19,7 +19,6 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:material_ui/material_ui.dart';
import 'package:wger/features/routines/models/slot_entry.dart';
import 'package:wger/features/routines/models/weight_unit.dart';
import 'package:wger/features/routines/providers/routines_notifier.dart';
import 'package:wger/features/routines/screens/routine_screen.dart';
@@ -34,17 +33,6 @@ void main() {
const unit2 = WeightUnit(id: 2, name: 'donkeys');
const unit3 = WeightUnit(id: 3, name: 'plates');
final slotEntry = SlotEntry(
slotId: 1,
exerciseId: 1,
repetitionUnitId: 1,
repetitionRounding: 0.25,
weightUnitId: 1,
weightRounding: 0.25,
comment: 'comment',
);
slotEntry.weightUnitObj = unit1;
setUp(() {
result = null;
});
@@ -79,8 +67,12 @@ void main() {
await tester.pumpWidget(renderWidget());
await tester.pump();
// The passed unit is preselected, nothing is reported yet
expect(find.text('kg'), findsOneWidget);
expect(find.text('donkeys'), findsNothing);
expect(result, isNull);
// act
expect(slotEntry.weightUnitObj, equals(unit1));
await tester.tap(find.byKey(const Key('1')));
await tester.pump();
await tester.tap(find.text('donkeys').last);

View File

@@ -67,6 +67,16 @@ void main() {
await tester.pumpWidget(renderWidget());
// One block per set page: the exercise name, one row per logged set, and
// a chevron to jump there. Nothing is done yet and the current page is
// the start page, so every row has the empty circle.
expect(find.text('Bench press'), findsOneWidget);
expect(find.text('3x100kg'), findsNWidgets(3));
expect(find.text('Side raises'), findsOneWidget);
expect(find.text('12x10kg'), findsNWidgets(3));
expect(find.byIcon(Icons.circle_outlined), findsNWidgets(6));
expect(find.byIcon(Icons.chevron_right), findsNWidgets(2));
if (Platform.isLinux) {
await expectLater(
find.byType(MaterialApp),

View File

@@ -1,72 +0,0 @@
/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* Copyright (c) 2025 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 <http://www.gnu.org/licenses/>.
*/
import 'package:flutter_test/flutter_test.dart';
import 'package:wger/features/trophies/models/trophy.dart';
void main() {
group('Trophy model', () {
final sampleJson = {
'id': 1,
'uuid': '550e8400-e29b-41d4-a716-446655440000',
'name': 'First Steps',
'description': 'Awarded for the first workout',
'image': 'https://example.org/trophy.png',
'trophy_type': 'count',
'is_hidden': false,
'is_progressive': true,
};
test('fromJson creates valid Trophy instance', () {
final trophy = Trophy.fromJson(sampleJson);
expect(trophy.id, 1);
expect(trophy.uuid, '550e8400-e29b-41d4-a716-446655440000');
expect(trophy.name, 'First Steps');
expect(trophy.description, 'Awarded for the first workout');
expect(trophy.image, 'https://example.org/trophy.png');
expect(trophy.type, TrophyType.count);
expect(trophy.isHidden, isFalse);
expect(trophy.isProgressive, isTrue);
});
test('toJson returns expected map', () {
final trophy = Trophy(
id: 2,
uuid: '00000000-0000-0000-0000-000000000000',
name: 'Progressor',
description: 'Progressive trophy',
image: 'https://example.org/prog.png',
type: TrophyType.time,
isHidden: true,
isProgressive: false,
);
final json = trophy.toJson();
expect(json['id'], 2);
expect(json['uuid'], '00000000-0000-0000-0000-000000000000');
expect(json['name'], 'Progressor');
expect(json['description'], 'Progressive trophy');
expect(json['image'], 'https://example.org/prog.png');
expect(json['trophy_type'], 'time');
expect(json['is_hidden'], true);
expect(json['is_progressive'], false);
});
});
}

View File

@@ -17,7 +17,6 @@
*/
import 'package:flutter_test/flutter_test.dart';
import 'package:wger/features/trophies/models/trophy.dart';
import 'package:wger/features/trophies/models/user_trophy_progression.dart';
void main() {
@@ -58,40 +57,5 @@ void main() {
expect(utp.targetValue, 100);
expect(utp.progressDisplay, '12.5/100');
});
test('toJson returns expected map', () {
final trophy = Trophy(
id: 2,
uuid: '00000000-0000-0000-0000-000000000000',
name: 'Progressor',
description: 'Progressive trophy',
image: 'https://example.org/prog.png',
type: TrophyType.time,
isHidden: true,
isProgressive: false,
);
final earnedAt = DateTime.parse('2020-01-02T15:04:05Z').toLocal();
final utp = UserTrophyProgression(
trophy: trophy,
isEarned: true,
earnedAt: earnedAt,
progress: 75,
currentValue: 75,
targetValue: 100,
progressDisplay: '75/100',
);
final json = utp.toJson();
expect(json['trophy'], same(trophy));
expect(json['is_earned'], true);
expect(json['earned_at'], earnedAt.toIso8601String());
expect(json['progress'], 75);
expect(json['current_value'], 75);
expect(json['target_value'], 100);
expect(json['progress_display'], '75/100');
});
});
}

View File

@@ -56,12 +56,25 @@ void main() {
final result = await repository.fetchTrophies();
// Assert
expect(result, isA<List>());
expect(result, hasLength(1));
final trophy = result.first;
expect(trophy.id, 1);
expect(trophy.name, 'First Steps');
expect(trophy.type.toString(), contains('count'));
final urlArgs = verify(
mockBase.makeUrl(
captureAny,
id: anyNamed('id'),
objectMethod: anyNamed('objectMethod'),
query: captureAnyNamed('query'),
),
).captured;
expect(urlArgs, [
'trophy',
{'limit': '999'},
]);
verify(mockBase.fetchPaginated(Uri.parse('https://example.org/trophies'))).called(1);
});
test('fetches list of user trophy progression', () async {
@@ -78,14 +91,15 @@ void main() {
final mockBase = MockWgerBaseProvider();
when(mockBase.fetch(any)).thenAnswer((_) async => [progressionJson]);
when(mockBase.makeUrl(any)).thenReturn(Uri.parse('https://example.org/user_progressions'));
when(
mockBase.makeUrl(any, query: anyNamed('query')),
).thenReturn(Uri.parse('https://example.org/user_progressions'));
final repository = TrophyRepository(mockBase);
// Act
final result = await repository.fetchProgression();
final result = await repository.fetchProgression(filterQuery: {'is_earned': 'true'});
// Assert
expect(result, isA<List>());
expect(result, hasLength(1));
final p = result.first;
expect(p.isEarned, isTrue);
@@ -93,7 +107,14 @@ void main() {
expect(p.currentValue, 12.5);
expect(p.progressDisplay, '12.5/100');
verify(mockBase.fetch(any)).called(1);
final urlArgs = verify(
mockBase.makeUrl(captureAny, query: captureAnyNamed('query')),
).captured;
expect(urlArgs, [
'trophy/progress',
{'is_earned': 'true'},
]);
verify(mockBase.fetch(Uri.parse('https://example.org/user_progressions'))).called(1);
});
});
}