mirror of https://github.com/flaggo/pydu.git
add boolean to string
This commit is contained in:
parent
36c9dc85bb
commit
0ada2fa96c
|
@ -141,3 +141,26 @@ def sort(s, reverse=False):
|
|||
If reverse is True, sorting given string by descending order.
|
||||
"""
|
||||
return ''.join(sorted(s, reverse=reverse))
|
||||
|
||||
|
||||
def boolean(obj):
|
||||
"""
|
||||
Convert obj to a boolean value.
|
||||
If obj is string, obj will converted by case-insensitive way:
|
||||
* convert `yes`, `y`, `on`, `true`, `t`, `1` to True
|
||||
* convert `no`, `n`, `off`, `false`, `f`, `0` to False
|
||||
* raising TypeError if other values passed
|
||||
If obj is non-string, obj will converted by bool(obj).
|
||||
"""
|
||||
|
||||
try:
|
||||
text = obj.strip().lower()
|
||||
except AttributeError:
|
||||
return bool(obj)
|
||||
|
||||
if text in ('yes', 'y', 'on', 'true', 't', '1'):
|
||||
return True
|
||||
elif text in ('no', 'n', 'off', 'false', 'f', '0'):
|
||||
return False
|
||||
else:
|
||||
raise ValueError("Unable to convert {!r} to a boolean value.".format(text))
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
# coding: utf-8
|
||||
import pytest
|
||||
from pydu.string import (safeencode, safeunicode, strips, lstrips, rstrips,
|
||||
common_prefix, common_suffix, sort)
|
||||
common_prefix, common_suffix, sort, boolean)
|
||||
|
||||
|
||||
def test_safeencode():
|
||||
|
@ -53,3 +54,26 @@ def test_common_suffix():
|
|||
def test_sort():
|
||||
assert sort('acb21') == '12abc'
|
||||
assert sort('abc21', reverse=True) == 'cba21'
|
||||
|
||||
|
||||
class TestBoolean:
|
||||
def test_accepted_text(self):
|
||||
for text in ('yes', 'y', 'on', 'true', 't', '1'):
|
||||
assert boolean(text)
|
||||
assert boolean(text.upper())
|
||||
|
||||
for text in ('no', 'n', 'off', 'false', 'f', '0'):
|
||||
assert not boolean(text)
|
||||
assert not boolean(text.upper())
|
||||
|
||||
@pytest.mark.parametrize('text', ('a', 'b'))
|
||||
def test_unaccepted_text(self, text):
|
||||
with pytest.raises(ValueError):
|
||||
boolean(text)
|
||||
|
||||
def test_nonstring(self):
|
||||
for obj in (10, [1], {1: 1}):
|
||||
assert boolean(obj)
|
||||
|
||||
for obj in (0, [], {}):
|
||||
assert not boolean(obj)
|
||||
|
|
Loading…
Reference in New Issue