Add id_generator_test.
authorScott Gasch <[email protected]>
Sat, 29 Oct 2022 21:37:43 +0000 (14:37 -0700)
committerScott Gasch <[email protected]>
Sat, 29 Oct 2022 21:37:43 +0000 (14:37 -0700)
src/pyutils/id_generator.py
tests/id_generator_test.py [new file with mode: 0755]

index c4885c81fd3534945ba4ab98a81a81c47c6729c7..108c230f09a5be67f3ff819cf384408f74296f53 100644 (file)
@@ -5,6 +5,11 @@
 """
 A helper class for generating thread safe monotonically increasing
 id numbers.
+
+.. note::
+
+    This code is thread safe but not process safe; for use only
+    within one python process.
 """
 
 import itertools
@@ -47,7 +52,7 @@ def get(name: str, *, start=0) -> int:
     return x
 
 
-if __name__ == '__main__':
+if __name__ == "__main__":
     import doctest
 
     doctest.testmod()
diff --git a/tests/id_generator_test.py b/tests/id_generator_test.py
new file mode 100755 (executable)
index 0000000..da718c7
--- /dev/null
@@ -0,0 +1,41 @@
+#!/usr/bin/env python3
+
+# © Copyright 2021-2022, Scott Gasch
+
+"""Make sure id_generator is thread safe."""
+
+import unittest
+
+from pyutils import id_generator
+from pyutils import unittest_utils as uu
+from pyutils.parallelize import parallelize as par
+from pyutils.parallelize import smart_future, thread_utils
+
+
+class TestIdGenerator(unittest.TestCase):
+    @par.parallelize(method=par.Method.THREAD)
+    def get_some_ids(self):
+        name = thread_utils.current_thread_id()
+        print(f"Hello from {name}")
+        results = []
+        for _ in range(10000):
+            results.append(id_generator.get("TestSequence"))
+        return results
+
+    def test_is_safe(self):
+        results = []
+        for i in range(10):
+            results.append(self.get_some_ids())
+
+        smart_future.wait_all(results)
+        already_seen = set()
+        for result in results:
+            for identifier in result:
+                if identifier in already_seen:
+                    self.fail(f"Saw the id {identifier} more than once?!")
+                else:
+                    already_seen.add(identifier)
+
+
+if __name__ == "__main__":
+    unittest.main()