Commits

Panagiotis Mavrogiorgos committed 1c273cf

Added support for BooleanColumn.
fixes #1
addresses #1

Comments (0)

Files changed (2)

csvmodels/columns.py

 
         if self.are_constraints_satisfied(value):
             return value
+
+
+class BooleanColumn(BaseColumn):
+    """
+    A ``bool`` column within a CSV file.
+
+    Each column value is compared with the specified
+    ``true_value``/``false_value``. If a match is found a ``True``/``False``
+    object is created respectively. If neither value is matched, then  a
+    ``ValueError`` is raised.
+
+    It extends ``BaseColumn``. It supports all the arguments that
+    ``BaseColumn`` supports plus the following ones:
+
+    :param string true_value:
+    :param string false_value:
+
+    """
+    def __init__(self, required=True, default=None, none_value=None, format=None,
+                 true_value="Yes", false_value="No"):
+        super().__init__(required=required, default=default,
+                         none_value=none_value, format=format)
+
+        self.true_value = true_value
+        self.false_value = false_value
+
+    def to_python(self, value):
+        """
+        Convert column value to a Float. If the conversion fails it raises a
+        ``ValueError``.
+
+        :param str value:
+            Column value
+
+        """
+        # If the value matches the specified ``none_value`` then we return
+        # the none_value
+        if self.none_value is not None:
+            if value == self.none_value:
+                return None
+
+        if value == self.true_value:
+            return True
+        elif value == self.false_value:
+            return False
+        else:
+            msg = "Couldn't convert value to Bool. " + _ERROR_MESSAGE
+            raise ValueError(msg.format(self.name, self.cls._linenumber, str(value)))

tests_csvmodels/test_columns.py

         self.assertEqual(return_value, output)
 
 
+class BooleanColumnTests(ColumnTestCase):
+    def setUp(self):
+        self.create_column_object(BooleanColumn)
+
+        self.empty_string = ""
+        self.valid_true_value = "Yes"
+        self.valid_false_value = "No"
+        self.valid_true_output = True
+        self.valid_false_output = False
+        self.invalid_input = "asda"
+        self.default = True
+
+    def test_valid_true_value(self):
+        """ Valid true_input must return True. """
+        return_value = self.column.to_python(self.valid_true_value)
+        self.assertTrue(return_value)
+
+    def test_valid_false_value(self):
+        """ Valid false_value must return False. """
+        return_value = self.column.to_python(self.valid_false_value)
+        self.assertFalse(return_value)
+
+    def test_invalid_input(self):
+        self.assertRaises(ValueError, self.column.to_python, self.invalid_input)
+
+
 if __name__ == '__main__':
     unittest.main()