Utility method for converting string to bool.
This commit is contained in:
15
common/djangoapps/util/string_utils.py
Normal file
15
common/djangoapps/util/string_utils.py
Normal file
@@ -0,0 +1,15 @@
|
||||
"""
|
||||
Utilities for string manipulation.
|
||||
"""
|
||||
|
||||
import ast
|
||||
|
||||
def str_to_bool(str):
|
||||
"""
|
||||
Converts "true" (case-insensitive) to the boolean True.
|
||||
Everything else will return False.
|
||||
"""
|
||||
try:
|
||||
return ast.literal_eval(str.title())
|
||||
except:
|
||||
return False
|
||||
26
common/djangoapps/util/tests/test_string_utils.py
Normal file
26
common/djangoapps/util/tests/test_string_utils.py
Normal file
@@ -0,0 +1,26 @@
|
||||
"""
|
||||
Tests for string_utils.py
|
||||
"""
|
||||
|
||||
from django.test import TestCase
|
||||
from util.string_utils import str_to_bool
|
||||
|
||||
class StringUtilsTest(TestCase):
|
||||
"""
|
||||
Tests for str_to_bool.
|
||||
"""
|
||||
def test_str_to_bool_true(self):
|
||||
self.assertTrue(str_to_bool('True'))
|
||||
self.assertTrue(str_to_bool('true'))
|
||||
self.assertTrue(str_to_bool('trUe'))
|
||||
|
||||
def test_str_to_bool_false(self):
|
||||
self.assertFalse(str_to_bool('Tru'))
|
||||
self.assertFalse(str_to_bool('False'))
|
||||
self.assertFalse(str_to_bool('false'))
|
||||
self.assertFalse(str_to_bool(''))
|
||||
self.assertFalse(str_to_bool(None))
|
||||
self.assertFalse(str_to_bool('anything'))
|
||||
self.assertFalse(str_to_bool([]))
|
||||
self.assertFalse(str_to_bool({}))
|
||||
self.assertFalse(str_to_bool(1))
|
||||
Reference in New Issue
Block a user