Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions HISTORY.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@
Release History
===============

Unreleased
++++++++++

* Preserve default integer and string values in command output (#215)

0.14.0
++++++

Expand Down
6 changes: 6 additions & 0 deletions knack/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down
10 changes: 10 additions & 0 deletions tests/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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)
Expand Down