From 0ada2fa96cd5f9858e49f23920fb4c9941968636 Mon Sep 17 00:00:00 2001 From: Prodesire Date: Mon, 8 Jan 2018 21:11:25 +0800 Subject: [PATCH] add boolean to string --- pydu/string.py | 23 +++++++++++++++++++++++ tests/test_string.py | 26 +++++++++++++++++++++++++- 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/pydu/string.py b/pydu/string.py index 351c77b..cba548f 100644 --- a/pydu/string.py +++ b/pydu/string.py @@ -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)) diff --git a/tests/test_string.py b/tests/test_string.py index 41b3cff..726b269 100644 --- a/tests/test_string.py +++ b/tests/test_string.py @@ -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)