From 833dbbb28c5ab7290c8f630632bde0eea0be4fa0 Mon Sep 17 00:00:00 2001 From: Daniel Watkins Date: Fri, 7 Aug 2015 13:51:57 +0100 Subject: [PATCH] Fix running cloud-init with no arguments on Python 3. Change-Id: I4c1b27aa5a762fd2e9fbec7085c719060c60071c --- cloudinit/shell.py | 2 ++ cloudinit/tests/test_shell.py | 19 ++++++++++++++++++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/cloudinit/shell.py b/cloudinit/shell.py index 4b6ea9c6..481d6d13 100644 --- a/cloudinit/shell.py +++ b/cloudinit/shell.py @@ -46,6 +46,8 @@ def main(args=sys.argv): populate_parser(parser, COMMON_ARGS, SUBCOMMANDS) parsed = parser.parse_args(args[1:]) + if not hasattr(parsed, 'func'): + parser.error('too few arguments') parsed.func(parsed) return 0 diff --git a/cloudinit/tests/test_shell.py b/cloudinit/tests/test_shell.py index e7085840..4bd65f6c 100644 --- a/cloudinit/tests/test_shell.py +++ b/cloudinit/tests/test_shell.py @@ -3,8 +3,9 @@ # # vi: ts=4 expandtab -import cloudinit.shell as shell +import six +import cloudinit.shell as shell from cloudinit.tests import TestCase from cloudinit.tests.util import mock @@ -29,3 +30,19 @@ class TestMain(TestCase): shell.main(args=['cloud-init', 'version']) write_arg = mock_out_write.write.call_args[0][0] self.assertTrue(write_arg.startswith('cloud-init')) + + @mock.patch('cloudinit.shell.sys.stderr', new_callable=six.StringIO) + def test_no_arguments_shows_usage(self, stderr): + self.assertRaises(SystemExit, shell.main, args=['cloud-init']) + self.assertIn('usage: cloud-init', stderr.getvalue()) + + @mock.patch('cloudinit.shell.sys.stderr', mock.MagicMock()) + def test_no_arguments_exits_2(self): + exc = self.assertRaises(SystemExit, shell.main, args=['cloud-init']) + self.assertEqual(2, exc.code) + + @mock.patch('cloudinit.shell.sys.stderr', new_callable=six.StringIO) + def test_no_arguments_shows_error_message(self, stderr): + self.assertRaises(SystemExit, shell.main, args=['cloud-init']) + self.assertIn('cloud-init: error: too few arguments', + stderr.getvalue())