import unittest import subprocess import threading class TestSysCommand(unittest.TestCase): __str_cmd = None __testname = None __outfilename = None __outdata = None __outtofile = False def __init__(self, testname, testfunc, str_cmd, outtofile=False): """ init """ super(TestSysCommand, self).__init__(testfunc) self.__str_cmd = str_cmd self.__testname = testname self.__outtofile = outtofile self._testMethodDoc = testname if self.__outtofile is True: self.__outfilename = '/tmp/{}.txt'.format(testname) def getName(self): return self.__testname def execute(self): res = -1 try: completed = subprocess.run( self.__str_cmd, check=True, shell=True, stdout=subprocess.PIPE, ) self.assertTrue(completed.returncode is 0) if completed.returncode is 0: if self.__outtofile is True: f = open(self.__outfilename, 'wb') f.write(completed.stdout) f.close() res = 0 else: res = -3 outdata = completed.stdout self.longMessage = str(outdata).replace("'", "") self.assertTrue(True) except subprocess.CalledProcessError as err: self.assertTrue(False) res = -1 except Exception as t: res = -2 return res def remove_file(self): pass class SysCommand(object): __str_cmd = None __cmdname = None __outdata = None __errdata = None __returnCode = None __exception = None def __init__(self, cmdname, str_cmd): """ init """ self.__str_cmd = str_cmd self.__cmdname = cmdname def getName(self): return self.__cmdname def setName(self, cmdName): self.__cmdname = cmdName def getParams(self): return self.__str_cmd def setParam(self, params): self.__str_cmd = params def execute(self): # try: self.__outdata = None self.__errdata = None self.__exception = None try: completed = subprocess.run( self.__str_cmd, check=False, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) self.__returnCode = completed.returncode self.__outdata = completed.stdout self.__errdata = completed.stderr.decode('ascii') except subprocess.CalledProcessError as err: self.__exception = err self.__returnCode = -1 return self.__returnCode def getOutput(self): return self.__outdata def getOutErr(self): return self.__errdata def getException(self): return self.__exception def IsException(self): return self.__exception is not None def getOutputlines(self): return self.__outdata.splitlines() def save_file(self, fname): f = open(fname, 'wb') f.write(self.__outdata) f.close() class AsyncSys(threading.Thread): sysObject = None sysres = None def __init__(self, threadID, name, counter): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.counter = counter self.sysObject = SysCommand(name, None) def setParams(self, Params): self.sysObject.setParam(Params) def getRes(self): return self.sysres def getData(self): return self.sysObject.getOutput() def run(self): self.sysres = self.sysObject.execute()