Skip to content

Commit

Permalink
admintpi: fix python 3.12 support, due to removed "distutils" (#373)
Browse files Browse the repository at this point in the history
  • Loading branch information
brainexe authored Aug 29, 2024
1 parent 8918181 commit 1f0d091
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 2 deletions.
21 changes: 19 additions & 2 deletions adminapi/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
Copyright (c) 2019 InnoGames GmbH
"""

from distutils.util import strtobool
from ipaddress import IPv4Address, IPv4Network, IPv6Address, IPv6Network
from itertools import chain
from types import GeneratorType
Expand Down Expand Up @@ -461,7 +460,7 @@ def set(self, key, value):
if isinstance(self[key], MultiAttr):
self[key].add(value)
elif type(self[key]) is bool:
self[key] = bool(strtobool(value))
self[key] = strtobool(value)
elif type(self[key]) is int:
self[key] = int(value)
else:
Expand Down Expand Up @@ -595,3 +594,21 @@ def _format_attribute_value(value):
if isinstance(value, dict):
return _format_obj(value)
return json_to_datatype(value)


def strtobool(val) -> bool:
"""
Convert a string representation of truth to true or false.
Acts the same as distutils.util.strtobool, which was removed in Python 3.12.
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}")
24 changes: 24 additions & 0 deletions adminapi/tests/test_dataset.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import unittest

from adminapi.dataset import strtobool


class TestStrtobool(unittest.TestCase):
def test_true_values(self):
true_values = ["y", "yes", "t", "true", "on", "1"]
for value in true_values:
with self.subTest(value=value):
self.assertTrue(strtobool(value))

def test_false_values(self):
false_values = ["n", "no", "f", "false", "off", "0"]
for value in false_values:
with self.subTest(value=value):
self.assertFalse(strtobool(value))

def test_invalid_values(self):
invalid_values = ["maybe", "2", "none", "", "Yess"]
for value in invalid_values:
with self.subTest(value=value):
with self.assertRaises(ValueError):
strtobool(value)

0 comments on commit 1f0d091

Please sign in to comment.