From db4569ff527a425033e47218b9c5721fa13f3f43 Mon Sep 17 00:00:00 2001 From: Oliver Date: Tue, 3 Nov 2026 07:35:50 +1100 Subject: [PATCH] More coverage (#905) * Exclude translation files from coverage * added unit test --- .github/workflows/ci.yaml | 6 + assets/release_notes.md | 1 + lib/api_form.dart | 6 +- test/api_form_test.dart | 271 ++++++++++++++++ test/helpers_test.dart | 92 ++++++ test/managed_config_test.dart | 115 +++++++ test/model_json_test.dart | 583 ++++++++++++++++++++++++++++++++++ test/order_models_test.dart | 578 +++++++++++++++++++++++++++++++++ test/status_codes_test.dart | 128 ++++++++ 9 files changed, 1779 insertions(+), 1 deletion(-) create mode 100644 test/api_form_test.dart create mode 100644 test/helpers_test.dart create mode 100644 test/managed_config_test.dart create mode 100644 test/model_json_test.dart create mode 100644 test/order_models_test.dart create mode 100644 test/status_codes_test.dart diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 0168ad83..d3425308 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -84,6 +84,12 @@ jobs: run: | fvm flutter test --coverage + # Generated translation files are not exercised by tests, and swamp the coverage report + - name: Exclude Translation Files from Coverage + run: | + awk '/^SF:/ { skip = ($0 ~ /lib\/l10n\//) } !skip; /^end_of_record/ { skip = 0 }' coverage/lcov.info > coverage/lcov.filtered.info + mv coverage/lcov.filtered.info coverage/lcov.info + - name: Coveralls uses: coverallsapp/github-action@master with: diff --git a/assets/release_notes.md b/assets/release_notes.md index aa2e5b9d..968e9845 100644 --- a/assets/release_notes.md +++ b/assets/release_notes.md @@ -8,6 +8,7 @@ - Expired sessions now return the user to the login screen - Credentials are removed from error reports - Requires InvenTree server API version 314 or newer - existing users must log in again +- Updated translations ## 0.26.0 - October 2026 --- diff --git a/lib/api_form.dart b/lib/api_form.dart index e42a24cd..c914acfb 100644 --- a/lib/api_form.dart +++ b/lib/api_form.dart @@ -40,7 +40,11 @@ Map extractFields(APIResponse response) { var actions = response.data["actions"] as Map; - dynamic result = actions["POST"] ?? actions["PUT"] ?? actions["PATCH"] ?? {}; + dynamic result = + actions["POST"] ?? + actions["PUT"] ?? + actions["PATCH"] ?? + {}; return result as Map; } diff --git a/test/api_form_test.dart b/test/api_form_test.dart new file mode 100644 index 00000000..f2f343b9 --- /dev/null +++ b/test/api_form_test.dart @@ -0,0 +1,271 @@ +/* + * Unit tests for APIFormField (no server or widgets required) + */ + +import "package:flutter_test/flutter_test.dart"; +import "package:inventree/api.dart"; +import "package:inventree/api_form.dart"; + +void main() { + group("Extract Fields:", () { + test("Invalid Response", () async { + expect(extractFields(APIResponse()), isEmpty); + expect(extractFields(APIResponse(statusCode: 500)), isEmpty); + }); + + test("No Actions", () async { + expect( + extractFields(APIResponse(statusCode: 200, data: {"name": "x"})), + isEmpty, + ); + + expect( + extractFields( + APIResponse(statusCode: 200, data: {"actions": {}}), + ), + isEmpty, + ); + }); + + test("Action Priority", () async { + Map fields(Map actions) => + extractFields( + APIResponse(statusCode: 200, data: {"actions": actions}), + ); + + expect( + fields({ + "POST": {"a": {}}, + "PUT": {"b": {}}, + }).keys, + equals(["a"]), + ); + + expect( + fields({ + "PUT": {"b": {}}, + "PATCH": {"c": {}}, + }).keys, + equals(["b"]), + ); + + expect( + fields({ + "PATCH": {"c": {}}, + }).keys, + equals(["c"]), + ); + }); + }); + + group("Form Field:", () { + test("Defaults", () async { + final field = APIFormField("name", {}); + + expect(field.pk_field, equals("pk")); + expect(field.api_url, equals("")); + expect(field.model, equals("")); + expect(field.hidden, isFalse); + expect(field.nested, isFalse); + expect(field.parent, equals("")); + expect(field.isSimple, isTrue); + expect(field.readOnly, isFalse); + expect(field.multiline, isFalse); + expect(field.required, isFalse); + expect(field.type, equals("")); + expect(field.label, equals("")); + expect(field.helpText, equals("")); + expect(field.placeholderText, equals("")); + expect(field.choices, isEmpty); + expect(field.value, isNull); + expect(field.defaultValue, isNull); + expect(field.filters, isEmpty); + expect(field.hasErrors(), isFalse); + expect(field.renderValueToString(), equals("")); + }); + + test("Parameters", () async { + final field = APIFormField("part", {"label": "Local Label"}); + + field.definition = { + "label": "Server Label", + "help_text": "Select a part", + "type": "related field", + "required": true, + "read_only": false, + "model": "part", + "api_url": "/api/part/", + "placeholder": "Part", + "choices": [ + {"value": 1, "display_name": "One"}, + ], + }; + + // Local data takes priority over the server definition + expect(field.label, equals("Local Label")); + + expect(field.helpText, equals("Select a part")); + expect(field.type, equals("related field")); + expect(field.required, isTrue); + expect(field.readOnly, isFalse); + expect(field.model, equals("part")); + expect(field.api_url, equals("/api/part/")); + expect(field.placeholderText, equals("Part")); + expect(field.choices.length, equals(1)); + expect(field.getParameter("missing"), isNull); + }); + + test("Value", () async { + final field = APIFormField("quantity", {}); + + field.definition = {"default": 1}; + expect(field.value, equals(1)); + + field.data["instance_value"] = 5; + expect(field.value, equals(5)); + + // Value is not rendered from the default or instance value + expect(field.renderValueToString(), equals("")); + + field.setFieldValue(10); + expect(field.value, equals(10)); + expect(field.renderValueToString(), equals("10")); + }); + + test("Lookup Path", () async { + expect(APIFormField("name", {}).lookupPath, equals("name")); + + expect( + APIFormField("quantity", {"parent": "items"}).lookupPath, + equals("items.child"), + ); + + expect( + APIFormField("quantity", {"nested": true}).lookupPath, + equals("children.quantity"), + ); + + final field = APIFormField("quantity", { + "parent": "items", + "nested": true, + }); + + expect(field.isSimple, isFalse); + expect(field.lookupPath, equals("items.child.children.quantity")); + }); + + test("Filters", () async { + final field = APIFormField("location", { + "filters": {"structural": false, "parent": 3}, + }); + + field.definition = { + "filters": {"active": true, "parent": 1}, + "instance_filters": {"category": 2}, + }; + + // Filters are merged, with local filters taking priority + expect( + field.filters, + equals({ + "active": "true", + "parent": "3", + "category": "2", + "structural": "false", + }), + ); + + // Malformed filters are ignored + final invalid = APIFormField("location", {"filters": "invalid"}); + invalid.definition = {"filters": 1, "instance_filters": []}; + + expect(invalid.filters, isEmpty); + }); + }); + + group("Form Field Errors:", () { + test("Simple Field", () async { + final field = APIFormField("name", {}); + + field.extractErrorMessages( + APIResponse( + statusCode: 400, + data: { + "name": ["This field is required", "Too short"], + }, + ), + ); + + expect(field.hasErrors(), isTrue); + expect( + field.errorMessages(), + equals(["This field is required", "Too short"]), + ); + + // Single string error message + field.extractErrorMessages( + APIResponse(statusCode: 400, data: {"name": "Invalid name"}), + ); + + expect(field.errorMessages(), equals(["Invalid name"])); + + // No error for this field + field.extractErrorMessages( + APIResponse(statusCode: 400, data: {"other": "error"}), + ); + + expect(field.hasErrors(), isFalse); + }); + + test("Nested Field", () async { + final field = APIFormField("quantity", { + "parent": "items", + "nested": true, + }); + + // Errors returned as a list (one entry per nested item) + field.extractErrorMessages( + APIResponse( + statusCode: 400, + data: { + "items": [ + { + "quantity": ["Must be positive"], + }, + ], + }, + ), + ); + + expect(field.errorMessages(), equals(["Must be positive"])); + + // Errors returned as a map + field.extractErrorMessages( + APIResponse( + statusCode: 400, + data: { + "items": {"quantity": "Invalid quantity"}, + }, + ), + ); + + expect(field.errorMessages(), equals(["Invalid quantity"])); + + // Parent element is missing + field.extractErrorMessages(APIResponse(statusCode: 400, data: {})); + + expect(field.hasErrors(), isFalse); + }); + + test("Nested Field Without Parent", () async { + // A nested field with no parent cannot be matched to errors + final field = APIFormField("quantity", {"nested": true}); + + field.extractErrorMessages( + APIResponse(statusCode: 400, data: {"quantity": "error"}), + ); + + expect(field.hasErrors(), isFalse); + }); + }); +} diff --git a/test/helpers_test.dart b/test/helpers_test.dart new file mode 100644 index 00000000..7be69184 --- /dev/null +++ b/test/helpers_test.dart @@ -0,0 +1,92 @@ +/* + * Unit tests for the helper functions in helpers.dart + */ + +import "package:flutter_test/flutter_test.dart"; +import "package:inventree/helpers.dart"; + +void main() { + group("Number Helpers:", () { + test("Simple Number String", () async { + expect(simpleNumberString(0), equals("0")); + expect(simpleNumberString(10), equals("10")); + expect(simpleNumberString(-3), equals("-3")); + expect(simpleNumberString(1.5), equals("1.5")); + expect(simpleNumberString(0.25), equals("0.25")); + }); + + test("Valid Number", () async { + expect(isValidNumber(1.0), isTrue); + expect(isValidNumber(0), isTrue); + expect(isValidNumber(-1.5), isTrue); + expect(isValidNumber(null), isFalse); + expect(isValidNumber(double.nan), isFalse); + expect(isValidNumber(double.infinity), isFalse); + expect(isValidNumber(double.negativeInfinity), isFalse); + }); + }); + + group("Currency Helpers:", () { + test("Invalid Values", () async { + expect(renderCurrency(null, "USD"), equals("-")); + expect(renderCurrency(double.nan, "USD"), equals("-")); + expect(renderCurrency(double.infinity, "USD"), equals("-")); + expect(renderCurrency(10, ""), equals("-")); + expect(renderCurrency(10, " "), equals("-")); + }); + + test("Render Currency", () async { + String usd = renderCurrency(12.5, "USD"); + expect(usd, contains("\$")); + expect(usd, contains("12.50")); + + // Currency code is case insensitive, and whitespace is ignored + expect(renderCurrency(12.5, " usd "), equals(usd)); + + // Unknown currency codes fall back to USD formatting + expect(renderCurrency(12.5, "XYZ"), equals(usd)); + + expect(renderCurrency(12.5, "EUR"), contains("€")); + }); + + test("Price Range", () async { + String low = renderCurrency(1, "USD"); + String high = renderCurrency(2, "USD"); + + expect(formatPriceRange(null, null), equals("-")); + expect(formatPriceRange(double.nan, double.infinity), equals("-")); + + expect(formatPriceRange(1, 1), equals(low)); + expect(formatPriceRange(1, 2), equals("${low} - ${high}")); + + // Only one valid value + expect(formatPriceRange(1, null), equals(low)); + expect(formatPriceRange(null, 2), equals(high)); + expect(formatPriceRange(double.nan, 2), equals(high)); + + // Currency is passed through + expect( + formatPriceRange(1, 2, currency: "EUR"), + equals("${renderCurrency(1, "EUR")} - ${renderCurrency(2, "EUR")}"), + ); + }); + }); + + group("Debug Helpers:", () { + test("Debug Messages", () async { + expect(isTesting(), isTrue); + expect(hasContext(), isFalse); + + int count = debugMessageCount(); + + debug("helpers_test: a unique message"); + + expect(debugMessageCount(), equals(count + 1)); + expect(debugContains("helpers_test: a unique message"), isTrue); + expect( + debugContains("helpers_test: missing", raiseAssert: false), + isFalse, + ); + }); + }); +} diff --git a/test/managed_config_test.dart b/test/managed_config_test.dart new file mode 100644 index 00000000..7718f4d9 --- /dev/null +++ b/test/managed_config_test.dart @@ -0,0 +1,115 @@ +/* + * Unit tests for parsing of managed (MDM) configuration values + */ + +import "package:flutter/material.dart"; +import "package:flutter_test/flutter_test.dart"; +import "package:inventree/managed_config.dart"; + +void main() { + group("Managed Setting:", () { + test("Null Value", () async { + for (final type in ManagedSettingType.values) { + expect(ManagedSetting("key", type).parse(null), isNull); + } + }); + + test("Boolean", () async { + const setting = ManagedSetting("key", ManagedSettingType.boolean); + + for (final value in [true, "true", " TRUE ", "1", 1, "yes", "On"]) { + expect(setting.parse(value), isTrue, reason: "value: '${value}'"); + } + + for (final value in [false, "false", "0", 0, "No", "off"]) { + expect(setting.parse(value), isFalse, reason: "value: '${value}'"); + } + + for (final value in ["", "maybe", 2, "truthy"]) { + expect(setting.parse(value), isNull, reason: "value: '${value}'"); + } + }); + + test("Integer", () async { + const setting = ManagedSetting("key", ManagedSettingType.integer); + + expect(setting.parse(5), equals(5)); + expect(setting.parse(7.9), equals(7)); + expect(setting.parse(" 42 "), equals(42)); + expect(setting.parse("-3"), equals(-3)); + expect(setting.parse("abc"), isNull); + expect(setting.parse("1.5"), isNull); + }); + + test("Integer Limits", () async { + const setting = ManagedSetting( + "key", + ManagedSettingType.integer, + minimum: 1, + maximum: 10, + ); + + expect(setting.parse(5), equals(5)); + expect(setting.parse(0), equals(1)); + expect(setting.parse("-100"), equals(1)); + expect(setting.parse(11), equals(10)); + expect(setting.parse("1000"), equals(10)); + }); + + test("Choice", () async { + const setting = ManagedSetting( + "key", + ManagedSettingType.choice, + choices: {"System": 0, "portrait": 1, "landscape": 2}, + ); + + // Match by name (case insensitive) + expect(setting.parse("system"), equals(0)); + expect(setting.parse(" PORTRAIT "), equals(1)); + expect(setting.parse("Landscape"), equals(2)); + + // Match by value + expect(setting.parse(2), equals(2)); + expect(setting.parse("1"), equals(1)); + + // No match + expect(setting.parse("sideways"), isNull); + expect(setting.parse(3), isNull); + expect(setting.parse("-1"), isNull); + }); + + test("Managed Settings List", () async { + // Every managed setting must have a unique key + final keys = MANAGED_SETTINGS.map((s) => s.key).toList(); + expect(keys.toSet().length, equals(keys.length)); + + for (final setting in MANAGED_SETTINGS) { + if (setting.type == ManagedSettingType.choice) { + expect(setting.choices, isNotEmpty, reason: setting.key); + } + } + }); + }); + + group("Managed Locale:", () { + test("Exact Match", () async { + expect(matchSupportedLocale("de_DE"), equals(const Locale("de", "DE"))); + expect(matchSupportedLocale("pt-PT"), equals(const Locale("pt", "PT"))); + expect(matchSupportedLocale("zh_tw"), equals(const Locale("zh", "TW"))); + expect(matchSupportedLocale(" en "), equals(const Locale("en", ""))); + }); + + test("Language Match", () async { + // Falls back to the first supported locale for the language + expect(matchSupportedLocale("fr"), equals(const Locale("fr", "FR"))); + expect(matchSupportedLocale("ES"), equals(const Locale("es", "ES"))); + }); + + test("No Match", () async { + expect(matchSupportedLocale(""), isNull); + expect(matchSupportedLocale(" "), isNull); + expect(matchSupportedLocale("xx"), isNull); + expect(matchSupportedLocale("xx_YY"), isNull); + }); + }); +} diff --git a/test/model_json_test.dart b/test/model_json_test.dart new file mode 100644 index 00000000..8236f164 --- /dev/null +++ b/test/model_json_test.dart @@ -0,0 +1,583 @@ +/* + * Unit tests for model classes constructed from JSON data + * + * These tests do not require a connection to the server + */ + +import "package:flutter_test/flutter_test.dart"; +import "package:inventree/api.dart"; +import "package:inventree/inventree/model.dart"; +import "package:inventree/inventree/orders.dart"; +import "package:inventree/inventree/part.dart"; +import "package:inventree/inventree/stock.dart"; +import "package:inventree/l10.dart"; + +void main() { + group("Model Accessors:", () { + test("Empty Data", () async { + final model = InvenTreeModel.fromJson({}); + + expect(model.pk, equals(-1)); + expect(model.name, equals("")); + expect(model.description, equals("")); + expect(model.getString("missing", backup: "x"), equals("x")); + expect(model.getInt("missing", backup: 7), equals(7)); + expect(model.getDouble("missing"), equals(0.0)); + expect(model.getDoubleOrNull("missing"), isNull); + expect(model.getBool("missing"), isFalse); + expect(model.getBool("missing", backup: true), isTrue); + expect(model.getDate("missing"), isNull); + expect(model.getDateString("missing"), equals("")); + expect(model.getMap("missing"), isEmpty); + expect(model.link, equals("")); + expect(model.hasLink, isFalse); + expect(model.customIcon, isNull); + expect(model.customBarcode, equals("")); + expect(model.reloadedWithin(const Duration(days: 1)), isFalse); + }); + + test("Typed Values", () async { + final model = InvenTreeModel.fromJson({ + "pk": 12, + "name": "Widget", + "count": "42", + "bad_int": "abc", + "ratio": "1.5", + "bad_double": "x", + "flag": "True", + "not_flag": "yes", + "null_value": null, + "date": "2024-03-07T10:15:00Z", + "detail": {"name": "Sub", "count": 3}, + }); + + expect(model.pk, equals(12)); + expect(model.pkString, equals("12")); + expect(model.name, equals("Widget")); + + expect(model.getInt("count"), equals(42)); + expect(model.getInt("bad_int"), equals(-1)); + expect(model.getDouble("ratio"), equals(1.5)); + expect(model.getDoubleOrNull("bad_double"), isNull); + expect(model.getBool("flag"), isTrue); + expect(model.getBool("not_flag"), isFalse); + + // Explicit null values return the backup + expect(model.getString("null_value", backup: "b"), equals("b")); + expect(model.getInt("null_value", backup: 3), equals(3)); + expect(model.getBool("null_value", backup: true), isTrue); + expect(model.getMap("null_value"), isEmpty); + + expect(model.getDate("date")?.year, equals(2024)); + expect(model.getDateString("date"), equals("2024-03-07")); + + // Sub-key lookups + expect(model.getString("name", subKey: "detail"), equals("Sub")); + expect(model.getInt("count", subKey: "detail"), equals(3)); + expect(model.getMap("detail")["name"], equals("Sub")); + expect( + model.getString("name", subKey: "missing", backup: "none"), + equals("none"), + ); + + model.setValue("name", "Gadget"); + expect(model.name, equals("Gadget")); + }); + + test("Status", () async { + var model = InvenTreeModel.fromJson({"status": 10}); + + expect(model.status, equals(10)); + expect(model.hasCustomStatus, isFalse); + + model = InvenTreeModel.fromJson({"status": 10, "status_custom_key": 101}); + + expect(model.logicalStatus, equals(10)); + expect(model.customStatus, equals(101)); + expect(model.status, equals(101)); + }); + + test("Link", () async { + expect( + InvenTreeModel.fromJson({"link": "https://a.com"}).link, + equals("https://a.com"), + ); + + // Legacy API used "URL" + final legacy = InvenTreeModel.fromJson({"URL": "https://b.com"}); + expect(legacy.link, equals("https://b.com")); + expect(legacy.hasLink, isTrue); + }); + + test("Custom Icon", () async { + expect(InvenTreeModel.fromJson({"icon": " "}).customIcon, isNull); + expect(InvenTreeModel.fromJson({"icon": "fa:box"}).customIcon, isNull); + expect(InvenTreeModel.fromJson({"icon": "ti:"}).customIcon, isNull); + expect( + InvenTreeModel.fromJson({"icon": "ti:not-an-icon:outline"}).customIcon, + isNull, + ); + expect( + InvenTreeModel.fromJson({"icon": "ti:box:outline"}).customIcon, + isNotNull, + ); + expect( + InvenTreeModel.fromJson({"icon": "ti:arrow-left:outline"}).customIcon, + isNotNull, + ); + }); + + test("Custom Barcode", () async { + expect( + InvenTreeModel.fromJson({ + "uid": "abc", + "barcode_hash": "def", + }).customBarcode, + equals("abc"), + ); + expect( + InvenTreeModel.fromJson({ + "barcode_hash": "def", + "barcode": "ghi", + }).customBarcode, + equals("def"), + ); + expect( + InvenTreeModel.fromJson({"barcode": "ghi"}).customBarcode, + equals("ghi"), + ); + }); + + test("Detail URL", () async { + final part = InvenTreePart.fromJson({"pk": 5}); + expect(part.url, equals("part/5/")); + + final item = InvenTreeStockItem.fromJson({"pk": 9}); + expect(item.url, equals("stock/9/")); + }); + + test("Reloaded Within", () async { + final model = InvenTreeModel.fromJson({}); + + model.lastReload = DateTime.now(); + expect(model.reloadedWithin(const Duration(minutes: 1)), isTrue); + + model.lastReload = DateTime.now().subtract(const Duration(hours: 1)); + expect(model.reloadedWithin(const Duration(minutes: 1)), isFalse); + }); + }); + + group("Part Category:", () { + test("Path", () async { + var category = InvenTreePartCategory.fromJson({ + "pathstring": "Electronics/Passives/Resistors", + }); + + expect(category.parentPathString, equals("Electronics/Passives")); + + category = InvenTreePartCategory.fromJson({"pathstring": "Electronics"}); + + expect(category.parentPathString, equals(L10().partCategoryTopLevel)); + }); + + test("Part Count", () async { + expect(InvenTreePartCategory.fromJson({}).partcount, equals(0)); + expect( + InvenTreePartCategory.fromJson({"part_count": 4}).partcount, + equals(4), + ); + + // Legacy API used "parts" + expect(InvenTreePartCategory.fromJson({"parts": 3}).partcount, equals(3)); + }); + }); + + group("Part:", () { + test("Full Name", () async { + expect( + InvenTreePart.fromJson({ + "full_name": "IPN | Name", + "name": "x", + }).fullname, + equals("IPN | Name"), + ); + + expect( + InvenTreePart.fromJson({"name": "Widget"}).fullname, + equals("Widget"), + ); + + expect( + InvenTreePart.fromJson({ + "name": "Widget", + "IPN": "W-001", + "revision": "B", + }).fullname, + equals("W-001 | Widget | B"), + ); + }); + + test("Stock", () async { + var part = InvenTreePart.fromJson({"in_stock": 10}); + + expect(part.inStock, equals(10)); + expect(part.unallocatedStock, equals(10)); + expect(part.stockString(), equals("10")); + + part = InvenTreePart.fromJson({ + "in_stock": 1, + "total_in_stock": 12.5, + "unallocated_stock": "4", + "units": "m", + "ordering": 3, + }); + + expect(part.inStock, equals(12.5)); + expect(part.inStockString, equals("12.5")); + expect(part.unallocatedStock, equals(4)); + expect(part.stockString(), equals("4 / 12.5 m")); + expect(part.stockString(includeUnits: false), equals("4 / 12.5")); + expect(part.onOrderString, equals("3")); + + // Available stock cannot be negative + part = InvenTreePart.fromJson({"in_stock": 1, "unallocated_stock": -5}); + + expect(part.unallocatedStock, equals(0)); + }); + + test("Category", () async { + final detail = {"name": "Resistors", "description": "Fixed resistors"}; + + var part = InvenTreePart.fromJson({ + "category": 4, + "category_detail": detail, + }); + + expect(part.categoryId, equals(4)); + expect(part.categoryName, equals("Resistors")); + expect(part.categoryDescription, equals("Fixed resistors")); + + // Missing detail + part = InvenTreePart.fromJson({"category": 4}); + expect(part.categoryName, equals("")); + expect(part.categoryDescription, equals("")); + + // No category + part = InvenTreePart.fromJson({"category_detail": detail}); + expect(part.categoryName, equals("")); + expect(part.categoryDescription, equals("")); + }); + + test("Images", () async { + var part = InvenTreePart.fromJson({}); + expect(part.image, equals(InvenTreeAPI.staticImage)); + expect(part.thumbnail, equals(InvenTreeAPI.staticThumb)); + + part = InvenTreePart.fromJson({"image": "/media/a.png"}); + expect(part.image, equals("/media/a.png")); + expect(part.thumbnail, equals("/media/a.png")); + + part = InvenTreePart.fromJson({"thumbnail": "/media/a.thumb.png"}); + expect(part.image, equals("/media/a.thumb.png")); + expect(part.thumbnail, equals("/media/a.thumb.png")); + }); + + test("Attributes", () async { + final part = InvenTreePart.fromJson({ + "assembly": true, + "component": false, + "purchaseable": true, + "salable": false, + "active": true, + "virtual": false, + "is_template": true, + "trackable": true, + "testable": false, + "starred": true, + "used_in": 6, + "variant_of": 2, + "default_location": 8, + }); + + expect(part.isAssembly, isTrue); + expect(part.isComponent, isFalse); + expect(part.isPurchaseable, isTrue); + expect(part.isSalable, isFalse); + expect(part.isActive, isTrue); + expect(part.isVirtual, isFalse); + expect(part.isTemplate, isTrue); + expect(part.isTrackable, isTrue); + expect(part.isTestable, isFalse); + expect(part.starred, isTrue); + expect(part.usedInCount, equals(6)); + expect(part.variantOf, equals(2)); + expect(part.defaultLocation, equals(8)); + + expect(InvenTreePart.fromJson({}).usedInCount, equals(0)); + }); + + test("Pricing", () async { + var pricing = InvenTreePartPricing.fromJson({}); + + expect(pricing.currency, equals("USD")); + expect(pricing.overallMin, isNull); + + pricing = InvenTreePartPricing.fromJson({ + "currency": "AUD", + "overall_min": "1.25", + "overall_max": 3, + }); + + expect(pricing.currency, equals("AUD")); + expect(pricing.overallMin, equals(1.25)); + expect(pricing.overallMax, equals(3)); + }); + }); + + group("Stock Item:", () { + test("Quantity", () async { + var item = InvenTreeStockItem.fromJson({"quantity": 10}); + + expect(item.isSerialized(), isFalse); + expect(item.quantityString(), equals("10")); + expect(item.serialOrQuantityDisplay(), equals("10")); + expect(item.displayQuantity, equals("10")); + + item = InvenTreeStockItem.fromJson({ + "quantity": 10, + "allocated": 4, + "part_detail": {"units": "kg"}, + }); + + expect(item.available, equals(6)); + expect(item.quantityString(), equals("6 / 10 kg")); + expect(item.quantityString(includeUnits: false), equals("6 / 10")); + expect(item.serialOrQuantityDisplay(), equals("6.0 / 10.0")); + expect(item.displayQuantity, equals("10 kg")); + }); + + test("Serial Number", () async { + var item = InvenTreeStockItem.fromJson({"quantity": 1, "serial": "123"}); + + expect(item.isSerialized(), isTrue); + expect(item.serialOrQuantityDisplay(), equals("SN 123")); + expect(item.displayQuantity, equals("SN: 123")); + + // Serial number with quantity > 1 is not considered serialized + item = InvenTreeStockItem.fromJson({"quantity": 2, "serial": "123"}); + expect(item.isSerialized(), isFalse); + }); + + test("Part Information", () async { + var item = InvenTreeStockItem.fromJson({ + "part_detail": { + "full_name": "Widget | A", + "description": "A widget", + "thumbnail": "/media/w.thumb.png", + }, + }); + + expect(item.partName, equals("Widget | A")); + expect(item.partDescription, equals("A widget")); + expect(item.partImage, equals("/media/w.thumb.png")); + expect(item.partThumbnail, equals("/media/w.thumb.png")); + + // Legacy API fields + item = InvenTreeStockItem.fromJson({ + "part__name": "Old", + "part__description": "Old desc", + "part__thumbnail": "/media/old.png", + }); + + expect(item.partName, equals("Old")); + expect(item.partDescription, equals("Old desc")); + expect(item.partImage, equals("/media/old.png")); + expect(item.partThumbnail, equals("/media/old.png")); + + // Image used as thumbnail backup + item = InvenTreeStockItem.fromJson({ + "part_detail": {"image": "/media/w.png"}, + }); + + expect(item.partThumbnail, equals("/media/w.png")); + + // No image at all + expect( + InvenTreeStockItem.fromJson({}).partThumbnail, + equals(InvenTreeAPI.staticThumb), + ); + }); + + test("Supplier Information", () async { + var item = InvenTreeStockItem.fromJson({ + "supplier_part": 3, + "supplier_part_detail": { + "SKU": "SKU-1", + "supplier_detail": {"image": "/media/s1.png"}, + }, + "supplier_detail": {"supplier_name": "ACME"}, + }); + + expect(item.supplierPartId, equals(3)); + expect(item.supplierSKU, equals("SKU-1")); + expect(item.supplierImage, equals("/media/s1.png")); + expect(item.supplierName, equals("ACME")); + + item = InvenTreeStockItem.fromJson({ + "supplier_detail": {"image": "/media/s2.png"}, + }); + + expect(item.supplierImage, equals("/media/s2.png")); + expect(InvenTreeStockItem.fromJson({}).supplierImage, equals("")); + }); + + test("Location", () async { + var item = InvenTreeStockItem.fromJson({}); + + expect(item.locationName, equals("Unknown Location")); + expect(item.locationPathString, equals(L10().locationNotSet)); + + item = InvenTreeStockItem.fromJson({ + "location": 7, + "location_detail": {"name": "Shelf", "pathstring": "Store/Shelf"}, + }); + + expect(item.locationId, equals(7)); + expect(item.locationName, equals("Shelf")); + expect(item.locationPathString, equals("Store/Shelf")); + + // Legacy name, and no pathstring + item = InvenTreeStockItem.fromJson({ + "location": 7, + "location_detail": {}, + "location__name": "Bin", + }); + + expect(item.locationName, equals("Bin")); + expect(item.locationPathString, equals("Bin")); + }); + + test("Purchase Price", () async { + var item = InvenTreeStockItem.fromJson({}); + + expect(item.purchasePrice, isNull); + expect(item.hasPurchasePrice, isFalse); + + item = InvenTreeStockItem.fromJson({ + "purchase_price": "2.50", + "purchase_price_currency": "AUD", + }); + + expect(item.purchasePrice, equals(2.5)); + expect(item.hasPurchasePrice, isTrue); + expect(item.purchasePriceCurrency, equals("AUD")); + + item = InvenTreeStockItem.fromJson({"purchase_price": "0"}); + expect(item.hasPurchasePrice, isFalse); + }); + + test("Attributes", () async { + var item = InvenTreeStockItem.fromJson({}); + + expect(item.isInStock, isTrue); + expect(item.hasSalesOrder, isFalse); + expect(item.hasCustomer, isFalse); + + item = InvenTreeStockItem.fromJson({ + "in_stock": false, + "sales_order": 4, + "customer": 2, + "stale": true, + "expired": false, + "expiry_date": "2025-01-31", + "batch": "B1", + "packaging": "Reel", + }); + + expect(item.isInStock, isFalse); + expect(item.hasSalesOrder, isTrue); + expect(item.hasCustomer, isTrue); + expect(item.stale, isTrue); + expect(item.expired, isFalse); + expect(item.expiryDateString, equals("2025-01-31")); + expect(item.batch, equals("B1")); + expect(item.packaging, equals("Reel")); + }); + }); + + group("Orders:", () { + test("Order", () async { + var order = InvenTreeOrder.fromJson({}); + + expect(order.lineItemCount, equals(0)); + expect(order.complete, isTrue); + expect(order.totalPrice, isNull); + expect(order.totalPriceCurrency, equals("")); + expect(order.hasProjectCode, isFalse); + + order = InvenTreeOrder.fromJson({ + "reference": "PO-0001", + "line_items": 5, + "completed_lines": 2, + "total_price": "100.5", + "order_currency": "AUD", + "total_price_currency": "USD", + "target_date": "2025-06-01", + "project_code_detail": {"code": "PRJ", "description": "Project"}, + "responsible_detail": {"name": "team", "label": "Team"}, + }); + + expect(order.reference, equals("PO-0001")); + expect(order.complete, isFalse); + expect(order.totalPrice, equals(100.5)); + expect(order.totalPriceCurrency, equals("AUD")); + expect(order.targetDate, equals("2025-06-01")); + expect(order.hasProjectCode, isTrue); + expect(order.projectCodeDescription, equals("Project")); + expect(order.responsibleName, equals("team")); + expect(order.responsibleLabel, equals("Team")); + + // Legacy currency field + order = InvenTreeOrder.fromJson({"total_price_currency": "USD"}); + expect(order.totalPriceCurrency, equals("USD")); + }); + + test("Order Line", () async { + var line = InvenTreeOrderLine.fromJson({"quantity": 3}); + + expect(line.quantity, equals(3)); + expect(line.part, isNull); + expect(line.partImage, equals("")); + + line = InvenTreeOrderLine.fromJson({ + "part_detail": { + "pk": 4, + "name": "Widget", + "description": "A widget", + "image": "/media/w.png", + }, + }); + + expect(line.part?.name, equals("Widget")); + expect(line.partId, equals(4)); + expect(line.partName, equals("Widget")); + expect(line.partDescription, equals("A widget")); + expect(line.partImage, equals("/media/w.png")); + }); + + test("Extra Line", () async { + final line = InvenTreeExtraLineItem.fromJson({ + "order": 2, + "quantity": "1.5", + "price": "10", + "price_currency": "EUR", + }); + + expect(line.orderId, equals(2)); + expect(line.quantity, equals(1.5)); + expect(line.price, equals(10)); + expect(line.priceCurrency, equals("EUR")); + expect(line.formFields()["order"]?["hidden"], isTrue); + }); + }); +} diff --git a/test/order_models_test.dart b/test/order_models_test.dart new file mode 100644 index 00000000..95d1786d --- /dev/null +++ b/test/order_models_test.dart @@ -0,0 +1,578 @@ +/* + * Unit tests for order and company model classes constructed from JSON data + * + * Status code data is provided directly, rather than loaded from the server + */ + +import "package:flutter_test/flutter_test.dart"; +import "package:inventree/api.dart"; +import "package:inventree/inventree/build.dart"; +import "package:inventree/inventree/company.dart"; +import "package:inventree/inventree/purchase_order.dart"; +import "package:inventree/inventree/sales_order.dart"; +import "package:inventree/inventree/transfer_order.dart"; +import "package:inventree/l10.dart"; + +// Construct status code data in the format provided by the server +Map statusData(Map codes) { + return codes.map( + (name, key) => + MapEntry(name, {"key": key, "name": name, "label": name.toLowerCase()}), + ); +} + +void main() { + setUp(() { + InvenTreeAPI().BuildOrderStatus.data = statusData({ + "PENDING": 10, + "PRODUCTION": 20, + "CANCELLED": 30, + "COMPLETE": 40, + "ON_HOLD": 25, + }); + + InvenTreeAPI().PurchaseOrderStatus.data = statusData({ + "PENDING": 10, + "PLACED": 20, + "ON_HOLD": 25, + "COMPLETE": 30, + "CANCELLED": 40, + "LOST": 50, + "RETURNED": 60, + }); + + InvenTreeAPI().SalesOrderStatus.data = statusData({ + "PENDING": 10, + "IN_PROGRESS": 15, + "SHIPPED": 20, + "ON_HOLD": 25, + "COMPLETE": 30, + "CANCELLED": 40, + }); + }); + + tearDown(() { + InvenTreeAPI().clearStatusCodeData(); + InvenTreeAPI().serverInfo = {}; + }); + + group("Build Order:", () { + test("Quantities", () async { + var build = InvenTreeBuildOrder.fromJson({ + "quantity": 10, + "completed": 4, + "item_count": 3, + "allocated_line_count": 3, + "output_count": 2, + }); + + expect(build.progressPercent, equals(40)); + expect(build.remaining, equals(6)); + expect(build.lineItemCount, equals(3)); + expect(build.areAllLinesAllocated, isTrue); + expect(build.outputCount, equals(2)); + + // Progress is clamped + build = InvenTreeBuildOrder.fromJson({"quantity": 10, "completed": 15}); + expect(build.progressPercent, equals(100)); + + build = InvenTreeBuildOrder.fromJson({"quantity": 0, "completed": 1}); + expect(build.progressPercent, equals(0)); + + // No line items + expect(InvenTreeBuildOrder.fromJson({}).areAllLinesAllocated, isFalse); + }); + + test("Details", () async { + var build = InvenTreeBuildOrder.fromJson({ + "parent": 3, + "part_detail": {"name": "Assembly"}, + "destination_detail": {"name": "Store"}, + }); + + expect(build.isParentBuild, isTrue); + expect(build.parentBuildId, equals(3)); + expect(build.partDetail?.name, equals("Assembly")); + expect(build.destinationName, equals("Store")); + + build = InvenTreeBuildOrder.fromJson({}); + expect(build.isParentBuild, isFalse); + expect(build.partDetail, isNull); + }); + + test("Status", () async { + InvenTreeBuildOrder build(int status) => + InvenTreeBuildOrder.fromJson({"status": status, "output_count": 1}); + + final pending = build(10); + expect(pending.isWaitingForBuild, isTrue); + expect(pending.canIssue, isTrue); + expect(pending.canHold, isTrue); + expect(pending.canCancel, isTrue); + expect(pending.canCompleteOrder, isFalse); + + final production = build(20); + expect(production.isInProgress, isTrue); + expect(production.canIssue, isFalse); + expect(production.canHold, isTrue); + expect(production.canCompleteOrder, isTrue); + + // Cannot complete without any outputs + expect( + InvenTreeBuildOrder.fromJson({"status": 20}).canCompleteOrder, + isFalse, + ); + + final onHold = build(25); + expect(onHold.isOnHold, isTrue); + expect(onHold.canIssue, isTrue); + expect(onHold.canHold, isFalse); + + final complete = build(40); + expect(complete.isComplete, isTrue); + expect(complete.canCancel, isFalse); + + final cancelled = build(30); + expect(cancelled.isCancelled, isTrue); + expect(cancelled.canCancel, isFalse); + expect(cancelled.canIssue, isFalse); + }); + + test("Build Line", () async { + var line = InvenTreeBuildLine.fromJson({ + "quantity": 10, + "allocated": 5, + "bom_item_detail": {"reference": "R1"}, + }); + + expect(line.isFullyAllocated, isFalse); + expect(line.isOverallocated, isFalse); + expect(line.progressPercent, equals(50)); + expect(line.bomReference, equals("R1")); + + // Allow for floating point error + line = InvenTreeBuildLine.fromJson({ + "quantity": 0.3, + "allocated": 0.1 + 0.2 - 0.00001, + }); + expect(line.isFullyAllocated, isTrue); + + line = InvenTreeBuildLine.fromJson({"quantity": 2, "allocated": 3}); + expect(line.isOverallocated, isTrue); + expect(line.progressPercent, equals(100)); + + line = InvenTreeBuildLine.fromJson({"quantity": 0}); + expect(line.progressPercent, equals(0)); + }); + + test("Build Item", () async { + var item = InvenTreeBuildItem.fromJson({ + "quantity": 2, + "stock_item_detail": {"quantity": 5, "serial": ""}, + "part_detail": {"name": "Resistor"}, + }); + + expect(item.quantity, equals(2)); + expect(item.stockItem?.quantity, equals(5)); + expect(item.partName, equals("Resistor")); + + expect(InvenTreeBuildItem.fromJson({}).stockItem, isNull); + }); + }); + + group("Purchase Order:", () { + test("Status", () async { + InvenTreePurchaseOrder order(int status) => + InvenTreePurchaseOrder.fromJson({"status": status}); + + expect(order(10).isOpen, isTrue); + expect(order(10).isPending, isTrue); + expect(order(10).isPlaced, isFalse); + + expect(order(20).isOpen, isTrue); + expect(order(20).isPlaced, isTrue); + expect(order(20).isPending, isFalse); + + expect(order(25).isPending, isTrue); + + expect(order(30).isOpen, isFalse); + expect(order(30).isFailed, isFalse); + + for (final status in [40, 50, 60]) { + expect(order(status).isFailed, isTrue); + expect(order(status).isOpen, isFalse); + } + }); + + test("Supplier", () async { + var order = InvenTreePurchaseOrder.fromJson({ + "supplier": 2, + "supplier_detail": {"name": "ACME"}, + "supplier_reference": "REF-1", + }); + + expect(order.supplierId, equals(2)); + expect(order.supplier?.name, equals("ACME")); + expect(order.supplierReference, equals("REF-1")); + + expect(InvenTreePurchaseOrder.fromJson({}).supplier, isNull); + }); + + test("Line Item", () async { + var line = InvenTreePOLineItem.fromJson({ + "quantity": 8, + "received": 2, + "purchase_price": "1.5", + "supplier_part_detail": {"SKU": "SKU-1"}, + "order_detail": {"reference": "PO-1"}, + }); + + expect(line.isComplete, isFalse); + expect(line.progressRatio, equals(0.25)); + expect(line.progressString, equals("2 / 8")); + expect(line.outstanding, equals(6)); + expect(line.SKU, equals("SKU-1")); + expect(line.purchasePrice, equals(1.5)); + expect(line.supplierPart?.SKU, equals("SKU-1")); + expect(line.purchaseOrder?.reference, equals("PO-1")); + + line = InvenTreePOLineItem.fromJson({"quantity": 8, "received": 8}); + expect(line.isComplete, isTrue); + expect(line.supplierPart, isNull); + expect(line.purchaseOrder, isNull); + + line = InvenTreePOLineItem.fromJson({"quantity": 0}); + expect(line.progressRatio, equals(0)); + }); + }); + + group("Sales Order:", () { + test("Status", () async { + InvenTreeSalesOrder order(int status) => + InvenTreeSalesOrder.fromJson({"status": status}); + + expect(order(10).isOpen, isTrue); + expect(order(10).isPending, isTrue); + + expect(order(15).isOpen, isTrue); + expect(order(15).isInProgress, isTrue); + expect(order(15).isPending, isFalse); + + expect(order(25).isPending, isTrue); + + expect(order(20).isComplete, isTrue); + expect(order(20).isOpen, isFalse); + + expect(order(40).isOpen, isFalse); + }); + + test("Customer", () async { + var order = InvenTreeSalesOrder.fromJson({ + "customer": 4, + "customer_detail": {"name": "Customer"}, + "customer_reference": "CUST-1", + }); + + expect(order.customerId, equals(4)); + expect(order.customer?.name, equals("Customer")); + expect(order.customerReference, equals("CUST-1")); + + expect(InvenTreeSalesOrder.fromJson({}).customer, isNull); + }); + + test("Line Item", () async { + var line = InvenTreeSOLineItem.fromJson({ + "quantity": 10, + "allocated": 4, + "shipped": 5, + "available_stock": 7, + "available_variant_stock": 3, + }); + + expect(line.isAllocated, isFalse); + expect(line.allocatedRatio, equals(0.4)); + expect(line.unallocatedQuantity, equals(6)); + expect(line.allocatedString, equals("4 / 10")); + expect(line.progressRatio, equals(0.5)); + expect(line.progressString, equals("5 / 10")); + expect(line.outstanding, equals(5)); + expect(line.isComplete, isFalse); + expect(line.availableStock, equals(7)); + expect(line.available, equals(10)); + + // Overallocated + line = InvenTreeSOLineItem.fromJson({ + "quantity": 2, + "allocated": 5, + "shipped": 2, + }); + + expect(line.isAllocated, isTrue); + expect(line.unallocatedQuantity, equals(0)); + expect(line.isComplete, isTrue); + + line = InvenTreeSOLineItem.fromJson({"quantity": 0}); + expect(line.allocatedRatio, equals(0)); + expect(line.progressRatio, equals(0)); + + expect( + line.allocateFormFields()["stock_item"]?["parent"], + equals("items"), + ); + }); + + test("Shipment", () async { + var shipment = InvenTreeSalesOrderShipment.fromJson({ + "pk": 3, + "reference": "SHIP-1", + "checked_by": 1, + "shipment_date": "2025-01-01", + "delivery_date": "", + "order_detail": {"reference": "SO-1"}, + }); + + expect(shipment.SHIP_SHIPMENT_URL, equals("order/so/shipment/3/ship/")); + expect(shipment.reference, equals("SHIP-1")); + expect(shipment.isChecked, isTrue); + expect(shipment.isShipped, isTrue); + expect(shipment.isDelivered, isFalse); + expect(shipment.order?.reference, equals("SO-1")); + + shipment = InvenTreeSalesOrderShipment.fromJson({}); + expect(shipment.isChecked, isFalse); + expect(shipment.isShipped, isFalse); + expect(shipment.order, isNull); + }); + + test("Allocation", () async { + var allocation = InvenTreeSalesOrderAllocation.fromJson({ + "shipment": 2, + "order_detail": {"reference": "SO-1"}, + "item_detail": {"serial": "123"}, + "part_detail": {"name": "Widget"}, + "shipment_detail": {"reference": "SHIP-1"}, + "location_detail": {"name": "Shelf"}, + }); + + expect(allocation.hasShipment, isTrue); + expect(allocation.order?.reference, equals("SO-1")); + expect(allocation.stockItem?.serialNumber, equals("123")); + expect(allocation.part?.name, equals("Widget")); + expect(allocation.shipment?.reference, equals("SHIP-1")); + expect(allocation.location?.name, equals("Shelf")); + + allocation = InvenTreeSalesOrderAllocation.fromJson({}); + expect(allocation.hasShipment, isFalse); + expect(allocation.order, isNull); + expect(allocation.stockItem, isNull); + expect(allocation.part, isNull); + expect(allocation.shipment, isNull); + expect(allocation.location, isNull); + }); + }); + + group("Transfer Order:", () { + test("Status Codes", () async { + expect(TransferOrderStatus.name(10), equals("PENDING")); + expect(TransferOrderStatus.name(99), equals("")); + expect(TransferOrderStatus.isNameIn(30, ["COMPLETE"]), isTrue); + expect(TransferOrderStatus.isNameIn(99, ["COMPLETE"]), isFalse); + + expect(TransferOrderStatus.getStatusText(10), equals(L10().pending)); + expect(TransferOrderStatus.getStatusText(20), equals(L10().issued)); + expect(TransferOrderStatus.getStatusText(25), equals(L10().onHold)); + expect(TransferOrderStatus.getStatusText(30), equals(L10().complete)); + expect(TransferOrderStatus.getStatusText(40), equals(L10().cancelled)); + expect(TransferOrderStatus.getStatusText(99), equals(L10().unknown)); + }); + + test("Status", () async { + InvenTreeTransferOrder order(int status) => + InvenTreeTransferOrder.fromJson({"status": status}); + + final pending = order(TransferOrderStatus.PENDING); + expect(pending.isOpen, isTrue); + expect(pending.canIssue, isTrue); + expect(pending.canHold, isTrue); + expect(pending.canCompleteOrder, isFalse); + expect(pending.canCancel, isTrue); + + final issued = order(TransferOrderStatus.ISSUED); + expect(issued.canIssue, isFalse); + expect(issued.canHold, isTrue); + expect(issued.canCompleteOrder, isTrue); + + final onHold = order(TransferOrderStatus.ON_HOLD); + expect(onHold.canIssue, isTrue); + expect(onHold.canHold, isFalse); + expect(onHold.canCompleteOrder, isTrue); + + for (final status in [ + TransferOrderStatus.COMPLETE, + TransferOrderStatus.CANCELLED, + ]) { + expect(order(status).isOpen, isFalse); + expect(order(status).canCancel, isFalse); + expect(order(status).canCompleteOrder, isFalse); + } + }); + + test("Locations", () async { + var order = InvenTreeTransferOrder.fromJson({ + "take_from": 2, + "destination": 3, + "consume": true, + }); + + expect(order.sourceLocationId, equals(2)); + expect(order.destinationId, equals(3)); + expect(order.consume, isTrue); + + order = InvenTreeTransferOrder.fromJson({"take_from": null}); + expect(order.sourceLocationId, isNull); + expect(order.destinationId, isNull); + }); + + test("Line Item", () async { + var line = InvenTreeTransferOrderLineItem.fromJson({ + "quantity": 4, + "allocated": 4, + "transferred": 1, + "order_detail": {"reference": "TO-1"}, + }); + + expect(line.isComplete, isFalse); + expect(line.outstanding, equals(3)); + expect(line.progressRatio, equals(0.25)); + expect(line.progressString, equals("1 / 4")); + expect(line.transferOrder?.reference, equals("TO-1")); + + line = InvenTreeTransferOrderLineItem.fromJson({"quantity": 0}); + expect(line.isComplete, isTrue); + expect(line.progressRatio, equals(0)); + expect(line.transferOrder, isNull); + }); + + test("Allocation", () async { + var allocation = InvenTreeTransferOrderAllocation.fromJson({ + "quantity": 2, + "order_detail": {"reference": "TO-1"}, + "item_detail": {"serial": "123"}, + "part_detail": {"name": "Widget"}, + "location_detail": {"name": "Shelf"}, + }); + + expect(allocation.quantity, equals(2)); + expect(allocation.order?.reference, equals("TO-1")); + expect(allocation.stockItem?.serialNumber, equals("123")); + expect(allocation.part?.name, equals("Widget")); + expect(allocation.location?.name, equals("Shelf")); + + allocation = InvenTreeTransferOrderAllocation.fromJson({}); + expect(allocation.order, isNull); + expect(allocation.stockItem, isNull); + expect(allocation.part, isNull); + expect(allocation.location, isNull); + }); + }); + + group("Company:", () { + test("Company", () async { + var company = InvenTreeCompany.fromJson({}); + + expect(company.image, equals(InvenTreeAPI.staticImage)); + expect(company.thumbnail, equals(InvenTreeAPI.staticThumb)); + expect(company.active, isTrue); + expect(company.isSupplier, isFalse); + + company = InvenTreeCompany.fromJson({ + "image": "/media/c.png", + "is_supplier": true, + "is_customer": true, + "active": false, + }); + + expect(company.image, equals("/media/c.png")); + expect(company.thumbnail, equals("/media/c.png")); + expect(company.isSupplier, isTrue); + expect(company.isCustomer, isTrue); + expect(company.isManufacturer, isFalse); + expect(company.active, isFalse); + + company = InvenTreeCompany.fromJson({"thumbnail": "/media/c.thumb.png"}); + expect(company.image, equals("/media/c.thumb.png")); + }); + + test("Company Form Fields", () async { + expect(InvenTreeCompany().formFields().containsKey("active"), isFalse); + + InvenTreeAPI().serverInfo = {"apiVersion": 189}; + expect(InvenTreeCompany().formFields().containsKey("active"), isTrue); + }); + + test("Supplier Part", () async { + var sp = InvenTreeSupplierPart.fromJson({ + "SKU": "SKU-1", + "pack_size": "10", + "pack_quantity": "1 reel", + "manufacturer_detail": {"pk": 5, "name": "MFG", "thumbnail": "/m.png"}, + "supplier_detail": {"name": "ACME", "image": "/s.png"}, + "manufacturer_part_detail": {"MPN": "MPN-1"}, + "part_detail": {"name": "Widget", "thumbnail": "/p.png"}, + }); + + expect(sp.SKU, equals("SKU-1")); + expect(sp.manufacturerId, equals(5)); + expect(sp.manufacturerName, equals("MFG")); + expect(sp.manufacturerImage, equals("/m.png")); + expect(sp.supplierName, equals("ACME")); + expect(sp.supplierImage, equals("/s.png")); + expect(sp.MPN, equals("MPN-1")); + expect(sp.partName, equals("Widget")); + expect(sp.partImage, equals("/p.png")); + expect(sp.active, isTrue); + expect(sp.primary, isFalse); + + // Older API versions use "pack_size" + expect(sp.pack_quantity, equals("10")); + expect(sp.formFields().containsKey("pack_size"), isTrue); + expect(sp.formFields().containsKey("primary"), isFalse); + + InvenTreeAPI().serverInfo = {"apiVersion": 456}; + expect(sp.pack_quantity, equals("1 reel")); + expect(sp.formFields().containsKey("pack_quantity"), isTrue); + expect(sp.formFields().containsKey("primary"), isTrue); + + // Missing images + sp = InvenTreeSupplierPart.fromJson({}); + expect(sp.manufacturerImage, equals(InvenTreeAPI.staticThumb)); + expect(sp.supplierImage, equals(InvenTreeAPI.staticThumb)); + expect(sp.partImage, equals(InvenTreeAPI.staticThumb)); + }); + + test("Manufacturer Part", () async { + var mp = InvenTreeManufacturerPart.fromJson({ + "MPN": "MPN-1", + "manufacturer": 5, + "manufacturer_detail": { + "name": "MFG", + "description": "Manufacturer", + "image": "/m.png", + }, + "part_detail": {"name": "Widget", "IPN": "W-1"}, + }); + + expect(mp.MPN, equals("MPN-1")); + expect(mp.manufacturerId, equals(5)); + expect(mp.manufacturerName, equals("MFG")); + expect(mp.manufacturerDescription, equals("Manufacturer")); + expect(mp.manufacturerImage, equals("/m.png")); + expect(mp.partName, equals("Widget")); + expect(mp.partIPN, equals("W-1")); + expect(mp.partImage, equals(InvenTreeAPI.staticThumb)); + + mp = InvenTreeManufacturerPart.fromJson({}); + expect(mp.manufacturerImage, equals(InvenTreeAPI.staticThumb)); + }); + }); +} diff --git a/test/status_codes_test.dart b/test/status_codes_test.dart new file mode 100644 index 00000000..c3812b21 --- /dev/null +++ b/test/status_codes_test.dart @@ -0,0 +1,128 @@ +/* + * Unit tests for the InvenTreeStatusCode class + * + * Status code data is provided directly, rather than loaded from the server + */ + +import "package:flutter/material.dart"; +import "package:flutter_test/flutter_test.dart"; +import "package:inventree/app_colors.dart"; +import "package:inventree/inventree/status_codes.dart"; +import "package:one_context/one_context.dart"; + +InvenTreeStatusCode buildStatusCodes() { + final codes = InvenTreeStatusCode("stock/status/"); + + codes.data = { + "OK": {"key": 10, "name": "OK", "label": "OK", "color": "success"}, + "ATTENTION": { + "key": 50, + "name": "ATTENTION", + "label": "Attention needed", + "color": "WARNING", + }, + "DAMAGED": {"key": 55, "name": "DAMAGED", "label": "Damaged"}, + "DESTROYED": { + "key": 60, + "name": "DESTROYED", + "label": "Destroyed", + "color": "danger", + }, + // Malformed entries should be ignored + "INVALID": "not a map", + "STRING_KEY": {"key": "70", "name": "STRING_KEY", "label": "String"}, + }; + + return codes; +} + +void main() { + group("Status Codes:", () { + test("Choices", () async { + final codes = buildStatusCodes(); + + expect( + codes.choices, + equals([ + {"value": 10, "display_name": "OK"}, + {"value": 50, "display_name": "Attention needed"}, + {"value": 55, "display_name": "Damaged"}, + {"value": 60, "display_name": "Destroyed"}, + {"value": "70", "display_name": "String"}, + ]), + ); + + expect(InvenTreeStatusCode("x/").choices, isEmpty); + }); + + test("Entry", () async { + final codes = buildStatusCodes(); + + expect(codes.entry(50)["name"], equals("ATTENTION")); + expect(codes.entry(999), isEmpty); + + // Only integer keys are matched + expect(codes.entry(70), isEmpty); + }); + + test("Label", () async { + final codes = buildStatusCodes(); + + expect(codes.label(10), equals("OK")); + expect(codes.label(50), equals("Attention needed")); + + // Unknown status returns the code itself + expect(codes.label(999), equals("999")); + }); + + test("Name", () async { + final codes = buildStatusCodes(); + + expect(codes.name(60), equals("DESTROYED")); + expect(codes.name(999), equals("")); + + expect(codes.isNameIn(10, ["OK", "DAMAGED"]), isTrue); + expect(codes.isNameIn(60, ["OK", "DAMAGED"]), isFalse); + expect(codes.isNameIn(999, ["OK"]), isFalse); + }); + + // Theme-dependent colors require an app context + testWidgets("Color", (tester) async { + OneContext().key = GlobalKey(); + + await tester.pumpWidget( + MaterialApp( + builder: OneContext().builder, + navigatorKey: OneContext().key, + home: const SizedBox(), + ), + ); + + final codes = buildStatusCodes(); + + expect(codes.color(10), equals(COLOR_SUCCESS)); + expect(codes.color(50), equals(COLOR_WARNING)); + expect(codes.color(60), equals(COLOR_DANGER)); + + // Missing color, or unknown status + expect(codes.color(55), equals(COLOR_GRAY_LIGHT)); + expect(codes.color(999), equals(COLOR_GRAY_LIGHT)); + + final Map colors = { + "primary": COLOR_PROGRESS, + "secondary": COLOR_GRAY_LIGHT, + "dark": COLOR_TEXT, + "info": COLOR_PROGRESS, + "unknown": COLOR_GRAY_LIGHT, + }; + + colors.forEach((name, color) { + codes.data = { + "X": {"key": 1, "name": "X", "label": "X", "color": name}, + }; + + expect(codes.color(1), equals(color), reason: name); + }); + }); + }); +}