diff --git a/uuid_generator.py b/uuid_generator.py new file mode 100644 index 0000000000..f3d7e3417c --- /dev/null +++ b/uuid_generator.py @@ -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() \ No newline at end of file