Skip to content

Commit

Permalink
added new utils class osbot_aws.utils.AWS_Sanitization with method st…
Browse files Browse the repository at this point in the history
…r_to_valid_s3_bucket_name
  • Loading branch information
DinisCruz committed Sep 11, 2024
1 parent 4fc61cb commit 0d3c5f6
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
12 changes: 12 additions & 0 deletions osbot_aws/utils/AWS_Sanitization.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import re


def str_to_valid_s3_bucket_name(value):

s3_bucket_name = re.sub(r'[^a-z0-9-]', '', value.lower()).strip('.-') # Replace invalid characters with a hyphen and ensure the name does not start or end with invalid characters

if s3_bucket_name.endswith('-'):
s3_bucket_name = s3_bucket_name[:-1] # Remove trailing hyphen if present
if not s3_bucket_name:
raise ValueError(f"[osbot_aws.utils.AWS_Sanitization] in str_to_valid_s3_bucket_name, could not create a valid name from: {value}")
return s3_bucket_name
22 changes: 22 additions & 0 deletions tests/unit/utils/test_AWS_Sanitization.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
from unittest import TestCase

from osbot_aws.utils.AWS_Sanitization import str_to_valid_s3_bucket_name


class test_AWS_Sanitization(TestCase):
def test_str_to_valid_s3_bucket_name(self):
assert str_to_valid_s3_bucket_name('valid-bucket-name' ) == 'valid-bucket-name' # Use case 1: Valid bucket name remains the same
assert str_to_valid_s3_bucket_name('ValidBucketName' ) == 'validbucketname' # Use case 2: Uppercase characters converted to lowercase
assert str_to_valid_s3_bucket_name('Invalid_Bucket@Name!' ) == 'invalidbucketname' # Use case 3: Invalid characters removed
assert str_to_valid_s3_bucket_name('.invalid.bucket.name-') == 'invalidbucketname' # Use case 4: Leading and trailing dots or hyphens removed
assert str_to_valid_s3_bucket_name('invalid..bucket--name') == 'invalidbucket--name' # Use case 5: Dots removed but double hyphen remains

try: # Use case 6: Empty string should raise ValueError
str_to_valid_s3_bucket_name('')
except ValueError as e:
assert str(e) == "[osbot_aws.utils.AWS_Sanitization] in str_to_valid_s3_bucket_name, could not create a valid name from: " # Verify that the correct error message is raised

try: # Use case 7: Name with only invalid characters should raise ValueError
str_to_valid_s3_bucket_name('@#$%^&')
except ValueError as e:
assert str(e) == "[osbot_aws.utils.AWS_Sanitization] in str_to_valid_s3_bucket_name, could not create a valid name from: @#$%^&" # Verify that the correct error message is raised

0 comments on commit 0d3c5f6

Please sign in to comment.