From ed9590cddf4e890d2e24effa897b0ecdbfd1f638 Mon Sep 17 00:00:00 2001 From: Oliver Date: Sun, 22 Nov 2026 22:32:05 +1100 Subject: [PATCH] API form fixes (#937) * API form fixes - Await form completion - Improved error code handling - Additional testing * improve error message display in forms * add text --- lib/api.dart | 39 +++++--- lib/api_form.dart | 41 ++++++-- lib/l10n/app_en.arb | 6 ++ lib/widget/dialogs.dart | 85 ++++++++++++++++ lib/widget/snacks.dart | 47 ++++++--- test/auth_flow_test.dart | 92 ++++++++++++++++++ test/dialogs_test.dart | 125 ++++++++++++++++++++++++ test/widget/locate_test.dart | 181 +++++++++++++++++++++++++++++++++++ 8 files changed, 585 insertions(+), 31 deletions(-) create mode 100644 test/widget/locate_test.dart diff --git a/lib/api.dart b/lib/api.dart index 0d0f624f..2513648f 100644 --- a/lib/api.dart +++ b/lib/api.dart @@ -748,7 +748,8 @@ class InvenTreeAPI { debug("Connecting to ${apiUrl}"); - APIResponse response = await get(url, expectedStatusCode: 200); + // Note: Unexpected status codes are reported below + APIResponse response = await get(url); if (!response.successful()) { debug("Server returned invalid response: ${response.statusCode}"); @@ -856,10 +857,16 @@ class InvenTreeAPI { _globalSettings.clear(); _userSettings.clear(); + // Clear data received from the server + // (so it is not shown while connecting to a different server) roles.clear(); + permissions.clear(); _plugins.clear(); serverInfo.clear(); userInfo = {}; + notification_counter = 0; + clearStatusCodeData(); + _connectionStatusChanged(); } @@ -929,6 +936,7 @@ class InvenTreeAPI { */ Future _fetchRoles() async { roles.clear(); + permissions.clear(); debug("API: Requesting user role data"); String actualRoleUrl = supportsNewUserEndpoints @@ -1906,7 +1914,9 @@ class InvenTreeAPI { String url, { Map params = const {}, Map headers = const {}, - int? expectedStatusCode = 200, + // If provided, the user is alerted when a different status code is returned + // (by default, callers handle unexpected responses, e.g. 404, themselves) + int? expectedStatusCode, }) async { HttpClientRequest? request = await apiRequest( url, @@ -1924,7 +1934,7 @@ class InvenTreeAPI { ); } - return completeRequest(request); + return completeRequest(request, statusCode: expectedStatusCode); } /* @@ -2186,9 +2196,14 @@ class InvenTreeAPI { fields, icon: TablerIcons.location_search, onSuccess: (Map data) async { - plugin_name = (data["plugin"] ?? "") as String; + plugin_name = (data["plugin"] ?? "").toString(); }, ); + + // Form was cancelled (no plugin selected) + if (plugin_name.isEmpty) { + return; + } } Map body = {"plugin": plugin_name}; @@ -2201,13 +2216,15 @@ class InvenTreeAPI { body["location"] = location.toString(); } - post("locate/", body: body, expectedStatusCode: 200).then(( - APIResponse response, - ) { - if (response.successful()) { - showSnackIcon(L10().requestSuccessful, success: true); - } - }); + final APIResponse response = await post( + "locate/", + body: body, + expectedStatusCode: 200, + ); + + if (response.successful()) { + showSnackIcon(L10().requestSuccessful, success: true); + } } // Keep an internal map of status codes diff --git a/lib/api_form.dart b/lib/api_form.dart index 113c33a9..6c4c959c 100644 --- a/lib/api_form.dart +++ b/lib/api_form.dart @@ -1123,6 +1123,11 @@ Map formResponseData(APIResponse response) { return Map.from(response.asMap()); } +/* + * Launch an API form. + * The returned future completes once the form is closed + * (after onSuccess has been called, if the form was submitted). + */ Future launchApiForm( BuildContext context, String title, @@ -1208,7 +1213,9 @@ Future launchApiForm( hideLoadingOverlay(); // Now, launch a new widget! - Navigator.push( + // Wait until the form is closed (submitted or cancelled), + // so that callers can await the outcome of the form + await Navigator.push( context, MaterialPageRoute( builder: (context) => APIFormWidget( @@ -1371,6 +1378,21 @@ class APIFormWidgetState extends State { return widgets; } + /* + * Notify the user that the form submission failed. + * Tapping the info icon displays the full response from the server. + */ + void showErrorSnack(String message, APIResponse response) { + showSnackIcon( + message, + success: false, + icon: TablerIcons.info_circle, + onAction: () { + showResponseDataDialog(message, response); + }, + ); + } + Future _submit(Map data) async { // If a file upload is required, we have to handle the submission differently if (widget.fileField.isNotEmpty) { @@ -1577,7 +1599,8 @@ class APIFormWidgetState extends State { return; case 400: // Form submission / validation error - showSnackIcon(L10().formError, success: false); + print("error: ${response.toString()}"); + showErrorSnack(L10().formError, response); // Update field errors for (var field in formFields) { @@ -1587,19 +1610,19 @@ class APIFormWidgetState extends State { extractNonFieldErrors(response); checkInvalidErrors(response); case 401: - showSnackIcon("401: " + L10().response401, success: false); + showErrorSnack("401: " + L10().response401, response); case 403: - showSnackIcon("403: " + L10().response403, success: false); + showErrorSnack("403: " + L10().response403, response); case 404: - showSnackIcon("404: " + L10().response404, success: false); + showErrorSnack("404: " + L10().response404, response); case 405: - showSnackIcon("405: " + L10().response405, success: false); + showErrorSnack("405: " + L10().response405, response); case 500: - showSnackIcon("500: " + L10().response500, success: false); + showErrorSnack("500: " + L10().response500, response); default: - showSnackIcon( + showErrorSnack( "${response.statusCode}: " + L10().responseInvalid, - success: false, + response, ); } diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 8cc368f4..4e4fdbe8 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -550,6 +550,12 @@ "destroyed": "Destroyed", "@destroyed": {}, + "copiedToClipboard": "Copied to clipboard", + "@copiedToClipboard": {}, + + "copyToClipboard": "Copy", + "@copyToClipboard": {}, + "details": "Details", "@details": { "description": "details" diff --git a/lib/widget/dialogs.dart b/lib/widget/dialogs.dart index ba64125a..9b5a4435 100644 --- a/lib/widget/dialogs.dart +++ b/lib/widget/dialogs.dart @@ -1,4 +1,7 @@ +import "dart:convert"; + import "package:flutter/material.dart"; +import "package:flutter/services.dart"; import "package:flutter_tabler_icons/flutter_tabler_icons.dart"; import "package:one_context/one_context.dart"; @@ -8,6 +11,7 @@ import "package:inventree/helpers.dart"; import "package:inventree/l10.dart"; import "package:inventree/preferences.dart"; +import "package:inventree/widget/snacks.dart"; /* * Launch a dialog allowing the user to select from a list of options @@ -290,6 +294,87 @@ Future showErrorDialog( }); } +/* + * Format the data returned in an API response for display + * (JSON data is pretty-printed) + */ +String formatResponseData(dynamic data) { + if (data is Map || data is List) { + try { + return const JsonEncoder.withIndent(" ").convert(data); + } catch (_) { + // Fall through to the string representation + } + } + + return data?.toString() ?? ""; +} + +/* + * Construct a view of the full data returned in an API response + */ +Widget buildResponseDataContent(APIResponse response) { + return ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 400), + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + "${L10().statusCode}: ${response.statusCode}", + style: const TextStyle(fontWeight: FontWeight.bold), + ), + if (response.url.isNotEmpty) Text(response.url), + const SizedBox(height: 8), + Text( + L10().responseData, + style: const TextStyle(fontWeight: FontWeight.bold), + ), + SelectableText( + formatResponseData(response.data), + style: const TextStyle(fontFamily: "monospace", fontSize: 12), + ), + ], + ), + ), + ); +} + +/* + * Display the full data returned in an API response (e.g. form errors) + */ +Future showResponseDataDialog(String title, APIResponse response) async { + if (!hasContext()) { + return; + } + + final String data = formatResponseData(response.data); + + OneContext().showDialog( + builder: (context) => AlertDialog( + icon: Icon(TablerIcons.info_circle, color: COLOR_DANGER), + title: Text(title), + content: buildResponseDataContent(response), + actions: [ + TextButton( + child: Text(L10().copyToClipboard), + onPressed: () { + Clipboard.setData(ClipboardData(text: data)); + showSnackIcon(L10().copiedToClipboard, success: true); + }, + ), + TextButton( + child: Text(L10().ok), + onPressed: () { + Navigator.pop(context); + }, + ), + ], + ), + ); +} + /* * Display a message indicating the nature of a server / API error */ diff --git a/lib/widget/snacks.dart b/lib/widget/snacks.dart index f6b0a3d8..6435897f 100644 --- a/lib/widget/snacks.dart +++ b/lib/widget/snacks.dart @@ -12,6 +12,9 @@ OverlayEntry? _currentSnackOverlay; /* * Display a configurable 'snackbar' at the top of the screen + * + * If both [icon] and [onAction] are provided, tapping the icon runs the action + * (and the text action button is only shown if [actionText] is provided) */ void showSnackIcon( String text, { @@ -50,17 +53,22 @@ void showSnackIcon( } } - final String actionLabel = actionText ?? L10().details; + // An action icon replaces the default text action button + final bool iconAction = onAction != null && icon != null; + final String? actionLabel = (iconAction && actionText == null) + ? null + : actionText ?? L10().details; final Duration duration = Duration(seconds: onAction == null ? 5 : 10); late OverlayEntry entry; entry = OverlayEntry( - builder: (ctx) => _TopSnackBar( + builder: (ctx) => TopSnackBar( text: text, icon: icon, backgroundColor: backgroundColor, onAction: onAction, actionText: actionLabel, + iconAction: iconAction, duration: duration, onDismiss: () { entry.remove(); @@ -75,8 +83,12 @@ void showSnackIcon( Overlay.of(context).insert(entry); } -class _TopSnackBar extends StatefulWidget { - const _TopSnackBar({ +/* + * Snackbar widget displayed by showSnackIcon() + * (public for testing, as snackbars are not displayed in tests) + */ +class TopSnackBar extends StatefulWidget { + const TopSnackBar({ required this.text, required this.backgroundColor, required this.duration, @@ -84,6 +96,7 @@ class _TopSnackBar extends StatefulWidget { this.icon, this.onAction, this.actionText, + this.iconAction = false, }); final String text; @@ -91,6 +104,10 @@ class _TopSnackBar extends StatefulWidget { final Color backgroundColor; final Function()? onAction; final String? actionText; + + // Tapping the icon runs the action + final bool iconAction; + final Duration duration; final VoidCallback onDismiss; @@ -98,7 +115,7 @@ class _TopSnackBar extends StatefulWidget { _TopSnackBarState createState() => _TopSnackBarState(); } -class _TopSnackBarState extends State<_TopSnackBar> +class _TopSnackBarState extends State with SingleTickerProviderStateMixin { late final AnimationController _controller; late final Animation _slideAnimation; @@ -130,6 +147,11 @@ class _TopSnackBarState extends State<_TopSnackBar> super.dispose(); } + void _runAction() { + _dismiss(); + widget.onAction?.call(); + } + void _dismiss() { if (_dismissed) return; _dismissed = true; @@ -170,7 +192,7 @@ class _TopSnackBarState extends State<_TopSnackBar> style: const TextStyle(color: Colors.white), ), ), - if (widget.icon != null) + if (widget.icon != null && !widget.iconAction) Padding( padding: const EdgeInsets.only(left: 8), child: Icon(widget.icon, color: Colors.white), @@ -179,12 +201,15 @@ class _TopSnackBarState extends State<_TopSnackBar> ), ), ), - if (widget.onAction != null) + if (widget.iconAction) + IconButton( + icon: Icon(widget.icon, color: Colors.white), + tooltip: widget.actionText ?? L10().details, + onPressed: _runAction, + ), + if (widget.onAction != null && widget.actionText != null) TextButton( - onPressed: () { - _dismiss(); - widget.onAction!(); - }, + onPressed: _runAction, child: Text( widget.actionText ?? "", style: const TextStyle(color: Colors.white), diff --git a/test/auth_flow_test.dart b/test/auth_flow_test.dart index 2c5fe355..f9cd7698 100644 --- a/test/auth_flow_test.dart +++ b/test/auth_flow_test.dart @@ -365,6 +365,64 @@ void main() { expect(logged("Opening login screen"), equals(false)); }); + test("Role request failure is reported", () async { + final profile = await fakeProfile(server); + + expect((await login(profile)).authenticated, equals(true)); + + server.once( + "GET", + "api/user/me/roles/", + (_) => FakeResponse(403, body: {"detail": "Permission denied."}), + ); + + expect(await api.connectToServer(profile), equals(false)); + + // Previously the connection failed without any message (B20) + expect( + logged("showServerError: '${statusCodeToString(403)}'"), + equals(true), + ); + }); + + test("Disconnect clears server data", () async { + final profile = await fakeProfile(server); + + server.always( + "GET", + "api/user/me/roles/", + (_) => FakeResponse( + 200, + body: { + "roles": { + "part": ["view"], + }, + "permissions": { + "part": ["view"], + }, + }, + ), + ); + + await loginAndConnect(profile); + + expect(api.roles, isNotEmpty); + expect(api.permissions, isNotEmpty); + + api.notification_counter = 3; + api.StockStatus.data["OK"] = {"key": 10, "name": "OK", "label": "OK"}; + + api.disconnectFromServer(); + + // Nothing from the previous server is shown while connecting to another + expect(api.roles, isEmpty); + expect(api.permissions, isEmpty); + expect(api.serverInfo, isEmpty); + expect(api.userInfo, isEmpty); + expect(api.notification_counter, equals(0)); + expect(api.StockStatus.data, isEmpty); + }); + final Map failures = { "Service unavailable (503)": FakeResponse(503), "Connection dropped": FakeResponse.drop(), @@ -936,6 +994,40 @@ void main() { expect(request.query, equals({"category": "1", "search": "x y"})); }); + test("Unexpected status code is reported if requested", () async { + server.once( + "GET", + "api/part/1/", + (_) => FakeResponse(404, body: {"detail": "Not found."}), + ); + + clearDebugMessage(); + + final response = await api.get("part/1/", expectedStatusCode: 200); + + expect(response.statusCode, equals(404)); + expect( + logged("showServerError: '${statusCodeToString(404)}'"), + equals(true), + ); + }); + + test("Unexpected status code is not reported by default", () async { + // e.g. a 404 when checking whether an object still exists + server.once( + "GET", + "api/part/1/", + (_) => FakeResponse(404, body: {"detail": "Not found."}), + ); + + clearDebugMessage(); + + final response = await api.get("part/1/"); + + expect(response.statusCode, equals(404)); + expect(logged("showServerError:"), equals(false)); + }); + test("No query string without parameters", () async { await api.get("part/"); diff --git a/test/dialogs_test.dart b/test/dialogs_test.dart index 7385f5e9..9b39b6ce 100644 --- a/test/dialogs_test.dart +++ b/test/dialogs_test.dart @@ -5,11 +5,13 @@ */ import "package:flutter/material.dart"; +import "package:flutter_tabler_icons/flutter_tabler_icons.dart"; import "package:flutter_test/flutter_test.dart"; import "package:inventree/api.dart"; import "package:inventree/l10.dart"; import "package:inventree/widget/dialogs.dart"; +import "package:inventree/widget/snacks.dart"; // Display the error content for the given description / response Future pumpErrorContent( @@ -234,4 +236,127 @@ void main() { ); }); }); + + group("Response Data:", () { + test("JSON data is pretty-printed", () { + expect( + formatResponseData({ + "name": ["This field is required."], + "quantity": ["Must be positive"], + }), + equals( + [ + "{", + ' "name": [', + ' "This field is required."', + " ],", + ' "quantity": [', + ' "Must be positive"', + " ]", + "}", + ].join("\n"), + ), + ); + + expect(formatResponseData(["a"]), equals('[\n "a"\n]')); + }); + + test("Other data", () { + expect( + formatResponseData("Bad Gateway"), + equals("Bad Gateway"), + ); + expect(formatResponseData(null), isEmpty); + }); + + testWidgets("Full response is displayed", (tester) async { + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: buildResponseDataContent( + APIResponse( + url: "https://server/api/part/", + statusCode: 400, + data: { + "name": ["This field is required."], + }, + ), + ), + ), + ), + ); + + expect(find.text("${L10().statusCode}: 400"), findsOneWidget); + expect(find.text("https://server/api/part/"), findsOneWidget); + expect( + find.textContaining('"This field is required."', findRichText: true), + findsOneWidget, + ); + }); + }); + + group("Snackbar Actions:", () { + Future pumpSnack( + WidgetTester tester, { + IconData? icon, + String? actionText, + required void Function() onAction, + }) async { + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Stack( + children: [ + TopSnackBar( + text: L10().formError, + icon: icon, + backgroundColor: Colors.red, + duration: const Duration(seconds: 10), + onDismiss: () {}, + onAction: onAction, + actionText: actionText, + iconAction: icon != null && actionText == null, + ), + ], + ), + ), + ), + ); + + await tester.pump(const Duration(milliseconds: 500)); + } + + testWidgets("Tapping the icon runs the action", (tester) async { + int actions = 0; + + await pumpSnack( + tester, + icon: TablerIcons.info_circle, + onAction: () => actions++, + ); + + // The icon replaces the text action button + expect(find.byType(TextButton), findsNothing); + + await tester.tap(find.byIcon(TablerIcons.info_circle)); + await tester.pump(const Duration(milliseconds: 500)); + + expect(actions, equals(1)); + }); + + testWidgets("Text action button", (tester) async { + int actions = 0; + + await pumpSnack( + tester, + actionText: L10().details, + onAction: () => actions++, + ); + + await tester.tap(find.text(L10().details)); + await tester.pump(const Duration(milliseconds: 500)); + + expect(actions, equals(1)); + }); + }); } diff --git a/test/widget/locate_test.dart b/test/widget/locate_test.dart new file mode 100644 index 00000000..5fcdac7d --- /dev/null +++ b/test/widget/locate_test.dart @@ -0,0 +1,181 @@ +/* + * Widget tests for locating a stock item / location (regression tests for B16). + * + * With more than one "locate" plugin, the user selects a plugin from a form. + * Previously the locate request was sent (with an empty plugin) as soon as + * the form was opened, as launchApiForm() returned before the form was closed. + * + * Uses an in-process fake server (see fake_server.dart). + */ + +import "package:flutter/material.dart"; +import "package:flutter_tabler_icons/flutter_tabler_icons.dart"; +import "package:flutter_test/flutter_test.dart"; + +import "package:inventree/api.dart"; +import "package:inventree/auth/auth_manager.dart"; +import "package:inventree/auth/auth_method.dart"; +import "package:inventree/l10.dart"; +import "package:inventree/user_profile.dart"; + +import "../fake_server.dart"; +import "../setup.dart"; +import "harness.dart"; + +const String profileName = "Locate Widget Test"; + +UserProfileDBManager get manager => UserProfileDBManager(); + +Map locatePlugin(String key) => { + "key": key, + "active": true, + "meta": {"human_name": "Plugin ${key}"}, + "mixins": { + "locate": {"key": "locate"}, + }, +}; + +void main() { + setupTestEnv(); + mockSharedPreferences(); + + late FakeInvenTreeServer server; + + setUp(() async { + server = await FakeInvenTreeServer.start(); + + server.always( + "GET", + "api/plugins/", + (_) => FakeResponse( + 200, + body: [locatePlugin("first"), locatePlugin("second")], + ), + ); + + server.always("POST", "api/locate/", (_) => FakeResponse(200, body: {})); + }); + + tearDown(() async { + await server.close(); + }); + + // Connect to the fake server, and show a screen to launch the form from + Future setupScreen(WidgetTester tester) async { + final UserProfile? existing = await settle( + tester, + manager.getProfileByName(profileName), + ); + + if (existing != null) { + await settle(tester, manager.deleteProfile(existing)); + } + + await settle( + tester, + manager.addProfile(UserProfile(name: profileName, server: server.url)), + ); + + final UserProfile profile = (await settle( + tester, + manager.getProfileByName(profileName), + ))!; + + addTearDown(() => manager.deleteProfile(profile)); + + final result = await settle( + tester, + InvenTreeAuth().beginLogin( + profile, + PasswordAuthMethod("user", "password"), + ), + ); + + expect(result.authenticated, isTrue); + expect( + await settle(tester, InvenTreeAPI().connectToServer(profile)), + isTrue, + ); + + expect(InvenTreeAPI().getPlugins(mixin: "locate"), hasLength(2)); + + late BuildContext context; + + await pumpScreen( + tester, + Scaffold( + body: Builder( + builder: (ctx) { + context = ctx; + return const Text("Locate Test"); + }, + ), + ), + ); + + return context; + } + + // Start locating an item, and wait for the plugin form to be displayed. + // [onComplete] is called when locateItemOrLocation() completes + Future startLocate( + WidgetTester tester, + void Function() onComplete, + ) async { + final BuildContext context = await setupScreen(tester); + + InvenTreeAPI() + .locateItemOrLocation(context, item: 5) + .then((_) => onComplete()); + + await waitUntil( + tester, + () => find.text(L10().locateLocation).evaluate().isNotEmpty, + reason: "plugin selection form displayed", + ); + } + + testWidgets("Locate request waits for plugin selection", (tester) async { + bool complete = false; + + await startLocate(tester, () => complete = true); + + // Wait for any (incorrect) request to arrive + for (int i = 0; i < 20; i++) { + await step(tester); + } + + expect(server.received("POST", "api/locate/"), isEmpty); + expect(complete, isFalse); + + // Submit the form (with the default plugin selected) + await tester.tap(find.byIcon(TablerIcons.location_search)); + + await waitUntil(tester, () => complete, reason: "locate complete"); + + final requests = server.received("POST", "api/locate/"); + + expect(requests, hasLength(1)); + expect(requests.first.json, equals({"plugin": "first", "item": "5"})); + + await disconnectInWidgetTest(tester); + }); + + testWidgets("Cancelled plugin selection sends no request", (tester) async { + bool complete = false; + + await startLocate(tester, () => complete = true); + + await tester.pageBack(); + + await waitUntil(tester, () => complete, reason: "locate complete"); + + for (int i = 0; i < 10; i++) { + await step(tester); + } + + expect(server.received("POST", "api/locate/"), isEmpty); + + await disconnectInWidgetTest(tester); + }); +}