diff --git a/python-stdlib/uuid/manifest.py b/python-stdlib/uuid/manifest.py new file mode 100644 index 000000000..e59bdf2c0 --- /dev/null +++ b/python-stdlib/uuid/manifest.py @@ -0,0 +1,3 @@ +metadata(version="0.1.0") + +module("uuid.py") diff --git a/python-stdlib/uuid/test_uuid.py b/python-stdlib/uuid/test_uuid.py new file mode 100644 index 000000000..138dd3360 --- /dev/null +++ b/python-stdlib/uuid/test_uuid.py @@ -0,0 +1,29 @@ +import unittest +import uuid + + +class TestUUID(unittest.TestCase): + def test_unique(self): + u1 = uuid.uuid4() + u2 = uuid.uuid4() + self.assertNotEqual(u1.hex, u2.hex) + self.assertNotEqual(str(u1), str(u2)) + + def test_len(self): + u = uuid.uuid4() + self.assertEqual(len(str(u)), 36) + self.assertEqual(len(u.hex), 32) + + def test_repr(self): + u = str(repr(uuid.uuid4())) + self.assertTrue(u.startswith("")) + + def test_constructor(self): + u1 = uuid.uuid4() + u2 = uuid.UUID(bytes.fromhex(u1.hex)) + self.assertEqual(u1.hex, u2.hex) + + +if __name__ == "__main__": + unittest.main() diff --git a/python-stdlib/uuid/uuid.py b/python-stdlib/uuid/uuid.py new file mode 100644 index 000000000..9790923c3 --- /dev/null +++ b/python-stdlib/uuid/uuid.py @@ -0,0 +1,27 @@ +import os + + +class UUID: + def __init__(self, bytes): + if len(bytes) != 16: + raise ValueError("bytes arg must be 16 bytes long") + self._bytes = bytes + + @property + def hex(self): + return self._bytes.hex() + + def __str__(self): + h = self.hex + return "-".join((h[0:8], h[8:12], h[12:16], h[16:20], h[20:32])) + + def __repr__(self): + return "" % str(self) + + +def uuid4(): + """Generates a random UUID compliant to RFC 4122 pg.14""" + random = bytearray(os.urandom(16)) + random[6] = (random[6] & 0x0F) | 0x40 + random[8] = (random[8] & 0x3F) | 0x80 + return UUID(bytes=random) diff --git a/tools/ci.sh b/tools/ci.sh index e2b6919be..1cb813432 100755 --- a/tools/ci.sh +++ b/tools/ci.sh @@ -104,6 +104,7 @@ function ci_package_tests_run { python-stdlib/time \ python-stdlib/unittest/tests \ python-stdlib/unittest-discover/tests \ + python-stdlib/uuid \ ; do (cd $path && "${MICROPYTHON}" -m unittest) if [ $? -ne 0 ]; then false; return; fi