Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit d56bc41

Browse files
committed
cmdmod: formatting and tests
1 parent 44fd6da commit d56bc41

File tree

7 files changed

+65
-94
lines changed

7 files changed

+65
-94
lines changed

salt/modules/cmdmod.py

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -418,7 +418,10 @@ def _run(
418418

419419
# Prepare the command to be executed
420420
win_shell_lower = win_shell.lower()
421-
if any(win_shell_lower.endswith(word) for word in ["powershell.exe", "pwsh.exe"]):
421+
if any(
422+
win_shell_lower.endswith(word)
423+
for word in ["powershell.exe", "pwsh.exe"]
424+
):
422425
cmd = _prep_powershell_cmd(win_shell, cmd, encoded_cmd)
423426
elif any(win_shell_lower.endswith(word) for word in ["cmd.exe"]):
424427
cmd = salt.platform.win.prepend_cmd(win_shell, cmd)
@@ -2927,9 +2930,9 @@ def _cleanup_tempfile(path):
29272930

29282931
if salt.utils.platform.is_windows() and not shell:
29292932
extension_map = {
2930-
'.bat': 'cmd',
2931-
'.cmd': 'cmd',
2932-
'.ps1': 'powershell',
2933+
".bat": "cmd",
2934+
".cmd": "cmd",
2935+
".ps1": "powershell",
29332936
}
29342937
shell = extension_map.get(ext)
29352938

@@ -2984,15 +2987,10 @@ def _cleanup_tempfile(path):
29842987
os.chmod(path, 320)
29852988
os.chown(path, __salt__["file.user_to_uid"](runas), -1)
29862989

2987-
if salt.utils.platform.is_windows():
2988-
cmd_path = path
2989-
else:
2990-
cmd_path = _cmd_quote(path)
2991-
29922990
if isinstance(args, (list, tuple)):
2993-
new_cmd = [cmd_path, *args] if args else [cmd_path]
2991+
new_cmd = [path, *args] if args else [path]
29942992
else:
2995-
new_cmd = [cmd_path, str(args)] if args else [cmd_path]
2993+
new_cmd = [path, str(args)] if args else [path]
29962994

29972995
ret = {}
29982996
try:
@@ -3020,7 +3018,7 @@ def _cleanup_tempfile(path):
30203018
success_stderr=success_stderr,
30213019
**kwargs,
30223020
)
3023-
except Exception as exc:
3021+
except (CommandExecutionError, SaltInvocationError) as exc:
30243022
log.error(
30253023
"cmd.script: Unable to run script '%s': %s",
30263024
new_cmd,
@@ -4163,7 +4161,7 @@ def powershell(
41634161
# caught in a try/catch block. For example, the `Get-WmiObject` command will
41644162
# often return a "Non Terminating Error". To fix this, make sure
41654163
# `-ErrorAction Stop` is set in the powershell command
4166-
cmd = "try { " + cmd + ' } catch { Write-Error $_ }'
4164+
cmd = "try { " + cmd + " } catch { Write-Error $_ }"
41674165

41684166
if encode_cmd:
41694167
# Convert the cmd to UTF-16LE without a BOM and base64 encode.

tests/integration/modules/test_cmdmod.py

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,9 @@ def test_stdout(self):
113113
cmd.run_stdout
114114
"""
115115
self.assertEqual(
116-
self.run_function("cmd.run_stdout", ['echo "cheese"'], shell=SHELL).rstrip(),
116+
self.run_function(
117+
"cmd.run_stdout", ['echo "cheese"'], shell=SHELL
118+
).rstrip(),
117119
"cheese" if not salt.utils.platform.is_windows() else '"cheese"',
118120
)
119121

@@ -413,7 +415,10 @@ def test_quotes_runas(self):
413415
cmd = """echo 'SELECT * FROM foo WHERE bar="baz"' """
414416
expected_result = 'SELECT * FROM foo WHERE bar="baz"'
415417
result = self.run_function(
416-
"cmd.run_all", [cmd], python_shell=True, runas=RUNTIME_VARS.RUNNING_TESTS_USER
418+
"cmd.run_all",
419+
[cmd],
420+
python_shell=True,
421+
runas=RUNTIME_VARS.RUNNING_TESTS_USER,
417422
)
418423
errmsg = f"The command returned: {result}"
419424
self.assertEqual(result["retcode"], 0, errmsg)
@@ -432,7 +437,10 @@ def test_avoid_injecting_shell_code_as_root(self):
432437

433438
root_id = self.run_function("cmd.run_stdout", [cmd], python_shell=True)
434439
runas_root_id = self.run_function(
435-
"cmd.run_stdout", [cmd], python_shell=True, runas=RUNTIME_VARS.RUNNING_TESTS_USER
440+
"cmd.run_stdout",
441+
[cmd],
442+
python_shell=True,
443+
runas=RUNTIME_VARS.RUNNING_TESTS_USER,
436444
)
437445
with self._ensure_user_exists(self.runas_usr):
438446
user_id = self.run_function(
@@ -576,21 +584,30 @@ def test_hide_output(self):
576584
self.assertEqual(out, "")
577585

578586
# cmd.run_stdout
579-
out = self.run_function("cmd.run_stdout", ls_command, shell=shell, hide_output=True)
587+
out = self.run_function(
588+
"cmd.run_stdout", ls_command, shell=shell, hide_output=True
589+
)
580590
self.assertEqual(out, "")
581591

582592
# cmd.run_stderr
583-
out = self.run_function("cmd.shell", error_command, shell=shell, hide_output=True)
584-
self.assertIn("Unable to run command", out)
593+
out = self.run_function(
594+
"cmd.shell", ls_command, shell=shell, hide_output=True
595+
)
596+
self.assertEqual(out, "")
585597

586598
# cmd.run_all (command should have produced stdout)
587-
out = self.run_function("cmd.run_all", ls_command, shell=shell, hide_output=True)
599+
out = self.run_function(
600+
"cmd.run_all", ls_command, shell=shell, hide_output=True
601+
)
588602
self.assertEqual(out["stdout"], "")
589603
self.assertEqual(out["stderr"], "")
590604

591605
# cmd.run_all (command should not have produced output)
592-
out = self.run_function("cmd.run_all", error_command, shell=SHELL, hide_output=True)
593-
self.assertIn("Unable to run command", out)
606+
out = self.run_function(
607+
"cmd.run_all", error_command, shell=SHELL, hide_output=True
608+
)
609+
self.assertEqual(out["stdout"], "")
610+
self.assertEqual(out["stderr"], "")
594611

595612
@pytest.mark.slow_test
596613
def test_cmd_run_whoami(self):

tests/pytests/functional/modules/cmd/test_powershell.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ def test_args_runas(issue_56195):
8888
(["Write-Output", "Foo"], "Foo", False),
8989
('Write-Output "Encoded Foo"', "Encoded Foo", True),
9090
(["Write-Output", '"Encoded Foo"'], "Encoded Foo", True),
91-
('$a="Plain";$b=\' Foo\';Write-Output ${a}${b}', "Plain Foo", False),
91+
("$a=\"Plain\";$b=' Foo';Write-Output ${a}${b}", "Plain Foo", False),
9292
("(Write-Output Foo)", "Foo", False),
9393
("& Write-Output Foo", "Foo", False),
9494
],
@@ -108,7 +108,7 @@ def test_powershell(shell, cmd, expected, encode_cmd):
108108
(["Write-Output", "Foo"], "Foo", False),
109109
('Write-Output "Encoded Foo"', "Encoded Foo", True),
110110
(["Write-Output", '"Encoded Foo"'], "Encoded Foo", True),
111-
('$a="Plain";$b=\' Foo\';Write-Output ${a}${b}', "Plain Foo", False),
111+
("$a=\"Plain\";$b=' Foo';Write-Output ${a}${b}", "Plain Foo", False),
112112
("(Write-Output Foo)", "Foo", False),
113113
("& Write-Output Foo", "Foo", False),
114114
],

tests/pytests/functional/modules/cmd/test_run_win.py

Lines changed: 9 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ def test_cmd_exitcode(modules, state_tree, exit_code, return_code, result):
2727
ret = modules.state.single(
2828
"cmd.run",
2929
name=f"exit {exit_code}",
30-
shell='cmd',
30+
shell="cmd",
3131
success_retcodes=[2, 44, 300],
3232
)
3333
assert ret.result is result
@@ -47,7 +47,7 @@ def test_cmd_exitcode_runas(
4747
ret = modules.state.single(
4848
"cmd.run",
4949
name=f"exit {exit_code}",
50-
shel='cmd',
50+
shell="cmd",
5151
success_retcodes=[2, 44, 300],
5252
runas=account.username,
5353
password=account.password,
@@ -60,8 +60,9 @@ def test_cmd_exitcode_runas(
6060
"command, expected",
6161
[
6262
("echo foo", "foo"),
63+
("cmd /c echo foo", "foo"),
6364
("whoami && echo foo", "foo"),
64-
('echo "foo \'bar\'"', '"foo \'bar\'"'),
65+
("echo \"foo 'bar'\"", "\"foo 'bar'\""),
6566
('echo|set /p="foo" & echo|set /p="bar"', "foobar"),
6667
('''echo "&<>[]|{}^=;!'+,`~ "''', '''"&<>[]|{}^=;!'+,`~ "'''),
6768
],
@@ -70,16 +71,17 @@ def test_cmd_builtins(modules, command, expected):
7071
"""
7172
Test builtin cmd.exe commands
7273
"""
73-
result = modules.cmd.run(command, shell='cmd')
74+
result = modules.cmd.run(command, shell="cmd")
7475
assert expected in result
7576

7677

7778
@pytest.mark.parametrize(
7879
"command, expected",
7980
[
8081
("echo foo", "foo"),
82+
("cmd /c echo foo", "foo"),
8183
("whoami && echo foo", "foo"),
82-
('echo "foo \'bar\'"', '"foo \'bar\'"'),
84+
("echo \"foo 'bar'\"", "\"foo 'bar'\""),
8385
('echo|set /p="foo" & echo|set /p="bar"', "foobar"),
8486
('''echo "&<>[]|{}^=;!'+,`~ "''', '''"&<>[]|{}^=;!'+,`~ "'''),
8587
],
@@ -89,7 +91,7 @@ def test_cmd_builtins_runas(modules, account, command, expected):
8991
Test builtin cmd.exe commands with runas
9092
"""
9193
result = modules.cmd.run(
92-
cmd=command, shell='cmd', runas=account.username, password=account.password
94+
cmd=command, shell="cmd", runas=account.username, password=account.password
9395
)
9496
assert expected in result
9597

@@ -142,25 +144,7 @@ def test_cmd_env(modules, command, env, expected):
142144
"""
143145
Test cmd.run with environment variables
144146
"""
145-
result = modules.cmd.run_all(command, shell='cmd', env=env)
146-
assert isinstance(result["pid"], int)
147-
assert result["retcode"] == 0
148-
assert result["stdout"] == expected
149-
assert result["stderr"] == ""
150-
151-
@pytest.mark.parametrize(
152-
"command, env, expected",
153-
[
154-
("echo %a%%b%", {"a": "foo", "b": "bar"}, "foobar"),
155-
],
156-
)
157-
def test_cmd_env_runas(modules, account, command, env, expected):
158-
"""
159-
Test cmd.run with environment variables and runas
160-
"""
161-
result = modules.cmd.run_all(
162-
command, shell='cmd', env=env, runas=account.username, password=account.password
163-
)
147+
result = modules.cmd.run_all(command, shell="cmd", env=env)
164148
assert isinstance(result["pid"], int)
165149
assert result["retcode"] == 0
166150
assert result["stdout"] == expected
@@ -187,30 +171,3 @@ def test_redirect_stderr(modules, command, expected, redirect_stderr):
187171
else:
188172
assert result["stdout"] == ""
189173
assert expected in result["stderr"]
190-
191-
192-
@pytest.mark.parametrize(
193-
"command, expected, redirect_stderr",
194-
[
195-
(["whoami.exe", "/foo"], "/foo", True),
196-
(["whoami.exe", "/foo"], "/foo", False),
197-
],
198-
)
199-
def test_redirect_stderr_runas(modules, account, command, expected, redirect_stderr):
200-
"""
201-
Test redirection of stderr to stdout by running cmd.run_all with runas and invalid commands
202-
"""
203-
result = modules.cmd.run_all(
204-
command,
205-
runas=account.username,
206-
password=account.password,
207-
redirect_stderr=redirect_stderr,
208-
)
209-
assert isinstance(result["pid"], int)
210-
assert result["retcode"] == 1
211-
if redirect_stderr:
212-
assert expected in result["stdout"]
213-
assert result["stderr"] == ""
214-
else:
215-
assert result["stdout"] == ""
216-
assert expected in result["stderr"]

tests/pytests/functional/utils/test_win_runas.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -50,11 +50,11 @@ def test_compound_runas(user, cmd, expected):
5050
if expected == "username":
5151
expected = user.username
5252
result = win_runas.runas(
53-
cmd=salt.platform.win.prepend_cmd('cmd', cmd),
53+
cmd=salt.platform.win.prepend_cmd("cmd", cmd),
5454
username=user.username,
5555
password=user.password,
5656
)
57-
assert expected in result["stdout"].decode()
57+
assert expected in result["stdout"]
5858

5959

6060
@pytest.mark.parametrize(
@@ -69,36 +69,36 @@ def test_compound_runas_unpriv(user, cmd, expected):
6969
if expected == "username":
7070
expected = user.username
7171
result = win_runas.runas_unpriv(
72-
cmd=salt.platform.win.prepend_cmd('cmd', cmd),
72+
cmd=salt.platform.win.prepend_cmd("cmd", cmd),
7373
username=user.username,
7474
password=user.password,
7575
)
76-
assert expected in result["stdout"].decode()
76+
assert expected in result["stdout"]
7777

7878

7979
def test_runas_str_user(user):
8080
result = win_runas.runas(
8181
cmd="whoami", username=user.username, password=user.password
8282
)
83-
assert user.username in result["stdout"].decode()
83+
assert user.username in result["stdout"]
8484

8585

8686
def test_runas_int_user(int_user):
8787
result = win_runas.runas(
8888
cmd="whoami", username=int(int_user.username), password=int_user.password
8989
)
90-
assert str(int_user.username) in result["stdout"].decode()
90+
assert str(int_user.username) in result["stdout"]
9191

9292

9393
def test_runas_unpriv_str_user(user):
9494
result = win_runas.runas_unpriv(
9595
cmd="whoami", username=user.username, password=user.password
9696
)
97-
assert user.username in result["stdout"].decode()
97+
assert user.username in result["stdout"]
9898

9999

100100
def test_runas_unpriv_int_user(int_user):
101101
result = win_runas.runas_unpriv(
102102
cmd="whoami", username=int(int_user.username), password=int_user.password
103103
)
104-
assert str(int_user.username) in result["stdout"].decode()
104+
assert str(int_user.username) in result["stdout"]

tests/pytests/unit/modules/test_cmdmod.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1059,15 +1059,14 @@ def test_runas_env_sudo_group(bundled):
10591059
@pytest.mark.skip_unless_on_windows
10601060
def test__run_no_powershell():
10611061
with pytest.raises(CommandExecutionError):
1062-
cmdmod._run(
1063-
shell="unk_bin", cmd="Some-Command", encoded_cmd=False
1064-
)
1062+
cmdmod._run(shell="unk_bin", cmd="Some-Command", encoded_cmd=False)
10651063

10661064

10671065
@pytest.mark.parametrize(
10681066
"cmd, parsed",
10691067
[
10701068
("Write-Host foo", "Write-Host foo"),
1069+
("& Write-Host foo", "& Write-Host foo"),
10711070
("$PSVersionTable", "$PSVersionTable"),
10721071
("try {this} catch {that}", "try {this} catch {that}"),
10731072
("[bool]@{value = 0}", "[bool]@{value = 0}"),
@@ -1120,7 +1119,7 @@ def test_prep_powershell_cmd(cmd, parsed):
11201119
"-ExecutionPolicy",
11211120
"Bypass",
11221121
"-Command",
1123-
f'{parsed}',
1122+
parsed,
11241123
]
11251124
assert ret == expected
11261125

@@ -1142,7 +1141,7 @@ def test_prep_powershell_cmd_encoded():
11421141
"-ExecutionPolicy",
11431142
"Bypass",
11441143
"-EncodedCommand",
1145-
f'{e_cmd}',
1144+
e_cmd,
11461145
]
11471146
assert ret == expected
11481147

@@ -1157,7 +1156,7 @@ def test_prep_powershell_cmd_script():
11571156
win_shell="powershell.exe", cmd=script, encoded_cmd=False
11581157
)
11591158
expected = [
1160-
'powershell.exe',
1159+
"powershell.exe",
11611160
"-NonInteractive",
11621161
"-NoProfile",
11631162
"-ExecutionPolicy",

tests/pytests/unit/platform/test_win.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,10 @@
1818
("cmd /c hostname", 'cmd.exe /c "cmd /c hostname"'),
1919
("echo foo", 'cmd.exe /c "echo foo"'),
2020
('cmd /c "echo foo"', 'cmd.exe /c "cmd /c "echo foo""'),
21-
("icacls 'C:\\Program Files'", 'cmd.exe /c "icacls \'C:\\Program Files\'"'),
21+
("icacls 'C:\\Program Files'", "cmd.exe /c \"icacls 'C:\\Program Files'\""),
2222
(
2323
"icacls 'C:\\Program Files' && echo 1",
24-
'cmd.exe /c "icacls \'C:\\Program Files\' && echo 1"',
24+
"cmd.exe /c \"icacls 'C:\\Program Files' && echo 1\"",
2525
),
2626
(
2727
["secedit", "/export", "/cfg", "C:\\A Path\\with\\a\\space"],
@@ -32,7 +32,7 @@
3232
'cmd.exe /c ""C:\\a space\\a space.bat" "foo foo" "bar bar""',
3333
),
3434
(
35-
''' echo "&<>[]|{}^=;!'+,`~ " ''',
35+
""" echo "&<>[]|{}^=;!'+,`~ " """,
3636
'''cmd.exe /c " echo "&<>[]|{}^=;!'+,`~ " "''',
3737
),
3838
],
@@ -41,6 +41,6 @@ def test_prepend_cmd(command, expected):
4141
"""
4242
Test that the command is prepended with "cmd /c" and quoted
4343
"""
44-
win_shell = 'cmd.exe'
44+
win_shell = "cmd.exe"
4545
result = win.prepend_cmd(win_shell, command)
4646
assert result == expected

0 commit comments

Comments
 (0)