Fix AnsibleModule.human_to_bytes (#85259)

* Fix AnsibleModule.human_to_bytes.

* Add unit test.

* Fix wrong example in docstring.

* Forgot tests without keyword.

Signed-off-by: Abhijeet Kasurde <Akasurde@redhat.com>

* Apply review suggestions.

* Add type hints.

Co-authored-by: Matt Clay <matt@mystile.com>

---------

Signed-off-by: Abhijeet Kasurde <Akasurde@redhat.com>
Co-authored-by: Matt Clay <matt@mystile.com>
This commit is contained in:
Felix Fontein
2025-11-11 20:50:36 +01:00
committed by GitHub
parent 222f786f23
commit 13a7393cfe
4 changed files with 42 additions and 4 deletions

View File

@@ -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)."

View File

@@ -2149,14 +2149,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

View File

@@ -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.

View File

@@ -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)