Change execute to raise exception on error

Previously the execute command had been silently ignoring any execution
errors. This lead to some unpredictable behavior as the callers were not
checking for error codes. In order to make this a bit easier, allow
caller to set the expected return code and fail if we get anythong other
than that.

Also, as the git functions in util.py were not being used, remove them
and their associated tests.
This commit is contained in:
Craig Tracey 2014-09-21 17:33:20 -04:00
parent 9d505b1b3f
commit 3a9de408cf
2 changed files with 16 additions and 44 deletions

View File

@ -17,43 +17,22 @@
import unittest2 as unittest
from mock import patch
from giftwrap import util
class TestUtil(unittest.TestCase):
def test_execute_returns_exitcode_tuple(self):
cmd = 'test true'
result, _, _ = util.execute(cmd)
self.assertEquals(0, result)
def test_execute_returns_stdout_tuple(self):
def test_execute_returns_stdout(self):
cmd = 'echo stdout'
_, out, _ = util.execute(cmd)
out = util.execute(cmd)
self.assertEquals('stdout\n', out)
def test_execute_returns_stderr_tuple(self):
cmd = 'echo stderr >&2'
_, _, err = util.execute(cmd)
def test_execute_raises_exception_on_error(self):
cmd = 'echo stderr >&2 && false'
with self.assertRaises(Exception):
util.execute(cmd)
self.assertEquals('stderr\n', err)
def test_clone_git_repo(self):
with patch('os.path.isdir') as mocked_isdir:
mocked_isdir.return_value = False
with patch('git.Repo.clone_from') as mocked:
util.clone_git_repo('git@github.com:foo/bar.git', '/tmp')
mocked.assert_called_once_with('git@github.com:foo/bar.git',
'/tmp/bar')
def test_clone_git_repo_does_not_clone_if_already_cloned(self):
with patch('os.path.isdir') as mocked_isdir:
mocked_isdir.return_value = True
with patch('git.Repo.clone_from') as mocked:
util.clone_git_repo('git@github.com:foo/bar.git', '/tmp/')
assert not mocked.called
def test_nonzero_exit_code(self):
cmd = 'echo stdout && false'
out = util.execute(cmd, exit=1)
self.assertEquals('stdout\n', out)

View File

@ -18,21 +18,19 @@
import os
import subprocess
from git import Repo
import giturlparse
from giftwrap import log
LOG = log.get_logger()
def execute(command, cwd=None):
def execute(command, cwd=None, exit=0):
"""
Executes a command in a subprocess. Returns a tuple of
(exitcode, out, err).
:param command: Command string to execute.
:param cwd: Directory to execute from.
:param exit: The expected exit code.
"""
original_dir = None
@ -58,13 +56,8 @@ def execute(command, cwd=None):
os.chdir(original_dir)
LOG.debug("Changed directory back to %s", original_dir)
return exitcode, out, err
if exitcode != exit:
raise Exception("Failed to run '%s': rc: %d, out: '%s', err: '%s'" %
(command, exitcode, out, err))
def clone_git_repo(repo, checkout_dir):
parsedrepo = giturlparse.parse(repo, False)
directory = os.path.join(checkout_dir, parsedrepo.repo)
if not os.path.isdir(directory):
Repo.clone_from(repo, directory)
return directory
return out