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

parent e2f5d561
...@@ -26,13 +26,13 @@ ...@@ -26,13 +26,13 @@
############################################################################## ##############################################################################
import os import os
import slapos.util import slapos.util
from slapos.util import string_to_boolean
import tempfile import tempfile
import unittest import unittest
import shutil import shutil
from pwd import getpwnam from pwd import getpwnam
class TestUtil(unittest.TestCase):
class TestMkdirP(unittest.TestCase):
""" """
Tests methods available in the slapos.util module. Tests methods available in the slapos.util module.
""" """
...@@ -107,5 +107,26 @@ class TestMkdirP(unittest.TestCase): ...@@ -107,5 +107,26 @@ class TestMkdirP(unittest.TestCase):
shutil.rmtree(root_slaptest) 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__': if __name__ == '__main__':
unittest.main() unittest.main()
...@@ -43,3 +43,24 @@ def parse_certificate_key_pair(html): ...@@ -43,3 +43,24 @@ def parse_certificate_key_pair(html):
key = html[k_start:k_end] key = html[k_start:k_end]
return certificate, key 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