Add tests for `make_command`.
@@ -3,6 +3,7 @@ from unittest import TestCase
from pyinfra.api.util import (
format_exception,
get_caller_frameinfo,
+ make_command,
try_int,
underscore,
)
@@ -20,7 +21,7 @@ class TestApiUtil(TestCase):
return get_caller_frameinfo()
frameinfo = _get_caller_frameinfo()
- self.assertEqual(frameinfo.lineno, 22) # called by the line above
+ self.assertEqual(frameinfo.lineno, 23) # called by the line above
def test_underscore(self):
for camel_string, snake_string in (
@@ -36,3 +37,52 @@ class TestApiUtil(TestCase):
format_exception(exception),
"Exception('I am a message', 1)",
)
+
+
+class TestMakeCommandApiUtil(TestCase):
+ def test_command(self):
+ command = make_command('uptime')
+ self.assertEqual(command, 'sh -c uptime')
+
+ def test_sudo_command(self):
+ command = make_command('uptime', sudo=True)
+ self.assertEqual(command, 'sudo -H sh -c uptime')
+
+ def test_sudo_preserve_env_command(self):
+ command = make_command('uptime', sudo=True, preserve_sudo_env=True)
+ self.assertEqual(command, 'sudo -H -E sh -c uptime')
+
+ def test_sudo_user_command(self):
+ command = make_command('uptime', sudo=True, sudo_user='pyinfra')
+ self.assertEqual(command, 'sudo -H -u pyinfra sh -c uptime')
+
+ def test_su_command(self):
+ command = make_command('uptime', su_user='pyinfra')
+ self.assertEqual(command, 'su pyinfra -s `which sh` -c uptime')
+
+ def test_command_env(self):
+ command = make_command('uptime', env={'key': 'value'})
+ self.assertEqual(command, "sh -c 'export key=value; uptime'")
+
+ def test_custom_shell_command(self):
+ command = make_command('uptime', shell_executable='bash')
+ self.assertEqual(command, 'bash -c uptime')
+
+ def test_mixed_command(self):
+ command = make_command(
+ 'uptime',
+ env={'key': 'value'},
+ sudo=True,
+ sudo_user='root',
+ preserve_sudo_env=True,
+ su_user='pyinfra',
+ shell_executable='bash',
+ )
+ self.assertEqual(
+ command,
+ (
+ 'sudo -H -E -u root ' # sudo bit
+ 'su pyinfra -s `which bash` -c ' # su bit
+ "'export key=value; uptime'" # command bit
+ ),
+ )
