changeset 50:4b20694b8a16

add module + test for uniqueness
author Jeff Hammel <k0scist@gmail.com>
date Sun, 17 Sep 2017 14:28:36 -0700
parents 111997fa04d1
children e1eb45c4763e
files tests/test_unique.py tvii/unique.py
diffstat 2 files changed, 51 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/tests/test_unique.py	Sun Sep 17 14:28:36 2017 -0700
@@ -0,0 +1,30 @@
+#!/usr/bin/env python
+
+import os
+import unittest
+from tvii.unique import unique
+from tvii.unique import NotUnique
+
+class TestUnique(unittest.TestCase):
+
+    def test_positive(self):
+        """ensure the unique functionality works as expected"""
+
+        # true positive
+        a_unique_value = [7] * 7
+        assert unique(a_unique_value) == 7
+
+    def test_negative(self):
+        """what if a set is not unique?"""
+
+        data = [1,2,3,4]
+        e = None
+        try:
+            unique(data)
+        except NotUnique as e:
+            pass
+        assert e is not None
+        assert isinstance(e, NotUnique)
+
+if __name__ == '__main__':
+    unittest.main()
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/tvii/unique.py	Sun Sep 17 14:28:36 2017 -0700
@@ -0,0 +1,21 @@
+class NotUnique(Exception):
+    """exception for a set of items that are not unique"""
+
+    msg_tmpl = "Not unique: {items}"
+
+    def __init__(self, multiples):
+        self.multiples = multiples
+        message = self.msg_tmpl.format(items=', '.join([str(item)
+                                                        for item in multiples]))
+        Exception.__init__(self, message)
+
+
+def unique(items):
+    """asserts that a `items` is a set of one"""
+
+    types = set(items)
+    unique = types.pop()
+    if types:
+        types.add(unique)
+        raise NotUnique(types)
+    return unique