Skip to content

Commit 6ed02a2

Browse files
committed
Add helpers.to_bool function
1 parent ce737ff commit 6ed02a2

File tree

2 files changed

+50
-2
lines changed

2 files changed

+50
-2
lines changed

reportportal_client/helpers.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -477,3 +477,19 @@ def guess_content_type_from_bytes(data: Union[bytes, bytearray, List[int]]) -> s
477477
return 'application/pdf'
478478

479479
return 'application/octet-stream'
480+
481+
482+
def to_bool(value: Optional[Any]) -> Optional[bool]:
483+
"""Convert value of any type to boolean or raise ValueError.
484+
485+
:param value: value to convert
486+
:return: boolean value
487+
:raises ValueError: if value is not boolean
488+
"""
489+
if value is None:
490+
return None
491+
if value in {'TRUE', 'True', 'true', '1', 'Y', 'y', 1, True}:
492+
return True
493+
if value in {'FALSE', 'False', 'false', '0', 'N', 'n', 0, False}:
494+
return False
495+
raise ValueError(f'Invalid boolean value {value}.')

tests/test_helpers.py

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,7 @@
1919
import pytest
2020

2121
from reportportal_client.helpers import (
22-
gen_attributes,
23-
get_launch_sys_attrs,
22+
gen_attributes, get_launch_sys_attrs, to_bool,
2423
verify_value_length, ATTRIBUTE_LENGTH_LIMIT, TRUNCATE_REPLACEMENT, guess_content_type_from_bytes, is_binary
2524
)
2625

@@ -134,3 +133,36 @@ def test_binary_content_type_detection(file, expected_type):
134133
with open(file, 'rb') as f:
135134
content = f.read()
136135
assert guess_content_type_from_bytes(content) == expected_type
136+
137+
138+
@pytest.mark.parametrize(
139+
'value, expected_result',
140+
[
141+
('TRUE', True),
142+
('True', True),
143+
('true', True),
144+
('Y', True),
145+
('y', True),
146+
(True, True),
147+
(1, True),
148+
('1', True),
149+
('FALSE', False),
150+
('False', False),
151+
('false', False),
152+
('N', False),
153+
('n', False),
154+
(False, False),
155+
(0, False),
156+
('0', False),
157+
(None, None),
158+
]
159+
)
160+
def test_to_bool(value, expected_result):
161+
"""Test for validate to_bool() function."""
162+
assert to_bool(value) == expected_result
163+
164+
165+
def test_to_bool_invalid_value():
166+
"""Test for validate to_bool() function exception case."""
167+
with pytest.raises(ValueError):
168+
to_bool('invalid_value')

0 commit comments

Comments
 (0)