Skip to content
Open
Changes from all 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
42 changes: 42 additions & 0 deletions uuid_generator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import uuid

def generate_uuid() -> str:
"""
Generate a universally unique identifier (UUID) using a cryptographically secure random number generator.

Returns:
str: A UUID following RFC 4122 version 4 format, consisting of 36 characters with hyphens.
"""
return str(uuid.uuid4())

if __name__ == "__main__":
# Test the generate_uuid function
import random
import string

def random_string(length: int) -> str:
"""Generate a random string of given length."""
letters = string.ascii_lowercase
return "".join(random.choice(letters) for _ in range(length))

def generate_and_validate_uuid() -> None:
"""Generate and validate a UUID."""
generated_uuid = generate_uuid()

# Verify the generated UUID is a valid 36-character string
assert len(generated_uuid) == 36, "UUID should be a 36-character string"

# Confirm the generated UUID follows RFC 4122 version 4 format
assert generated_uuid.count("-") == 4, "UUID should have correct hyphen placement"

# Ensure two consecutive UUID generations produce different values
second_generated_uuid = generate_uuid()
assert generated_uuid != second_generated_uuid, "Two consecutive UUID generations should produce different values"

# Validate the UUID contains only hexadecimal characters and hyphens
for char in generated_uuid:
assert char in "-0123456789abcdef", "UUID should contain only hexadecimal characters and hyphens"

# Test the generate_uuid function multiple times
for _ in range(10):
generate_and_validate_uuid()