Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@

"""Models for Overlays app."""

import re

from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ValidationError
Expand Down Expand Up @@ -340,16 +342,40 @@ class Meta:
verbose_name_plural = "InfiniBand PKeys"
unique_together = ["pkey", "overlay"]

_PKEY_RE = re.compile(r"\A0[xX][0-9a-fA-F]{1,4}\Z")

def __str__(self):
"""Stringify instance."""
return f"{self.name} ({self.pkey})"

@staticmethod
def normalize_pkey(value):
"""Return pkey as '0x' + 4 lowercase hex digits, or the input unchanged if it doesn't match the expected format."""
if not isinstance(value, str):
return value
stripped = value.strip()
if not InfiniBandPKey._PKEY_RE.match(stripped):
return stripped
return f"0x{int(stripped, 16):04x}"

def clean_fields(self, exclude=None):
"""Normalize pkey before field validators run so '0X1' and whitespace are accepted."""
if isinstance(self.pkey, str):
self.pkey = self.normalize_pkey(self.pkey)
super().clean_fields(exclude=exclude)

def clean(self):
"""Validate PKey can only be associated with IB PKey overlays."""
"""Validate PKey associations and normalize the pkey value."""
super().clean()
self.pkey = self.normalize_pkey(self.pkey)
if self.overlay and self.overlay.isolation_type != IsolationTypeChoices.IB_PKEY:
raise ValidationError({"overlay": "InfiniBand PKeys can only be associated with IB PKey overlays."})

def save(self, *args, **kwargs):
"""Normalize pkey before persisting."""
self.pkey = self.normalize_pkey(self.pkey)
super().save(*args, **kwargs)
Comment thread
susanhooks marked this conversation as resolved.


@extras_features("graphql", "statuses", "custom_fields")
class InfiniBandMKey(PrimaryModel):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,50 @@ def test_pkey_format_validator_rejects_invalid_values(self):
with self.assertRaises(ValidationError, msg=f"Expected ValidationError for pkey={invalid!r}"):
pkey.full_clean()

def test_normalize_pkey_helper(self):
"""normalize_pkey() produces '0x' + 4 lowercase hex digits for all valid inputs."""
cases = {
"0x1": "0x0001",
"0x01": "0x0001",
"0x001": "0x0001",
"0x0001": "0x0001",
"0X100": "0x0100",
"0xFFFF": "0xffff",
"0xffff": "0xffff",
" 0x100 ": "0x0100",
}
for raw, expected in cases.items():
self.assertEqual(
InfiniBandPKey.normalize_pkey(raw),
expected,
msg=f"normalize_pkey({raw!r})",
)

def test_normalize_pkey_passes_through_invalid_input(self):
"""normalize_pkey() leaves invalid input alone so the field validator can reject it."""
for raw in ("", "not-a-pkey", "8001", "0x1234567", None, 0x100):
self.assertEqual(
InfiniBandPKey.normalize_pkey(raw),
raw if not isinstance(raw, str) else raw.strip(),
msg=f"normalize_pkey({raw!r})",
)

def test_save_normalizes_pkey(self):
"""Raw ORM save() normalizes pkey."""
pkey = InfiniBandPKey.objects.create(
pkey="0x100",
name="Raw ORM PKey",
status=self.status,
)
pkey.refresh_from_db()
self.assertEqual(pkey.pkey, "0x0100")

def test_full_clean_normalizes_pkey(self):
"""full_clean() normalizes pkey."""
pkey = InfiniBandPKey(pkey="0x1", name="Form PKey", status=self.status)
pkey.full_clean()
self.assertEqual(pkey.pkey, "0x0001")


class InfiniBandMKeyModelTest(TestCase):
"""Test cases for InfiniBandMKey model."""
Expand Down