Skip to content

Commit

Permalink
{Core} Add run_az_cmd for internal az-related cmd execution (Azur…
Browse files Browse the repository at this point in the history
…e#29899)

* add run_az_cmd
  • Loading branch information
AllyW authored Oct 12, 2024
1 parent 11d4b92 commit 3a0ae3a
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
10 changes: 9 additions & 1 deletion src/azure-cli-core/azure/cli/core/tests/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
(get_file_json, truncate_text, shell_safe_json_parse, b64_to_hex, hash_string, random_string,
open_page_in_browser, can_launch_browser, handle_exception, ConfiguredDefaultSetter, send_raw_request,
should_disable_connection_verify, parse_proxy_resource_id, get_az_user_agent, get_az_rest_user_agent,
_get_parent_proc_name, is_wsl, run_cmd)
_get_parent_proc_name, is_wsl, run_cmd, run_az_cmd)
from azure.cli.core.mock import DummyCli


Expand Down Expand Up @@ -442,6 +442,14 @@ def test_run_cmd_arg_error(self):
with self.assertRaises(ArgumentUsageError):
run_cmd(cmd, check=True)

def test_run_az_cmd(self):
cmd = ["az", "version"]
output = run_az_cmd(cmd)
self.assertEqual(output.exit_code, 0, "unexpected exit_code when run az version")
self.assertEqual(output.error, None, "unexpected error when run az cmd")
self.assertIsInstance(output.result, dict, "unexpected cmd execution result")
self.assertIn("azure-cli-core", output.result, "unexpected cmd execution result")


class TestBase64ToHex(unittest.TestCase):

Expand Down
19 changes: 19 additions & 0 deletions src/azure-cli-core/azure/cli/core/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -1374,3 +1374,22 @@ def run_cmd(args, *, capture_output=False, timeout=None, check=False, encoding=N
import subprocess
return subprocess.run(args, capture_output=capture_output, timeout=timeout, check=check,
encoding=encoding, env=env)


def run_az_cmd(args, out_file=None):
"""
run_az_cmd would run az related cmds during command execution
:param args: cmd to be executed, array of string, like `["az", "version"]`, "az" is optional
:param out_file: The file to send output to. file-like object
:return: cmd execution result object, containing `result`, `error`, `exit_code`
"""
from azure.cli.core.azclierror import ArgumentUsageError
if not isinstance(args, list):
raise ArgumentUsageError("Invalid args. run_az_cmd args must be a list")
if args[0] == "az":
args = args[1:]

from azure.cli.core import get_default_cli
cli = get_default_cli()
cli.invoke(args, out_file=out_file)
return cli.result

0 comments on commit 3a0ae3a

Please sign in to comment.