(MeasurementProvider) Fixed error handling

MeasurementProvider
(Edited)
- Fixed error handling
- implemented findEntryById and findCategoryById

MeasurementCategory
(Added)
- findEntryById()
This commit is contained in:
ton-An
2021-08-26 14:41:26 +02:00
parent 4e9ca1db6b
commit 89e0060ff5
6 changed files with 132 additions and 88 deletions

View File

@@ -1,4 +1,5 @@
import 'package:json_annotation/json_annotation.dart';
import 'package:wger/exceptions/no_such_entry_exception.dart';
import 'package:wger/models/measurements/measurement_entry.dart';
import 'package:equatable/equatable.dart';
@@ -39,6 +40,11 @@ class MeasurementCategory extends Equatable {
);
}
MeasurementEntry findEntryById(entryId) {
return entries.firstWhere((entry) => entry.id == entryId,
orElse: () => throw NoSuchEntryException());
}
// Boilerplate
factory MeasurementCategory.fromJson(Map<String, dynamic> json) =>
_$MeasurementCategoryFromJson(json);

View File

@@ -7,17 +7,19 @@ part of 'measurement_entry.dart';
// **************************************************************************
MeasurementEntry _$MeasurementEntryFromJson(Map<String, dynamic> json) {
$checkKeys(json, requiredKeys: const ['id', 'category', 'date', 'value', 'notes']);
$checkKeys(json,
requiredKeys: const ['id', 'category', 'date', 'value', 'notes']);
return MeasurementEntry(
id: json['id'] as int?,
category: json['category'] as int,
date: DateTime.parse(json['date'] as String),
value: stringToNum(json['value'] as String?),
notes: json['notes'] ?? '',
notes: json['notes'] as String? ?? '',
);
}
Map<String, dynamic> _$MeasurementEntryToJson(MeasurementEntry instance) => <String, dynamic>{
Map<String, dynamic> _$MeasurementEntryToJson(MeasurementEntry instance) =>
<String, dynamic>{
'id': instance.id,
'category': instance.category,
'date': toDate(instance.date),

View File

@@ -51,7 +51,7 @@ class MeasurementProvider with ChangeNotifier {
MeasurementCategory findCategoryById(int id) {
return _categories.firstWhere(
(category) => category.id == id,
orElse: () => throw NoResultException(),
orElse: () => throw NoSuchEntryException(),
);
}
@@ -90,6 +90,7 @@ class MeasurementProvider with ChangeNotifier {
/// Adds a measurement category
Future<void> addCategory(MeasurementCategory category) async {
Uri postUri = baseProvider.makeUrl(_categoryUrl);
final Map<String, dynamic> newCategoryMap = await baseProvider.post(category.toJson(), postUri);
final MeasurementCategory newCategory = MeasurementCategory.fromJson(newCategoryMap);
_categories.add(newCategory);
@@ -99,33 +100,32 @@ class MeasurementProvider with ChangeNotifier {
/// Deletes a measurement category
Future<void> deleteCategory(int id) async {
MeasurementCategory category = _categories.firstWhere((element) => element.id == id,
orElse: () => throw NoSuchEntryException());
MeasurementCategory category = findCategoryById(id);
int categoryIndex = _categories.indexOf(category);
_categories.remove(category);
notifyListeners();
final http.Response response = await baseProvider.deleteRequest(_categoryUrl, id);
if (response.statusCode >= 400) {
try {
await baseProvider.deleteRequest(_categoryUrl, id);
} on WgerHttpException catch (e) {
_categories.insert(categoryIndex, category);
notifyListeners();
throw e;
}
}
/// Edits a measurement category
/// Currently there isn't any fallback if the call to the api is unsuccessful, as WgerBaseProvider.patch only returns the response body and not the whole response
Future<void> editCategory(int id, String? newName, String? newUnit) async {
final MeasurementCategory oldCategory = _categories.firstWhere((category) => category.id == id,
orElse: () => throw NoSuchEntryException());
final MeasurementCategory oldCategory = findCategoryById(id);
int categoryIndex = _categories.indexOf(oldCategory);
_categories.removeAt(categoryIndex);
final MeasurementCategory tempNewCategory = oldCategory.copyWith(name: newName, unit: newUnit);
final Map<String, dynamic> response =
await baseProvider.patch(tempNewCategory.toJson(), baseProvider.makeUrl(_categoryUrl));
final MeasurementCategory newCategory =
(MeasurementCategory.fromJson(response)).copyWith(entries: oldCategory.entries);
_categories.removeAt(categoryIndex);
_categories.insert(categoryIndex, newCategory);
notifyListeners();
}
@@ -137,54 +137,45 @@ class MeasurementProvider with ChangeNotifier {
final Map<String, dynamic> newEntryMap = await baseProvider.post(entry.toJson(), postUri);
final MeasurementEntry newEntry = MeasurementEntry.fromJson(newEntryMap);
_categories.firstWhere((categories) {
if (categories.id == newEntry.category) {
categories.entries.add(newEntry);
categories.entries.sort((a, b) => b.date.compareTo(a.date));
notifyListeners();
return true;
}
return false;
}, orElse: () => throw NoSuchEntryException());
MeasurementCategory category = findCategoryById(newEntry.category);
category.entries.add(newEntry);
category.entries.sort((a, b) => b.date.compareTo(a.date));
notifyListeners();
}
/// Deletes a measurement entry
Future<void> deleteEntry(int id, int categoryId) async {
final int categoryIndex = _categories.indexWhere((category) => category.id == categoryId);
if (categoryIndex == -1) throw NoSuchEntryException();
final MeasurementCategory category = findCategoryById(categoryId);
final MeasurementEntry entry = _categories[categoryIndex]
.entries
.firstWhere((entry) => entry.id == id, orElse: () => throw NoSuchEntryException());
final int entryIndex = _categories[categoryIndex].entries.indexOf(entry);
final MeasurementEntry entry = category.findEntryById(id);
final int entryIndex = category.entries.indexOf(entry);
_categories[categoryIndex].entries.removeAt(entryIndex);
category.entries.removeAt(entryIndex);
notifyListeners();
final http.Response response = await baseProvider.deleteRequest(_entryUrl, id);
if (response.statusCode >= 400) {
_categories[categoryIndex].entries.insert(entryIndex, entry);
try {
await baseProvider.deleteRequest(_entryUrl, id);
} on WgerHttpException catch (e) {
category.entries.insert(entryIndex, entry);
notifyListeners();
throw e;
}
}
/// Edits a measurement entry
/// Currently there isn't any fallback if the call to the api is unsuccessful, as WgerBaseProvider.patch only returns the response body and not the whole response
Future<void> editEntry(int id, int categroyId, num? newValue, String? newNotes) async {
final MeasurementCategory category = _categories.firstWhere(
(category) => category.id == categroyId,
orElse: () => throw NoSuchEntryException());
final MeasurementEntry oldEntry = category.entries
.firstWhere((entry) => entry.id == id, orElse: () => throw NoSuchEntryException());
final MeasurementCategory category = findCategoryById(categroyId);
final MeasurementEntry oldEntry = category.findEntryById(id);
final int entryIndex = category.entries.indexOf(oldEntry);
category.entries.removeAt(entryIndex);
final MeasurementEntry tempNewEntry = oldEntry.copyWith(value: newValue, notes: newNotes);
final Map<String, dynamic> response =
await baseProvider.patch(tempNewEntry.toJson(), baseProvider.makeUrl(_entryUrl));
final MeasurementEntry newEntry = MeasurementEntry.fromJson(response);
category.entries.removeAt(entryIndex);
category.entries.insert(entryIndex, newEntry);
notifyListeners();
}

View File

@@ -1,4 +1,5 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:wger/exceptions/no_such_entry_exception.dart';
import 'package:wger/models/measurements/measurement_category.dart';
import 'package:wger/models/measurements/measurement_entry.dart';
@@ -13,6 +14,15 @@ void main() {
)
];
MeasurementEntry tMeasurementEntry = MeasurementEntry(
id: 1234,
category: 123,
date: DateTime(2021, 7, 22),
value: 83,
notes: 'notes',
);
int tMeasurementEntryId = 1234;
MeasurementCategory tMeasurementCategory = MeasurementCategory(
id: 123,
name: 'Bizeps',
@@ -42,41 +52,64 @@ void main() {
'entries': null,
};
test('should convert a JSON map to a MeasurementCategory object', () {
// act
final result = MeasurementCategory.fromJson(tMeasurementCategoryMap);
group('fromJson()', () {
test('should convert a JSON map to a MeasurementCategory object', () {
// act
final result = MeasurementCategory.fromJson(tMeasurementCategoryMap);
// assert
expect(result, tMeasurementCategory);
// assert
expect(result, tMeasurementCategory);
});
});
test('should convert a MeasurementCategory object to a JSON map', () {
// act
final result = tMeasurementCategory.toJson();
group('toJson()', () {
test('should convert a MeasurementCategory object to a JSON map', () {
// act
final result = tMeasurementCategory.toJson();
// assert
expect(result, tMeasurementCategoryMaptoJson);
// assert
expect(result, tMeasurementCategoryMaptoJson);
});
});
test('should copyWith objects of this class', () {
// arrange
group('copyWith()', () {
test('should copyWith objects of this class', () {
// arrange
MeasurementCategory tMeasurementCategoryCopied = MeasurementCategory(
id: 1234,
name: 'Coolness',
unit: 'lp',
entries: tMeasurementEntries,
);
MeasurementCategory tMeasurementCategoryCopied = MeasurementCategory(
id: 1234,
name: 'Coolness',
unit: 'lp',
entries: tMeasurementEntries,
);
// act
final result = tMeasurementCategory.copyWith(
id: 1234,
name: 'Coolness',
unit: 'lp',
entries: tMeasurementEntries,
);
// act
final result = tMeasurementCategory.copyWith(
id: 1234,
name: 'Coolness',
unit: 'lp',
entries: tMeasurementEntries,
);
// assert
expect(result, tMeasurementCategoryCopied);
// assert
expect(result, tMeasurementCategoryCopied);
});
});
group('findEntryById()', () {
test('should find an entry in the entries list', () {
// arrange
// act
final result = tMeasurementCategory.findEntryById(tMeasurementEntryId);
// assert
expect(result, tMeasurementEntry);
});
test('should throw a NoSuchEntryException if no MeasurementEntry was found', () {
// act & assert
expect(() => tMeasurementCategory.findEntryById(83), throwsA(isA<NoSuchEntryException>()));
});
});
}

View File

@@ -90,7 +90,7 @@ main() {
test('should throw a NoResultException if no category is found', () {
// act & assert
expect(() => measurementProvider.findCategoryById(3), throwsA(isA<NoResultException>()));
expect(() => measurementProvider.findCategoryById(3), throwsA(isA<NoSuchEntryException>()));
});
});
@@ -238,15 +238,15 @@ main() {
throwsA(isA<NoSuchEntryException>()));
});
test('should re-add the "removed" MeasurementCategory if call to api fails', () async {
test(
'should re-add the "removed" MeasurementCategory and relay the exception on WgerHttpException',
() async {
// arrange
when(mockWgerBaseProvider.deleteRequest(any, any))
.thenAnswer((realInvocation) => Future.value(Response('{}', 400)));
when(mockWgerBaseProvider.deleteRequest(any, any)).thenThrow(WgerHttpException('{}'));
// act
await measurementProvider.deleteCategory(tCategoryId);
// assert
// act & assert
expect(() async => await measurementProvider.deleteCategory(tCategoryId),
throwsA(isA<WgerHttpException>()));
expect(measurementProvider.categories, tMeasurementCategories);
});
});
@@ -292,6 +292,18 @@ main() {
// assert
verify(mockWgerBaseProvider.patch(tCategoryMapEditedToJson, tCategoryUri));
});
test('should keep categories list as is on WgerHttpException', () {
// arrange
when(mockWgerBaseProvider.patch(any, any)).thenThrow(WgerHttpException('{}'));
// act & assert
expect(
() async => await measurementProvider.editCategory(
tCategoryId, tCategoryEditedName, tCategoryEditedUnit),
throwsA(isA<WgerHttpException>()));
expect(measurementProvider.categories, tMeasurementCategories);
});
});
group('addEntry()', () {
@@ -469,13 +481,11 @@ main() {
]),
MeasurementCategory(id: 2, name: 'Biceps', unit: 'cm')
];
when(mockWgerBaseProvider.deleteRequest(any, any))
.thenAnswer((realInvocation) => Future.value(Response('{}', 404)));
when(mockWgerBaseProvider.deleteRequest(any, any)).thenThrow(WgerHttpException('{}'));
//act
await measurementProvider.deleteEntry(tEntryId, tCategoryId);
// assert
// act & assert
expect(() async => await measurementProvider.deleteEntry(tEntryId, tCategoryId),
throwsA(isA<WgerHttpException>()));
expect(measurementProvider.categories, tMeasurementCategories);
});
});

View File

@@ -1,4 +1,4 @@
// Mocks generated by Mockito 5.0.12 from annotations
// Mocks generated by Mockito 5.0.14 from annotations
// in wger/test/measurements/measurement_provider_test.dart.
// Do not manually edit this file.
@@ -17,13 +17,13 @@ import 'package:wger/providers/base_provider.dart' as _i4;
// ignore_for_file: prefer_const_constructors
// ignore_for_file: unnecessary_parenthesis
class _FakeAuthProvider extends _i1.Fake implements _i2.AuthProvider {}
class _FakeAuthProvider_0 extends _i1.Fake implements _i2.AuthProvider {}
class _FakeClient extends _i1.Fake implements _i3.Client {}
class _FakeClient_1 extends _i1.Fake implements _i3.Client {}
class _FakeUri extends _i1.Fake implements Uri {}
class _FakeUri_2 extends _i1.Fake implements Uri {}
class _FakeResponse extends _i1.Fake implements _i3.Response {}
class _FakeResponse_3 extends _i1.Fake implements _i3.Response {}
/// A class which mocks [WgerBaseProvider].
///
@@ -35,14 +35,14 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider {
@override
_i2.AuthProvider get auth => (super.noSuchMethod(Invocation.getter(#auth),
returnValue: _FakeAuthProvider()) as _i2.AuthProvider);
returnValue: _FakeAuthProvider_0()) as _i2.AuthProvider);
@override
set auth(_i2.AuthProvider? _auth) =>
super.noSuchMethod(Invocation.setter(#auth, _auth),
returnValueForMissingStub: null);
@override
_i3.Client get client => (super.noSuchMethod(Invocation.getter(#client),
returnValue: _FakeClient()) as _i3.Client);
returnValue: _FakeClient_1()) as _i3.Client);
@override
set client(_i3.Client? _client) =>
super.noSuchMethod(Invocation.setter(#client, _client),
@@ -53,7 +53,7 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider {
(super.noSuchMethod(
Invocation.method(#makeUrl, [path],
{#id: id, #objectMethod: objectMethod, #query: query}),
returnValue: _FakeUri()) as Uri);
returnValue: _FakeUri_2()) as Uri);
@override
_i5.Future<Map<String, dynamic>> fetch(Uri? uri) => (super.noSuchMethod(
Invocation.method(#fetch, [uri]),
@@ -75,6 +75,8 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider {
@override
_i5.Future<_i3.Response> deleteRequest(String? url, int? id) =>
(super.noSuchMethod(Invocation.method(#deleteRequest, [url, id]),
returnValue: Future<_i3.Response>.value(_FakeResponse()))
returnValue: Future<_i3.Response>.value(_FakeResponse_3()))
as _i5.Future<_i3.Response>);
@override
String toString() => super.toString();
}