Skip to content

Commit

Permalink
review: Use regex in rfc1123 helper
Browse files Browse the repository at this point in the history
  • Loading branch information
kimwnasptd committed Jan 21, 2025
1 parent 1a1d177 commit ffe50c6
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 14 deletions.
19 changes: 7 additions & 12 deletions src/profiles_management/helpers/k8s.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Generic helpers for manipulating K8s objects, via lightkube."""

import logging
import re

import tenacity
from lightkube import Client
Expand Down Expand Up @@ -68,21 +69,15 @@ def to_rfc1123_compliant(name: str) -> str:
Returns:
The RFC 1123-compliant string.
"""
compliant_str = name.lower()
compliant_str = "".join(char if char.isalnum() else "-" for char in compliant_str)
if len(name) == 0:
raise ValueError("Can't convert to valid RFC1123 an empty string.")

# remove starting non-alphanum chars
i = 0
while not compliant_str[i].isalnum():
i += 1
compliant_str = compliant_str[i:63]
compliant_str = name.lower()
compliant_str = re.sub(r"[^a-z0-9-]", "-", compliant_str)

# remove ending non-alphanum chars
j = len(compliant_str)
while not compliant_str[j - 1].isalnum():
j -= 1
compliant_str = compliant_str.lstrip("-").rstrip("-")

return compliant_str[:j]
return compliant_str[:63]


@tenacity.retry(stop=tenacity.stop_after_delay(300), wait=tenacity.wait_fixed(5), reraise=True)
Expand Down
10 changes: 8 additions & 2 deletions tests/unit/profiles-management/helpers/test_k8s.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,20 @@ def test_no_annotations():
assert get_annotations(resource) == {}


def test_non_alphanum_to_hyphen():
def test_rfc1123_non_alphanum_to_hyphen():
name = "[email protected]"

assert to_rfc1123_compliant(name) == "kimonas-canonical-com"


def test_more_than_63_char_name():
def test_rfc1123_more_than_63_char_name():
name = "I-had-to-think-of-a-reeeally-long-string-to-use-for-the-test-which-was-tough"

assert len(name) > 63
assert len(to_rfc1123_compliant(name)) == 63


def test_rfc1123_strip_starting_and_trailing_dashes():
name = "-=shouldn't have trailing dashes!"

assert to_rfc1123_compliant(name) == "shouldn-t-have-trailing-dashes"

0 comments on commit ffe50c6

Please sign in to comment.