Skip to content

Commit

Permalink
Add helpers.to_bool function
Browse files Browse the repository at this point in the history
  • Loading branch information
HardNorth committed Sep 4, 2024
1 parent ce737ff commit 6ed02a2
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 2 deletions.
16 changes: 16 additions & 0 deletions reportportal_client/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -477,3 +477,19 @@ def guess_content_type_from_bytes(data: Union[bytes, bytearray, List[int]]) -> s
return 'application/pdf'

return 'application/octet-stream'


def to_bool(value: Optional[Any]) -> Optional[bool]:
"""Convert value of any type to boolean or raise ValueError.
:param value: value to convert
:return: boolean value
:raises ValueError: if value is not boolean
"""
if value is None:
return None
if value in {'TRUE', 'True', 'true', '1', 'Y', 'y', 1, True}:
return True
if value in {'FALSE', 'False', 'false', '0', 'N', 'n', 0, False}:
return False
raise ValueError(f'Invalid boolean value {value}.')
36 changes: 34 additions & 2 deletions tests/test_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,7 @@
import pytest

from reportportal_client.helpers import (
gen_attributes,
get_launch_sys_attrs,
gen_attributes, get_launch_sys_attrs, to_bool,
verify_value_length, ATTRIBUTE_LENGTH_LIMIT, TRUNCATE_REPLACEMENT, guess_content_type_from_bytes, is_binary
)

Expand Down Expand Up @@ -134,3 +133,36 @@ def test_binary_content_type_detection(file, expected_type):
with open(file, 'rb') as f:
content = f.read()
assert guess_content_type_from_bytes(content) == expected_type


@pytest.mark.parametrize(
'value, expected_result',
[
('TRUE', True),
('True', True),
('true', True),
('Y', True),
('y', True),
(True, True),
(1, True),
('1', True),
('FALSE', False),
('False', False),
('false', False),
('N', False),
('n', False),
(False, False),
(0, False),
('0', False),
(None, None),
]
)
def test_to_bool(value, expected_result):
"""Test for validate to_bool() function."""
assert to_bool(value) == expected_result


def test_to_bool_invalid_value():
"""Test for validate to_bool() function exception case."""
with pytest.raises(ValueError):
to_bool('invalid_value')

0 comments on commit 6ed02a2

Please sign in to comment.