Skip to content

Commit 1f0d091

Browse files
authored
admintpi: fix python 3.12 support, due to removed "distutils" (#373)
1 parent 8918181 commit 1f0d091

File tree

2 files changed

+43
-2
lines changed

2 files changed

+43
-2
lines changed

adminapi/dataset.py

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
Copyright (c) 2019 InnoGames GmbH
44
"""
55

6-
from distutils.util import strtobool
76
from ipaddress import IPv4Address, IPv4Network, IPv6Address, IPv6Network
87
from itertools import chain
98
from types import GeneratorType
@@ -461,7 +460,7 @@ def set(self, key, value):
461460
if isinstance(self[key], MultiAttr):
462461
self[key].add(value)
463462
elif type(self[key]) is bool:
464-
self[key] = bool(strtobool(value))
463+
self[key] = strtobool(value)
465464
elif type(self[key]) is int:
466465
self[key] = int(value)
467466
else:
@@ -595,3 +594,21 @@ def _format_attribute_value(value):
595594
if isinstance(value, dict):
596595
return _format_obj(value)
597596
return json_to_datatype(value)
597+
598+
599+
def strtobool(val) -> bool:
600+
"""
601+
Convert a string representation of truth to true or false.
602+
Acts the same as distutils.util.strtobool, which was removed in Python 3.12.
603+
604+
True values are 'y', 'yes', 't', 'true', 'on', and '1';
605+
false values are 'n', 'no', 'f', 'false', 'off', and '0'.
606+
Raises ValueError if 'val' is anything else.
607+
"""
608+
val = val.lower()
609+
if val in ('y', 'yes', 't', 'true', 'on', '1'):
610+
return True
611+
elif val in ('n', 'no', 'f', 'false', 'off', '0'):
612+
return False
613+
else:
614+
raise ValueError(f"invalid truth value {val}")

adminapi/tests/test_dataset.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import unittest
2+
3+
from adminapi.dataset import strtobool
4+
5+
6+
class TestStrtobool(unittest.TestCase):
7+
def test_true_values(self):
8+
true_values = ["y", "yes", "t", "true", "on", "1"]
9+
for value in true_values:
10+
with self.subTest(value=value):
11+
self.assertTrue(strtobool(value))
12+
13+
def test_false_values(self):
14+
false_values = ["n", "no", "f", "false", "off", "0"]
15+
for value in false_values:
16+
with self.subTest(value=value):
17+
self.assertFalse(strtobool(value))
18+
19+
def test_invalid_values(self):
20+
invalid_values = ["maybe", "2", "none", "", "Yess"]
21+
for value in invalid_values:
22+
with self.subTest(value=value):
23+
with self.assertRaises(ValueError):
24+
strtobool(value)

0 commit comments

Comments
 (0)