Fix AnsibleModule.human_to_bytes (#85259) (#86173)

* Fix AnsibleModule.human_to_bytes.

* Add unit test.

* Fix wrong example in docstring.

* Forgot tests without keyword.



* Apply review suggestions.

* Add type hints.



---------



(cherry picked from commit 13a7393cfe)

Signed-off-by: Abhijeet Kasurde <Akasurde@redhat.com>
Co-authored-by: Matt Clay <matt@mystile.com>
pull/86256/head
Felix Fontein 1 week ago committed by GitHub
parent 8de1d8ea3f
commit 79a243940f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -0,0 +1,2 @@
bugfixes:
- "Fix ``AnsibleModule.human_to_bytes()``, which was never adjusted after the standalone ``human_to_bytes()`` got a new parameter ``default_unit`` (https://github.com/ansible/ansible/pull/85259)."

@ -2153,14 +2153,16 @@ class AnsibleModule(object):
with open(filename, 'a') as fh:
fh.write(str)
def bytes_to_human(self, size):
@staticmethod
def bytes_to_human(size: int) -> str:
return bytes_to_human(size)
# for backwards compatibility
pretty_bytes = bytes_to_human
def human_to_bytes(self, number, isbits=False):
return human_to_bytes(number, isbits)
@staticmethod
def human_to_bytes(number: str, isbits: bool = False) -> int:
return human_to_bytes(number, isbits=isbits)
#
# Backwards compat

@ -60,7 +60,7 @@ def human_to_bytes(number, default_unit=None, isbits=False):
if 'Mb'/'Kb'/... is passed, the ValueError will be rased.
When isbits is True, converts bits from a human-readable format to integer.
example: human_to_bytes('1Mb', isbits=True) returns 8388608 (int) -
example: human_to_bytes('1Mb', isbits=True) returns 1048576 (int) -
string bits representation was passed and return as a number or bits.
The function expects 'b' (lowercase) as a bit identifier, e.g. 'Mb'/'Kb'/etc.
if 'MB'/'KB'/... is passed, the ValueError will be rased.

@ -0,0 +1,34 @@
# -*- coding: utf-8 -*-
# Copyright: (c) 2025 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
import pytest
from ansible.module_utils.basic import AnsibleModule
@pytest.mark.parametrize('value, isbits, expected', [
("4KB", False, 4096),
("4KB", None, 4096),
("4Kb", True, 4096),
])
def test_validator_function(value: str, isbits: bool | None, expected: int) -> None:
assert AnsibleModule.human_to_bytes(value, isbits=isbits) == expected
@pytest.mark.parametrize('value, expected', [
("4KB", 4096),
])
def test_validator_function_default_isbits(value: str, expected: int) -> None:
assert AnsibleModule.human_to_bytes(value) == expected
@pytest.mark.parametrize('value, isbits', [
("4Kb", False),
("4KB", True),
])
def test_validator_functions(value: str, isbits: bool) -> None:
with pytest.raises(ValueError):
AnsibleModule.human_to_bytes(value, isbits=isbits)
Loading…
Cancel
Save