diff --git a/app/grandchallenge/core/utils/__init__.py b/app/grandchallenge/core/utils/__init__.py index b85db19373..9b02929426 100644 --- a/app/grandchallenge/core/utils/__init__.py +++ b/app/grandchallenge/core/utils/__init__.py @@ -1,4 +1,3 @@ -from distutils.util import strtobool as strtobool_i from functools import wraps @@ -16,6 +15,17 @@ def wrapper(*args, **kwargs): return wrapper -def strtobool(val) -> bool: - """Return disutils.util.strtobool as a boolean.""" - return bool(strtobool_i(val)) +def strtobool(val): + """Convert a string representation of truth to true or false. + + True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values + are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if + 'val' is anything else. + """ + val = val.lower() + if val in ("y", "yes", "t", "true", "on", "1"): + return True + elif val in ("n", "no", "f", "false", "off", "0"): + return False + else: + raise ValueError(f"invalid truth value {val}") diff --git a/app/tests/core_tests/test_utils.py b/app/tests/core_tests/test_utils.py new file mode 100644 index 0000000000..309db7383f --- /dev/null +++ b/app/tests/core_tests/test_utils.py @@ -0,0 +1,39 @@ +import pytest + +from grandchallenge.core.utils import strtobool + + +@pytest.mark.parametrize( + "val, result", + [ + ("y", True), + ("Y", True), + ("yes", True), + ("Yes", True), + ("true", True), + ("True", True), + ("t", True), + ("T", True), + ("on", True), + ("On", True), + ("1", True), + ("n", False), + ("N", False), + ("no", False), + ("No", False), + ("false", False), + ("False", False), + ("f", False), + ("F", False), + ("off", False), + ("Off", False), + ("0", False), + ], +) +def test_strtobool(val, result): + assert strtobool(val) is result + + +def test_strtobool_exception(): + with pytest.raises(ValueError): + strtobool("foobar")