1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
import os
import logging
import sys
import unittest
from unittest import mock
from knack.arguments import ArgumentsContext
from knack.commands import CLICommandsLoader, CommandGroup
from tests.util import DummyCLI, redirect_io
# a dummy callback for arg-parse
def load_params(_):
pass
def list_foo(my_param):
print(str(my_param), end='')
class TestCommandWithConfiguredDefaults(unittest.TestCase):
@classmethod
def setUpClass(cls):
# Ensure initialization has occurred correctly
logging.basicConfig(level=logging.DEBUG)
@classmethod
def tearDownClass(cls):
logging.shutdown()
def _set_up_command_table(self, required):
class TestCommandsLoader(CLICommandsLoader):
def load_command_table(self, args):
super().load_command_table(args)
with CommandGroup(self, 'foo', '{}#{{}}'.format(__name__)) as g:
g.command('list', 'list_foo')
return self.command_table
def load_arguments(self, command):
with ArgumentsContext(self, 'foo') as c:
c.argument('my_param', options_list='--my-param',
configured_default='param', required=required)
super().load_arguments(command)
self.cli_ctx = DummyCLI(commands_loader_cls=TestCommandsLoader)
@mock.patch.dict(os.environ, {'CLI_DEFAULTS_PARAM': 'myVal'})
@redirect_io
def test_apply_configured_defaults_on_required_arg(self):
self._set_up_command_table(required=True)
self.cli_ctx.invoke('foo list'.split())
actual = self.io.getvalue()
expected = 'myVal'
self.assertEqual(expected, actual)
@redirect_io
def test_no_configured_default_on_required_arg(self):
self._set_up_command_table(required=True)
with self.assertRaises(SystemExit):
self.cli_ctx.invoke('foo list'.split())
actual = self.io.getvalue()
expected = 'required: --my-param'
if sys.version_info[0] == 2:
expected = 'argument --my-param is required'
self.assertEqual(expected in actual, True)
@mock.patch.dict(os.environ, {'CLI_DEFAULTS_PARAM': 'myVal'})
@redirect_io
def test_apply_configured_defaults_on_optional_arg(self):
self._set_up_command_table(required=False)
self.cli_ctx.invoke('foo list'.split())
actual = self.io.getvalue()
expected = 'myVal'
self.assertEqual(expected, actual)
if __name__ == '__main__':
unittest.main()
|