summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorrsiddharth <s@ricketyspace.net>2016-10-02 13:21:50 +0000
committerrsiddharth <s@ricketyspace.net>2016-10-02 13:29:18 +0000
commit60ae86411fb4727dd29baacb60f1d7d78a1c0942 (patch)
treeb7eec93cf3161d60207c0b75795857ca1a6e8995
parente2e157cfc3286a291e64121bf1422faf85094880 (diff)
Add `execute` function (gd_diff.py).
* gd_diff.py (execute): New function. * tests/test_gd_diff.py (test_execute_success, test_execute_cmderror) (test_execute_raise_exception): Tests for `execute` function.
-rw-r--r--gd_diff.py21
-rw-r--r--tests/test_gd_diff.py25
2 files changed, 46 insertions, 0 deletions
diff --git a/gd_diff.py b/gd_diff.py
index 97cf175..3c704e9 100644
--- a/gd_diff.py
+++ b/gd_diff.py
@@ -6,8 +6,12 @@
# gns-deb-diff is under the Public Domain. See
# <https://creativecommons.org/publicdomain/zero/1.0>
+import shlex
import sys
+from subprocess import run, PIPE
+
+
# list of recognized fields.
field_list = [
"Change-Type",
@@ -28,6 +32,23 @@ def read_file(fpath):
return f.read()
+def execute(cmd, out=None, err=None):
+ """Run `cmd`. Returns an instance of `subprocess.CompletedProcess`
+
+ `cmd` must be a string containing the command to run.
+ """
+ cmd = shlex.split(cmd)
+
+ try:
+ completed_process = run(cmd, stdout=out, stderr=err)
+ except (FileNotFoundError, OSError, ValueError) as e:
+ print("Error running '%s'\n Error Info:\n %r" % (cmd[0], e),
+ file=sys.stderr)
+ sys.exit(1)
+
+ return completed_process
+
+
def get_packages(pkgs_file):
"""Return an iterator contaning of package names from `pkgs_file`.
diff --git a/tests/test_gd_diff.py b/tests/test_gd_diff.py
index 650094f..2d6fe86 100644
--- a/tests/test_gd_diff.py
+++ b/tests/test_gd_diff.py
@@ -7,12 +7,14 @@
# <https://creativecommons.org/publicdomain/zero/1.0>
import os
+import subprocess
import sys
from nose.tools import *
from gd_diff import *
+
class TestGdDiff(object):
def setup(self):
@@ -32,6 +34,29 @@ class TestGdDiff(object):
f_content = read_file(self.pkgs_file_ne)
+ def test_execute_success(self):
+ cmd = 'python --version'
+ cp = execute(cmd, out=subprocess.PIPE)
+
+ assert cp.returncode == 0
+ assert cp.stdout.split()[0] == b'Python'
+ assert cp.stdout.split()[1].startswith(b'3.5')
+
+ def test_execute_cmderror(self):
+ cmd = 'bzr cat bzr://bzr.sv.gnu.org/gnewsense/packages-parkes/nonexistent-packages/debian/README.gNewSense'
+ cp = execute(cmd, err=subprocess.PIPE)
+
+ assert cp.returncode == 3
+ assert cp.stderr.startswith(b'bzr: ERROR:')
+
+
+ @raises(SystemExit)
+ def test_execute_raise_exception(self):
+ cmd = 'cornhole computers'
+ with open(os.devnull, 'w') as sys.stderr:
+ cp = execute(cmd)
+
+
def test_get_packages(self):
pkgs_iter = get_packages(self.pkgs_file)
assert len(list(pkgs_iter)) == 82