*: Always pass check= argument to subprocess.run()

- Avoid flake8 warnings.

- Makes the call more explicitly readable in case an exception is expected but
check=True is not passed by mistake.

Tests:

- Many tests are skipped since the changes are considered trivial.
check=False is already the default for subprocess.run() method.

- actions/package: Install an app when it is not installed.

- actions/upgrade: Run manual upgrades.

- actions/users: Change a user password. Login. Create/remove a user.

- actions/zoph: Restore a database.

- container: On a fresh repository, run ./container up,ssh,stop,destroy for a
testing container.

- plinth/action_utils.py: Enable/disable an app that has a running service.

Signed-off-by: Sunil Mohan Adapa <sunil@medhas.org>
Reviewed-by: James Valleroy <jvalleroy@mailbox.org>
This commit is contained in:
Sunil Mohan Adapa authored and James Valleroy committed 2021-10-11 14:34:40 -04:00
1 parent ebd357476d
commit 9bd1f80d5c
17 files changed
+62 -55

No files matched your search

+6 -5
View File
@@ -128,10 +128,10 @@ def service_action(service_name, action):
"""Perform the given action on the service_name."""
if is_systemd_running():
subprocess.run(['systemctl', action, service_name],
stdout=subprocess.DEVNULL)
stdout=subprocess.DEVNULL, check=False)
else:
subprocess.run(['service', service_name, action],
stdout=subprocess.DEVNULL)
stdout=subprocess.DEVNULL, check=False)
def webserver_is_enabled(name, kind='config'):
@@ -371,7 +371,7 @@ Owners: {package}
env['DEBCONF_DB_OVERRIDE'] = 'File{' + override_file.name + \
' readonly:true}'
env['DEBIAN_FRONTEND'] = 'noninteractive'
subprocess.run(['dpkg-reconfigure', package], env=env)
subprocess.run(['dpkg-reconfigure', package], env=env, check=False)
try:
os.remove(override_file.name)
@@ -419,7 +419,7 @@ def run_apt_command(arguments):
env['DEBIAN_FRONTEND'] = 'noninteractive'
process = subprocess.run(command, stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL, close_fds=False,
env=env)
env=env, check=False)
return process.returncode
@@ -458,7 +458,8 @@ def apt_hold_freedombox():
def apt_unhold_freedombox():
"""Remove any hold on freedombox package, and clear flag."""
subprocess.run(['apt-mark', 'unhold', 'freedombox'],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
check=False)
if apt_hold_flag.exists():
apt_hold_flag.unlink()
+3 -2
View File
@@ -285,12 +285,13 @@ class VerifySshHostkeyForm(forms.Form):
# Fetch public keys of ssh remote
keyscan = subprocess.run(['ssh-keyscan', hostname],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stderr=subprocess.PIPE, check=False)
keys = keyscan.stdout.decode().splitlines()
error_message = keyscan.stderr.decode() if keyscan.returncode else None
# Generate user-friendly fingerprints of public keys
keygen = subprocess.run(['ssh-keygen', '-l', '-f', '-'],
input=keyscan.stdout, stdout=subprocess.PIPE)
input=keyscan.stdout, stdout=subprocess.PIPE,
check=False)
fingerprints = keygen.stdout.decode().splitlines()
return zip(keys, fingerprints), error_message
@@ -38,7 +38,7 @@ def fixture_password():
def get_hashed_password(password):
res = subprocess.run(['mkpasswd', '--method=md5', password],
stdout=subprocess.PIPE)
stdout=subprocess.PIPE, check=True)
return res.stdout.decode().strip()
+3 -3
View File
@@ -244,8 +244,8 @@ def _action_set_keys():
clean_dict[key] = clean_function(value)
# Apply changes (postconf)
postconf_dict = dict(filter(lambda kv: not kv[0].startswith('_'),
clean_dict.items()))
postconf_dict = dict(
filter(lambda kv: not kv[0].startswith('_'), clean_dict.items()))
postconf.set_many(postconf_dict)
# Apply changes (special)
@@ -258,7 +258,7 @@ def _action_set_keys():
with postconf.mutex.lock_all():
# systemctl reload postfix
args = ['systemctl', 'reload', 'postfix']
completed = subprocess.run(args, capture_output=True)
completed = subprocess.run(args, capture_output=True, check=False)
if completed.returncode != 0:
interproc.log_subprocess(completed)
raise OSError('Could not reload postfix')
+1 -1
View File
@@ -65,7 +65,7 @@ def action_mk(arg_type, user_info):
args = ['sudo', '-n', '--user=#' + str(passwd.pw_uid)]
args.extend(['/bin/sh', '-c', 'mkdir -p ~'])
completed = subprocess.run(args, capture_output=True)
completed = subprocess.run(args, capture_output=True, check=False)
if completed.returncode != 0:
interproc.log_subprocess(completed)
raise OSError('Could not create home directory')
+1 -1
View File
@@ -140,7 +140,7 @@ def _compile_sieve():
def _run_sievec(sieve_file):
logger.info('Compiling sieve script %s', sieve_file)
args = ['sievec', '--', sieve_file]
completed = subprocess.run(args, capture_output=True)
completed = subprocess.run(args, capture_output=True, check=False)
if completed.returncode != 0:
interproc.log_subprocess(completed)
raise OSError('Sieve compilation failed: ' + sieve_file)
+1 -1
View File
@@ -89,7 +89,7 @@ class Mutex:
args.extend(['/bin/sh', '-c'])
args.append('umask 177 && > ' + self.lock_path)
completed = subprocess.run(args, capture_output=True)
completed = subprocess.run(args, capture_output=True, check=False)
if completed.returncode != 0:
interproc.log_subprocess(completed)
raise OSError('Could not create ' + self.lock_path)
+5 -6
View File
@@ -56,7 +56,7 @@ class Disk():
command = 'losetup --show --find {file}'.format(
file=self.disk_file.name)
process = subprocess.run(command.split(), stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stderr=subprocess.PIPE, check=False)
if process.returncode:
if b'cannot find an unused loop device' in process.stderr:
pytest.skip('Loopback devices not available')
@@ -107,7 +107,7 @@ class Disk():
def _cleanup_loopback(self):
"""Undo the loopback device setup."""
subprocess.run(['losetup', '--detach', self.device])
subprocess.run(['losetup', '--detach', self.device], check=False)
def _remove_disk_file(self):
"""Delete the disk_file."""
@@ -231,16 +231,15 @@ class TestActions:
self.assert_aligned(partition_number)
@staticmethod
def call_action(action_command, **kwargs):
def call_action(action_command, check=True, **kwargs):
"""Call the action script."""
test_directory = pathlib.Path(__file__).parent
top_directory = (test_directory / '..' / '..' / '..' / '..').resolve()
action_command[0] = top_directory / 'actions' / action_command[0]
kwargs['stdout'] = kwargs.get('stdout', subprocess.DEVNULL)
kwargs['stderr'] = kwargs.get('stderr', subprocess.DEVNULL)
kwargs['check'] = kwargs.get('check', True)
env = dict(os.environ, PYTHONPATH=str(top_directory))
return subprocess.run(action_command, env=env, **kwargs)
return subprocess.run(action_command, env=env, check=check, **kwargs)
def check_action(self, action_command):
"""Return success/failure result of the action command."""
@@ -255,7 +254,7 @@ class TestActions:
subprocess.run([
'parted', '--script', self.device, 'align-check', 'opti',
str(partition_number)
])
], check=True)
def assert_btrfs_file_system_healthy(self, partition_number):
"""Perform a successful ext4 file system check."""
+2 -1
View File
@@ -114,7 +114,8 @@ def get_log():
def _is_updating():
"""Check if manually triggered update is running."""
command = ['systemctl', 'is-active', 'freedombox-manual-upgrade']
result = subprocess.run(command, capture_output=True, text=True)
result = subprocess.run(command, capture_output=True, text=True,
check=False)
return str(result.stdout).startswith('activ') # 'active' or 'activating'
+2 -3
View File
@@ -138,12 +138,11 @@ def fixture_auto_cleanup_users_groups(needs_root, load_cfg):
_delete_group(group)
def _call_action(arguments, **kwargs):
def _call_action(arguments, check=True, **kwargs):
"""Call the action script."""
kwargs['stdout'] = kwargs.get('stdout', subprocess.PIPE)
kwargs['stderr'] = kwargs.get('stderr', subprocess.PIPE)
kwargs['check'] = kwargs.get('check', True)
return subprocess.run([_action_file()] + arguments, **kwargs)
return subprocess.run([_action_file()] + arguments, check=check, **kwargs)
def _create_user(username=None, groups=None):