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 <[email protected]>
This commit is contained in:
MrBlakeandClaude Opus 5.5 committed 2026-11-18 12:43:08 +01:00
1 parent 4dd01b82e3
commit cf1cafb632
5 files changed
+134 -1

No files matched your search

+9
View File
@@ -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.
+35
View File
@@ -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):
+4 -1
View File
@@ -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)
@@ -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()},
@@ -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())