diff --git a/lib/pavilion/commands/view.py b/lib/pavilion/commands/view.py index fe1d5cd14..462f55733 100644 --- a/lib/pavilion/commands/view.py +++ b/lib/pavilion/commands/view.py @@ -2,6 +2,7 @@ import errno import pprint +import json from pavilion import output from pavilion import cmd_utils @@ -53,6 +54,9 @@ def _setup_arguments(self, parser): '-f', '--file', dest='files', action='append', default=[], help='Add tests listed in the given file, as per the "pav run" command', ) + parser.add_argument( + '-j', '--json', action='store_true', + help='Output the resolved test config as JSON') parser.add_argument( 'tests', action='store', nargs='*', help='The name of the test to view. Should be in the format ' @@ -96,5 +100,9 @@ def run(self, pav_cfg, args): return errno.EINVAL configs = {pt.config['name']: pt.config for pt in proto_tests} - pprint.pprint(configs, stream=self.outfile) # ext-print: ignore + + if args.json: + json.dump(configs, self.outfile, indent=2) + else: + pprint.pprint(configs, stream=self.outfile) # ext-print: ignore return 0 diff --git a/test/tests/view_cmd_tests.py b/test/tests/view_cmd_tests.py index 377706577..be8381b53 100644 --- a/test/tests/view_cmd_tests.py +++ b/test/tests/view_cmd_tests.py @@ -1,4 +1,6 @@ """Exercise the view command.""" +import json + from pavilion import arguments from pavilion import commands from pavilion.unittest import PavTestCase @@ -18,3 +20,31 @@ def test_view(self): ]) self.assertEqual(view_cmd.run(self.pav_cfg, args), 0) + + def test_view_json(self): + """Test that the --json flag outputs valid JSON.""" + + view_cmd = commands.get_command('view') + view_cmd.silence() + + arg_parser = arguments.get_parser() + + args = arg_parser.parse_args([ + 'view', '--json', 'hello_world' + ]) + + self.assertEqual(view_cmd.run(self.pav_cfg, args), 0) + + # Verify output is valid JSON + output_str = view_cmd.outfile.getvalue() + + try: + json_obj = json.loads(output_str) + except json.JSONDecodeError as e: + self.fail(f"Output is not valid JSON: {e}") + + print(json_obj) + + # Ensure it's a dict with expected structure (non-empty) + self.assertIsInstance(json_obj, dict) + self.assertTrue(json_obj != {})