diff --git a/HISTORY.rst b/HISTORY.rst index 0c92d21..055e130 100644 --- a/HISTORY.rst +++ b/HISTORY.rst @@ -3,6 +3,11 @@ Release History =============== +Unreleased +++++++++++ + +* Preserve default integer and string values in command output (#215) + 0.14.0 ++++++ diff --git a/knack/util.py b/knack/util.py index 68e5076..77f47ae 100644 --- a/knack/util.py +++ b/knack/util.py @@ -9,6 +9,8 @@ from datetime import date, time, datetime, timedelta from enum import Enum +from .validators import DefaultInt, DefaultStr + NO_COLOR_VARIABLE_NAME = 'KNACK_NO_COLOR' # Override these values to customize the status message. @@ -135,6 +137,10 @@ def todict(obj, post_processor=None): # pylint: disable=too-many-return-stateme Convert an object to a dictionary. Use 'post_processor(original_obj, dictionary)' to update the dictionary in the process """ + if isinstance(obj, DefaultInt): + return int(obj) + if isinstance(obj, DefaultStr): + return str(obj) if isinstance(obj, dict): result = {k: todict(v, post_processor) for (k, v) in obj.items()} return post_processor(obj, result) if post_processor else result diff --git a/tests/test_util.py b/tests/test_util.py index 3a41435..7c453ad 100644 --- a/tests/test_util.py +++ b/tests/test_util.py @@ -9,6 +9,7 @@ from unittest import mock from knack.util import todict, to_snake_case, is_modern_terminal +from knack.validators import DefaultInt, DefaultStr class TestUtils(unittest.TestCase): @@ -19,6 +20,15 @@ def test_application_todict_none(self): expected = None self.assertEqual(actual, expected) + def test_application_todict_default_scalars(self): + for value, expected in [(DefaultInt(100), 100), (DefaultStr('hello'), 'hello')]: + with self.subTest(value=value): + actual = todict(value) + self.assertEqual(actual, expected) + self.assertIs(type(actual), type(expected)) + self.assertEqual(todict({'value': [value]}), {'value': [expected]}) + self.assertTrue(value.is_default) + def test_application_todict_dict_empty(self): the_input = {} actual = todict(the_input)