From fcb3d0f96f83fe18fe04e984fd4440b3b78c64b7 Mon Sep 17 00:00:00 2001 From: Dan Prince Date: Tue, 16 Dec 2014 09:42:24 -0500 Subject: [PATCH] Output useful JSON data If you use os-apply-config to slice out a JSON blob on the command line you'll get back a string formatted dump of a python dictionary (or list). Ideally we would print out proper JSON text so that other tooling (jq, etc) can post process things in a useful manner. This patch updates apply_config so that if an output key is detected to be a dict or a list it is printed to stdout in a JSON format. Change-Id: Ibc8b21cd6922b8664ca71e9e6009c8573ea9d107 --- os_apply_config/apply_config.py | 5 ++++- os_apply_config/tests/test_apply_config.py | 18 ++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/os_apply_config/apply_config.py b/os_apply_config/apply_config.py index 5c28494..ab69b94 100755 --- a/os_apply_config/apply_config.py +++ b/os_apply_config/apply_config.py @@ -102,7 +102,10 @@ def print_key( raise exc.ConfigException( 'key %s does not exist in %s' % (key, config_path)) value_types.ensure_type(str(config), type_name) - print(str(config)) + if isinstance(config, (dict, list)): + print(json.dumps(config)) + else: + print(str(config)) def write_file(path, obj): diff --git a/os_apply_config/tests/test_apply_config.py b/os_apply_config/tests/test_apply_config.py index c5a03cb..87b7b2e 100644 --- a/os_apply_config/tests/test_apply_config.py +++ b/os_apply_config/tests/test_apply_config.py @@ -112,6 +112,24 @@ class TestRunOSConfigApplier(testtools.TestCase): self.stdout.read().strip()) self.assertEqual('', self.logger.output) + def test_print_key_json_dict(self): + self.assertEqual(0, apply_config.main( + ['os-apply-config.py', '--metadata', self.path, '--key', + 'database', '--type', 'raw'])) + self.stdout.seek(0) + self.assertEqual(CONFIG['database'], + json.loads(self.stdout.read().strip())) + self.assertEqual('', self.logger.output) + + def test_print_key_json_list(self): + self.assertEqual(0, apply_config.main( + ['os-apply-config.py', '--metadata', self.path, '--key', + 'l', '--type', 'raw'])) + self.stdout.seek(0) + self.assertEqual(CONFIG['l'], + json.loads(self.stdout.read().strip())) + self.assertEqual('', self.logger.output) + def test_print_non_string_key(self): self.assertEqual(0, apply_config.main( ['os-apply-config.py', '--metadata', self.path, '--key',