From cf1cafb632654b96e347513dac377e72b2da8d44 Mon Sep 17 00:00:00 2001 From: Louis Date: Wed, 18 Nov 2026 12:43:08 +0100 Subject: [PATCH] feat: tenant-aware netbox-inventory assets Assets without a tenant take the tenant of the device, module, inventory item or rack they are assigned to, both in clean() and before save. The plugin's assign, reassign and "create hardware from asset" views save assets without a tenant field and failed with mandatory tenancy before. Asset forms are also pre-filled from an assigned module or inventory item. Existing tenants are never changed. Co-Authored-By: Claude Opus 5.5 --- README.md | 9 ++++ netbox_utilities/tenant_autofill.py | 35 +++++++++++++++ netbox_utilities/tenant_validation.py | 5 ++- .../tests/test_tenant_autofill.py | 45 +++++++++++++++++++ .../tests/test_tenant_validation.py | 41 +++++++++++++++++ 5 files changed, 134 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 5e3eeb5..d06e113 100644 --- a/README.md +++ b/README.md @@ -783,6 +783,15 @@ cable ends are evaluated; the tenant is only set if it is unambiguous. If an automatically set tenant is saved unchanged, the browser asks for an explicit confirmation. +Assets of the optional [netbox-inventory](https://github.com/ArnesSI/netbox-inventory) +plugin are tenant-aware as well: the asset forms are pre-filled like core +objects (also from an assigned module or inventory item), and an asset without +a tenant takes the tenant of the device, module, inventory item or rack it is +assigned to when it is saved. This keeps the plugin's *assign*, *reassign* and +*create hardware from asset* views working with mandatory tenancy, which save +the asset without a tenant field. An asset that is in stock and has no +assigned hardware still needs a tenant. + `tenant_required = False` disables the feature permanently and takes precedence over the UI setting. diff --git a/netbox_utilities/tenant_autofill.py b/netbox_utilities/tenant_autofill.py index 7332bba..3edf454 100644 --- a/netbox_utilities/tenant_autofill.py +++ b/netbox_utilities/tenant_autofill.py @@ -16,8 +16,14 @@ PARENT_RELATIONS = ( "l2vpn", "wireless_lan", "power_panel", + # netbox-inventory assets: modules and inventory items belong to a device + "module", + "inventoryitem", ) +# Hardware a netbox-inventory asset can be assigned to, in the plugin's order. +ASSET_HARDWARE_RELATIONS = ("device", "module", "inventoryitem", "rack") + def tenant_id_from_object(obj, depth=0): if obj is None or depth > 3: @@ -133,6 +139,35 @@ def _cable_form_tenant_result(form): return None, False +def _is_inventory_asset(instance): + meta = getattr(instance, "_meta", None) + return bool( + meta and getattr(meta, "app_label", None) == "netbox_inventory" and getattr(meta, "model_name", None) == "asset" + ) + + +def apply_asset_instance_tenant(instance): + """ + Give a netbox-inventory asset without tenant the tenant of its assigned hardware. + + The plugin's "assign", "reassign" and "create hardware from asset" views save the + asset without a tenant field; with mandatory tenancy they would fail although the + tenant of the device, module, inventory item or rack is known. Existing tenants are + never overwritten. + """ + if not _is_inventory_asset(instance) or getattr(instance, "tenant_id", None): + return None + for relation in ASSET_HARDWARE_RELATIONS: + try: + hardware = getattr(instance, relation, None) + except (AttributeError, ObjectDoesNotExist, ValueError): + continue + if tenant_id := tenant_id_from_object(hardware): + instance.tenant_id = tenant_id + return tenant_id + return None + + def apply_cable_instance_tenant(instance): """Assign a cable's tenant when all derivable terminations agree.""" if not _is_cable(instance) or getattr(instance, "tenant_id", None): diff --git a/netbox_utilities/tenant_validation.py b/netbox_utilities/tenant_validation.py index 9ad1109..bcec2b5 100644 --- a/netbox_utilities/tenant_validation.py +++ b/netbox_utilities/tenant_validation.py @@ -7,7 +7,7 @@ from django.forms.models import BaseModelForm from tenancy.models import Tenant from .runtime import tenant_required -from .tenant_autofill import apply_cable_instance_tenant, apply_tenant_autofill +from .tenant_autofill import apply_asset_instance_tenant, apply_cable_instance_tenant, apply_tenant_autofill VALIDATION_MESSAGE = "Für dieses Objekt muss ein Mandant angegeben werden." @@ -37,6 +37,7 @@ def _install_model_clean_validation(model): @wraps(original_clean) def tenant_aware_clean(instance, *args, **kwargs): apply_cable_instance_tenant(instance) + apply_asset_instance_tenant(instance) result = original_clean(instance, *args, **kwargs) validate_tenant_assignment(instance) return result @@ -65,6 +66,8 @@ def _install_form_validation(): def _enforce_before_save(sender, instance, raw=False, **kwargs): if not raw: + # netbox-inventory saves assets in several views without calling clean() + apply_asset_instance_tenant(instance) validate_tenant_assignment(instance) diff --git a/netbox_utilities/tests/test_tenant_autofill.py b/netbox_utilities/tests/test_tenant_autofill.py index 5830277..22b8eb8 100644 --- a/netbox_utilities/tests/test_tenant_autofill.py +++ b/netbox_utilities/tests/test_tenant_autofill.py @@ -6,6 +6,7 @@ from django.test import SimpleTestCase from tenancy.models import TenantGroup from netbox_utilities.tenant_autofill import ( + apply_asset_instance_tenant, apply_cable_instance_tenant, apply_tenant_autofill, infer_tenant_id, @@ -44,6 +45,20 @@ class FakeCable(FakeObject): self.b_terminations = b_terminations or [] +class FakeAssetMeta(FakeMeta): + app_label = "netbox_inventory" + model_name = "asset" + + +class FakeAsset(FakeObject): + """netbox-inventory asset: tenant plus one of device, module, inventoryitem or rack.""" + + def __init__(self, *, tenant_id=None, device=None, module=None, inventoryitem=None, rack=None): + super().__init__(tenant_id=tenant_id) + self._meta = FakeAssetMeta("tenant", "device", "module", "inventoryitem", "rack") + self.device, self.module, self.inventoryitem, self.rack = device, module, inventoryitem, rack + + class FakeQuerySet: def __init__(self, model): self.model = model @@ -99,6 +114,36 @@ class TenantAutofillTest(SimpleTestCase): self.assertEqual(apply_cable_instance_tenant(cable), 42) self.assertEqual(cable.tenant_id, 42) + def test_asset_takes_tenant_of_assigned_device(self): + asset = FakeAsset(device=FakeObject(tenant_id=42)) + + self.assertEqual(apply_asset_instance_tenant(asset), 42) + self.assertEqual(asset.tenant_id, 42) + + def test_asset_takes_tenant_of_module_device_inventory_item_and_rack(self): + device = FakeObject(tenant_id=7) + for asset in ( + FakeAsset(module=FakeObject(device=device)), + FakeAsset(inventoryitem=FakeObject(device=device)), + FakeAsset(rack=FakeObject(tenant_id=7)), + ): + self.assertEqual(apply_asset_instance_tenant(asset), 7) + + def test_asset_keeps_existing_tenant_and_stays_empty_without_hardware(self): + asset = FakeAsset(tenant_id=5, device=FakeObject(tenant_id=42)) + self.assertIsNone(apply_asset_instance_tenant(asset)) + self.assertEqual(asset.tenant_id, 5) + + stored = FakeAsset() + self.assertIsNone(apply_asset_instance_tenant(stored)) + self.assertIsNone(stored.tenant_id) + + def test_other_models_are_not_assigned_a_tenant_from_their_device(self): + interface_like = FakeObject(device=FakeObject(tenant_id=42)) + + self.assertIsNone(apply_asset_instance_tenant(interface_like)) + self.assertIsNone(interface_like.tenant_id) + def test_prefers_cable_terminations_over_global_scope(self): form = SimpleNamespace( fields={"tenant": forms.IntegerField()}, diff --git a/netbox_utilities/tests/test_tenant_validation.py b/netbox_utilities/tests/test_tenant_validation.py index 9d492c5..99f73c5 100644 --- a/netbox_utilities/tests/test_tenant_validation.py +++ b/netbox_utilities/tests/test_tenant_validation.py @@ -48,3 +48,44 @@ class TenantValidationTest(SimpleTestCase): @patch("netbox_utilities.tenant_validation.tenant_required", return_value=False) def test_allows_missing_tenant_when_disabled(self, _tenant_required): validate_tenant_assignment(TenantModel()) + + +class FakeAssetMeta(FakeMeta): + app_label = "netbox_inventory" + model_name = "asset" + + def get_fields(self): + return [SimpleNamespace(name=name) for name in ("tenant", "device", "module", "inventoryitem", "rack")] + + +class FakeAsset(TenantModel): + _meta = FakeAssetMeta() + + def __init__(self, tenant_id=None, device=None): + super().__init__(tenant_id) + self.device, self.module, self.inventoryitem, self.rack = device, None, None, None + + +class FakeDevice: + _meta = SimpleNamespace(get_fields=lambda: [SimpleNamespace(name="tenant")]) + + def __init__(self, tenant_id): + self.tenant_id = tenant_id + + +class InventoryAssetTenantTest(SimpleTestCase): + @patch("netbox_utilities.tenant_validation.tenant_required", return_value=True) + def test_reassigned_asset_takes_device_tenant_before_save(self, _tenant_required): + from netbox_utilities.tenant_validation import _enforce_before_save + + asset = FakeAsset(device=FakeDevice(42)) + _enforce_before_save(FakeAsset, asset) + + self.assertEqual(asset.tenant_id, 42) + + @patch("netbox_utilities.tenant_validation.tenant_required", return_value=True) + def test_unassigned_asset_without_tenant_is_still_rejected(self, _tenant_required): + from netbox_utilities.tenant_validation import _enforce_before_save + + with self.assertRaises(ValidationError): + _enforce_before_save(FakeAsset, FakeAsset())