Add utility to check if some string value can be 'casted' to true or false.

parent e2f5d561
......@@ -26,13 +26,13 @@
##############################################################################
import os
import slapos.util
from slapos.util import string_to_boolean
import tempfile
import unittest
import shutil
from pwd import getpwnam
class TestMkdirP(unittest.TestCase):
class TestUtil(unittest.TestCase):
"""
Tests methods available in the slapos.util module.
"""
......@@ -107,5 +107,26 @@ class TestMkdirP(unittest.TestCase):
shutil.rmtree(root_slaptest)
def test_string_to_boolean_with_true_values(self):
"""
Check that mkdir_p doesn't raise if directory already exist.
"""
for value in ['true', 'True', 'TRUE']:
self.assertTrue(string_to_boolean(value))
def test_string_to_boolean_with_false_values(self):
"""
Check that mkdir_p doesn't raise if directory already exist.
"""
for value in ['false', 'False', 'False']:
self.assertFalse(string_to_boolean(value))
def test_string_to_boolean_with_incorrect_values(self):
"""
Check that mkdir_p doesn't raise if directory already exist.
"""
for value in [True, False, 1, '1', 't', 'tru', 'truelle', 'f', 'fals', 'falsey']:
self.assertRaises(ValueError, string_to_boolean, value)
if __name__ == '__main__':
unittest.main()
......@@ -43,3 +43,24 @@ def parse_certificate_key_pair(html):
key = html[k_start:k_end]
return certificate, key
def string_to_boolean(string):
"""
Return True if the value of the "string" parameter can be parsed as True.
Return False if the value of the "string" parameter can be parsed as False.
Otherwise, Raise.
The parser is completely arbitrary, see code for actual implementation.
"""
if not isinstance(string, str) and not isinstance(string, unicode):
raise ValueError('Given value is not a string.')
acceptable_true_values = ['true']
acceptable_false_values = ['false']
string = string.lower()
if string in acceptable_true_values:
return True
if string in acceptable_false_values:
return False
else:
raise ValueError('%s is neither True nor False.' % string)
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment