From 09de774dcc1a5abc1c8f3a00fdb039aa3c522f52 Mon Sep 17 00:00:00 2001 From: Manel Caro Date: Wed, 4 Mar 2020 17:46:36 +0100 Subject: SOPA Initial Commit --- test-cli/test/helpers/cv_display_test.py | 28 ++++-------- test-cli/test/helpers/get_dieid.py | 2 - test-cli/test/helpers/globalVariables.py | 2 - test-cli/test/helpers/iseelogger.py | 39 ++++++++++++++++ test-cli/test/helpers/psqldb.py | 19 ++++---- test-cli/test/helpers/setup_xml.py | 9 +++- test-cli/test/helpers/syscmd.py | 19 ++++++-- test-cli/test/helpers/testsrv_db.py | 37 ++++++++------- test-cli/test/helpers/usb.sh | 14 ++++++ test-cli/test/runners/simple.py | 26 +++++++---- test-cli/test/tests/qamp.py | 47 ++++++++----------- test-cli/test/tests/qaudio.py | 11 +++-- test-cli/test/tests/qbutton.py | 19 +++++--- test-cli/test/tests/qduplex_ser.py | 21 +++++++-- test-cli/test/tests/qeeprom.py | 2 +- test-cli/test/tests/qethernet.py | 78 +++++++++++++++----------------- test-cli/test/tests/qflash.py | 5 +- test-cli/test/tests/qi2c.py | 12 +++-- test-cli/test/tests/qnand.py | 22 +++++++++ test-cli/test/tests/qram.py | 33 ++++++++------ test-cli/test/tests/qrtc.py | 9 +++- test-cli/test/tests/qscreen.py | 18 +++----- test-cli/test/tests/qserial.py | 15 ++++-- test-cli/test/tests/qusb.py | 17 ++++--- test-cli/test/tests/qwifi.py | 52 ++++++++------------- 25 files changed, 326 insertions(+), 230 deletions(-) create mode 100644 test-cli/test/helpers/iseelogger.py create mode 100755 test-cli/test/helpers/usb.sh create mode 100644 test-cli/test/tests/qnand.py (limited to 'test-cli/test') diff --git a/test-cli/test/helpers/cv_display_test.py b/test-cli/test/helpers/cv_display_test.py index b54a698..3a3004f 100644 --- a/test-cli/test/helpers/cv_display_test.py +++ b/test-cli/test/helpers/cv_display_test.py @@ -14,8 +14,7 @@ def pattern_detect(cam_device=0): # RETURN 0 only if the test is ok msg="0" # Capture the corresponding camera device [0,1] - #capture = cv2.VideoCapture(0) - capture = cv2.VideoCapture("/dev/v4l/by-id/usb-Creative_Technology_Ltd._Live__Cam_Sync_HD_VF0770-video-index0") + capture = cv2.VideoCapture(0) try: _, image = capture.read() except: @@ -64,12 +63,10 @@ def pattern_detect(cam_device=0): # After testing the gamma factor correction is computed with the green color # gamma = gamma_factor / blue+red into green part # gamma factor = 50-100 - #gamma = (100 / (avg_color_rawg[0] + avg_color_rawg[2] + 1)) - gamma=1 + gamma = (100 / (avg_color_rawg[0] + avg_color_rawg[2] + 1)) # Adjust the image acording to this gamma value adjusted = adjust_gamma(image, gamma=gamma) -# adjusted=image - cv2.imwrite( "/home/root/result_hdmi_img.jpg", adjusted); + # Calculate again the average color using the gamma adjusted image # Crop the gamma adjusted image for wach color section red_cal = adjusted[y1:y2, xr1:xr2] @@ -109,19 +106,14 @@ def pattern_detect(cam_device=0): mask_r = mask0 + mask1 # mask_r = cv2.inRange(hsv, lower_red, upper_red) # Perform a morphological open to expand -# kernel = np.ones((5, 5), np.uint8) -# closing_r = cv2.morphologyEx(mask_r, cv2.MORPH_OPEN, kernel) -# closing_b = cv2.morphologyEx(mask_b, cv2.MORPH_OPEN, kernel) -# closing_g = cv2.morphologyEx(mask_g, cv2.MORPH_OPEN, kernel) + kernel = np.ones((15, 15), np.uint8) + closing_r = cv2.morphologyEx(mask_r, cv2.MORPH_OPEN, kernel) + closing_b = cv2.morphologyEx(mask_b, cv2.MORPH_OPEN, kernel) + closing_g = cv2.morphologyEx(mask_g, cv2.MORPH_OPEN, kernel) # Count the number of pixels that are not of the corresponding color (black) -# count_r = cv2.countNonZero(closing_r) -# count_b = cv2.countNonZero(closing_b) -# count_g = cv2.countNonZero(closing_g) - #----------- - count_r = cv2.countNonZero(mask_r) - count_b = cv2.countNonZero(mask_b) - count_g = cv2.countNonZero(mask_g) - #------- + count_r = cv2.countNonZero(closing_r) + count_b = cv2.countNonZero(closing_b) + count_g = cv2.countNonZero(closing_g) if (count_r < 5): msg = "RED COUNT FAIL" return msg diff --git a/test-cli/test/helpers/get_dieid.py b/test-cli/test/helpers/get_dieid.py index b20f143..029ddb5 100644 --- a/test-cli/test/helpers/get_dieid.py +++ b/test-cli/test/helpers/get_dieid.py @@ -21,8 +21,6 @@ def read(addr): def getRegisters(model): if model.find("IGEP0046") == 0: registers = [0x021BC420, 0x021BC410] - elif model.find("IGEP0000") == 0: - registers = [0x021BC420, 0x021BC410] elif model.find("IGEP0034") == 0 or model.find("SOPA0000") == 0: registers = [0x44e10630, 0x44e10634, 0x44e10638, 0x44e1063C] elif model.find("OMAP3") == 0: diff --git a/test-cli/test/helpers/globalVariables.py b/test-cli/test/helpers/globalVariables.py index c4d8358..6b89f4d 100644 --- a/test-cli/test/helpers/globalVariables.py +++ b/test-cli/test/helpers/globalVariables.py @@ -6,5 +6,3 @@ def globalVar(): g_mid = "" outdata = "NONE" station = "" - fstatus = "" - gdisplay = None \ No newline at end of file diff --git a/test-cli/test/helpers/iseelogger.py b/test-cli/test/helpers/iseelogger.py new file mode 100644 index 0000000..785a78c --- /dev/null +++ b/test-cli/test/helpers/iseelogger.py @@ -0,0 +1,39 @@ +import logging +import logging.handlers + + +class ISEE_Logger(object): + __logger = None + __logHandler = None + __formater = None + __logHandlerConsole = None + + def __init__(self, level=logging.INFO): + # Create syslog logger + self.__logger = logging.getLogger('ISEE_logger') + self.__logger.setLevel(level) + self.__logHandler = logging.handlers.SysLogHandler('/dev/log') + self.__logHandlerConsole = logging.StreamHandler() + self.__formater = logging.Formatter('Python: { "loggerName":"%(name)s", "timestamp":"%(asctime)s", "pathName":"%(pathname)s", "logRecordCreationTime":"%(created)f", "functionName":"%(funcName)s", "levelNo":"%(levelno)s", "lineNo":"%(lineno)d", "time":"%(msecs)d", "levelName":"%(levelname)s", "message":"%(message)s"}') + self.__logHandler.formatter = self.__formater + self.__logHandlerConsole.formatter = self.__formater + self.__logger.addHandler(self.__logHandler) + self.__logger.addHandler(self.__logHandlerConsole) + + def setLogLevel(self, level): + if level.upper() == "DEBUG": + nlevel = logging.DEBUG + elif level.upper() == "INFO": + nlevel = logging.INFO + elif level.upper() == "ERROR": + nlevel = logging.ERROR + elif level.upper() == "WARNING": + nlevel = logging.WARNING + else: + nlevel = logging.DEBUG + + self.__logger.setLevel(nlevel) + + def getlogger(self): + return self.__logger + diff --git a/test-cli/test/helpers/psqldb.py b/test-cli/test/helpers/psqldb.py index 26dd03d..1d0e422 100644 --- a/test-cli/test/helpers/psqldb.py +++ b/test-cli/test/helpers/psqldb.py @@ -7,15 +7,15 @@ class PgSQLConnection(object): __db_config = {'dbname': 'testsrv', 'host': '192.168.2.171', 'password': 'Idkfa2009', 'port': 5432, 'user': 'admin'} - def __init__ (self): -# self.__conection_object = None -# if connect_str is not None: -# self.__db_config = connect_str -# else: - self.__db_config = {'dbname': 'testsrv', 'host': '192.168.2.171', - 'password': 'Idkfa2009', 'port': 5432, 'user': 'admin'} - - def db_connect (self, connect_str): + def __init__ (self, connect_str = None): + self.__conection_object = None + if connect_str is not None: + self.__db_config = connect_str + else: + self.__db_config = {'dbname': 'testsrv', 'host': '192.168.2.171', + 'password': 'Idkfa2009', 'port': 5432, 'user': 'admin'} + + def db_connect (self, connect_str = None): result = False try: if connect_str == None: @@ -23,6 +23,7 @@ class PgSQLConnection(object): else: self.__db_config = connect_str; self.__conection_object = psycopg2.connect(**self.__db_config) + self.__conection_object.autocommit = True result = True except Exception as error: diff --git a/test-cli/test/helpers/setup_xml.py b/test-cli/test/helpers/setup_xml.py index 3fd9fd5..eb8d73c 100644 --- a/test-cli/test/helpers/setup_xml.py +++ b/test-cli/test/helpers/setup_xml.py @@ -37,4 +37,11 @@ class XMLSetup (object): def getMysqlConnectionStr (self): """aaaaa""" - pass \ No newline at end of file + pass + + def gettagKey (self, xmltag, xmlkey): + """aaaaa""" + for element in self.__tree.iter(xmltag): + return element.attrib[xmlkey] + + return None \ No newline at end of file diff --git a/test-cli/test/helpers/syscmd.py b/test-cli/test/helpers/syscmd.py index b579e39..a869bd7 100644 --- a/test-cli/test/helpers/syscmd.py +++ b/test-cli/test/helpers/syscmd.py @@ -10,15 +10,24 @@ class TestSysCommand(unittest.TestCase): __outdata = None __outtofile = False - def __init__(self, testname, testfunc, str_cmd, outtofile = False): + #varlist: str_cmd, outtofile + def __init__(self, testname, testfunc, varlist): """ init """ super(TestSysCommand, self).__init__(testfunc) - self.__str_cmd = str_cmd + if "str_cmd" in varlist: + self.__str_cmd = varlist["str_cmd"] + else: + raise Exception('str_cmd param inside TestSysCommand have been be defined') self.__testname = testname - self.__outtofile = outtofile + if "outtofile" in varlist: + self.__outtofile = varlist["outtofile"] + if self.__outtofile is True: + self.__outfilename = '/tmp/{}.txt'.format(testname) + else: + self.__outtofile = None + self.__outfilename = None self._testMethodDoc = testname - if self.__outtofile is True: - self.__outfilename = '/tmp/{}.txt'.format(testname) + def getName(self): return self.__testname diff --git a/test-cli/test/helpers/testsrv_db.py b/test-cli/test/helpers/testsrv_db.py index 94181f9..f08cb17 100644 --- a/test-cli/test/helpers/testsrv_db.py +++ b/test-cli/test/helpers/testsrv_db.py @@ -19,12 +19,12 @@ class TestSrv_Database(object): def __init__(self): pass - def open (self, filename): - '''Open database connection''' - self.__xml_setup = XMLSetup(filename) + def open (self, xmlObj): + self.__xml_setup = xmlObj; self.__sqlObject = PgSQLConnection() return self.__sqlObject.db_connect(self.__xml_setup.getdbConnectionStr()) + def create_board(self, processor_id, model_id, variant, bmac = None): '''create a new board''' if bmac is None: @@ -95,7 +95,20 @@ class TestSrv_Database(object): def getboard_comp_test_list(self, board_uuid): '''get the board test list''' - sql = "SELECT isee.gettestcompletelist('{}')".format(board_uuid) + sql = "SELECT * FROM isee.gettestcompletelist('{}')".format(board_uuid) + #print('>>>' + sql) + try: + res = self.__sqlObject.db_execute_query(sql) + #print(res) + return res; + except Exception as err: + r = find_between(str(err), '#', '#') + #print(r) + return None + + def getboard_test_variables(self, board_uuid, testdefid): + '''get the board test list''' + sql = "SELECT * FROM isee.getboardtestvariables('{}', '{}')".format(board_uuid, testdefid) #print('>>>' + sql) try: res = self.__sqlObject.db_execute_query(sql) @@ -159,18 +172,4 @@ class TestSrv_Database(object): except Exception as err: r = find_between(str(err), '#', '#') #print(r) - return None - - def getboard_eeprom(self, board_uuid): - '''get the board eeprom struct ''' - sql = "SELECT isee.getboard_eeprom('{}')".format(board_uuid) - #print('>>>' + sql) - try: - res = self.__sqlObject.db_execute_query(sql) - #print(res) - return res; - except Exception as err: - r = find_between(str(err), '#', '#') - #print(r) - return None - \ No newline at end of file + return None \ No newline at end of file diff --git a/test-cli/test/helpers/usb.sh b/test-cli/test/helpers/usb.sh new file mode 100755 index 0000000..c8e6924 --- /dev/null +++ b/test-cli/test/helpers/usb.sh @@ -0,0 +1,14 @@ +#!/bin/bash + +for sysdevpath in $(find /sys/bus/usb/devices/usb*/ -name dev); do + ( + syspath="${sysdevpath%/dev}" + devname="$(udevadm info -q name -p $syspath)" + [[ "$devname" == "bus/"* ]] && continue + eval "$(udevadm info -q property --export -p $syspath)" + [[ -z "$ID_SERIAL" ]] && continue + echo "/dev/$devname - $ID_SERIAL" + ) +done + +return 0 diff --git a/test-cli/test/runners/simple.py b/test-cli/test/runners/simple.py index 5b2da5a..3537d0e 100644 --- a/test-cli/test/runners/simple.py +++ b/test-cli/test/runners/simple.py @@ -22,9 +22,12 @@ class SimpleTestRunner: --------------------------------------------- """ - def __init__(self, stream=sys.stderr, verbosity=0): + __pgObj = None + + def __init__(self, pgObj, stream=sys.stderr, verbosity=0): self.stream = stream self.verbosity = verbosity + self.__pgObj = pgObj def writeUpdate(self, message): self.stream.write(message) @@ -33,7 +36,7 @@ class SimpleTestRunner: """ Run the given test case or Test Suite. """ - result = TextTestResult(self) + result = TextTestResult(self, self.__pgObj) test(result) result.testsRun # self.writeUpdate("---------------------------------------------\n") @@ -45,18 +48,22 @@ class TextTestResult(unittest.TestResult): FAIL = '\033[31mFAIL\033[0m\n' ERROR = '\033[31mERROR\033[0m\n' - def __init__(self, runner): + __pgObj = None + + def __init__(self, runner, pgObj): unittest.TestResult.__init__(self) self.runner = runner self.result = self.ERROR + self.__pgObj = pgObj def startTest(self, test): unittest.TestResult.startTest(self, test) self.runner.writeUpdate("%s : " % test.shortDescription()) # SEND TO DB THE UPDATE THAT WE RUN EACH TEST - psdb = TestSrv_Database() - psdb.open("setup.xml") - psdb.update_set_test_row(globalVar.station, globalVar.testid_ctl, globalVar.g_uuid, test.shortDescription(), "RUNNING") + self.__pgObj.update_set_test_row(globalVar.station, globalVar.testid_ctl, globalVar.g_uuid, test.shortDescription(), "RUNNING") + # psdb = TestSrv_Database() + # psdb.open("setup.xml") + # psdb.update_set_test_row(globalVar.station, globalVar.testid_ctl, globalVar.g_uuid, test.shortDescription(), "RUNNING") def addSuccess(self, test): unittest.TestResult.addSuccess(self, test) @@ -93,6 +100,7 @@ class TextTestResult(unittest.TestResult): if self.result == self.FAIL: simple_result = "FALSE" elif self.result == self.ERROR: simple_result = "FALSE" #SEND TO DB THE RESULT OF THE TEST - psdb = TestSrv_Database() - psdb.open("setup.xml") - psdb.add_test_to_batch(globalVar.g_uuid, test.shortDescription(), globalVar.testid_ctl, simple_result, globalVar.g_mid, test.longMessage) + # psdb = TestSrv_Database() + # psdb.open("setup.xml") + self.__pgObj.add_test_to_batch(globalVar.g_uuid, test.shortDescription(), globalVar.testid_ctl, simple_result, globalVar.g_mid, test.longMessage) + # psdb.add_test_to_batch(globalVar.g_uuid, test.shortDescription(), globalVar.testid_ctl, simple_result, globalVar.g_mid, test.longMessage) diff --git a/test-cli/test/tests/qamp.py b/test-cli/test/tests/qamp.py index 9fcd6d2..3e38ce9 100644 --- a/test-cli/test/tests/qamp.py +++ b/test-cli/test/tests/qamp.py @@ -5,10 +5,17 @@ import time class Qamp(unittest.TestCase): - def __init__(self, testname, testfunc, undercurrent=0.1, overcurrent=2): + #varlist: undercurrent, overcurrent + def __init__(self, testname, testfunc, varlist): self._current = 0.0 - self._undercurrent=undercurrent - self._overcurrent = overcurrent + if "undercurrent" in varlist: + self._undercurrent = varlist["undercurrent"] + else: + raise Exception('undercurrent param inside Qamp must be defined') + if "overcurrent" in varlist: + self._overcurrent = varlist["overcurrent"] + else: + raise Exception('overcurrent param inside Qamp must be defined') self._vshuntfactor=16384.0 self._ser = serial.Serial() self._ser.port = '/dev/ttyUSB0' @@ -33,24 +40,12 @@ class Qamp(unittest.TestCase): except: self.fail("failed: IMPOSSIBLE OPEN USB-SERIAL PORT ( {} )".format(self._ser.port)) error=1 - return -1 if error==0: # Clean input and output buffer of serial port self._ser.flushInput() self._ser.flushOutput() # Send command to read Voltage at Shunt resistor # Prepare cmd - cmd = ('at\n\r') - i=0 - while (i < len(cmd)): - i = i + self._ser.write(cmd[i].encode('ascii')) - time.sleep(0.05) - self._ser.read(1) - res0 = [] - while (self._ser.inWaiting() > 0): # if incoming bytes are waiting to be read from the serial input buffer - res0.append(self._ser.read(1).decode('ascii')) # read the bytes and convert from binary array to ASCII - print(res0) - #CHECK COM FIRST cmd = ('at+in?\n\r') i = 0 @@ -67,21 +62,15 @@ class Qamp(unittest.TestCase): string = ''.join(res) string = string.replace('\n', '') - try: - self._current = float(int(string, 0)) / self._vshuntfactor - except: - self.fail("failed: CAN'T READ CONSUMPTION (CURRENT=0?)") - error=1 - return -1 - if error==0: - print(self._current) + self._current = float(int(string, 0)) / self._vshuntfactor + print(self._current) # In order to give a valid result it is importarnt to define an under current value - if (self._current > float(self._overcurrent)): - self.fail("failed: OVERCURRENT DETECTED ( {} )".format(self._current)) - return -1 + if (self._current > float(self._overcurrent)): + self.fail("failed: OVERCURRENT DETECTED ( {} )".format(self._current)) + + if (self._current < float(self._undercurrent)): + self.fail("failed: UNDERCURRENT DETECTED ( {} )".format(self._current)) + - if (self._current < float(self._undercurrent)): - self.fail("failed: UNDERCURRENT DETECTED ( {} )".format(self._current)) - return -1 diff --git a/test-cli/test/tests/qaudio.py b/test-cli/test/tests/qaudio.py index a1572ca..fe57be2 100644 --- a/test-cli/test/tests/qaudio.py +++ b/test-cli/test/tests/qaudio.py @@ -13,13 +13,14 @@ class Qaudio(unittest.TestCase): self.__refSum = 25 # 1+3+5+7+9 def execute(self): - str_cmd = "aplay test/files/dtmf-13579.wav 2> /dev/null & arecord -r 8000 -d 1 recorded.wav 2> /dev/null" #.format(self.__dtmfFile) + str_cmd = "aplay test/files/dtmf-13579.wav & arecord -r 8000 -d 1 recorded.wav" #.format(self.__dtmfFile) audio_loop = SysCommand("command-name", str_cmd) - if audio_loop.execute() == 0:# BUG: Returns -1 but work + if audio_loop.execute() == -1:# BUG: Returns -1 but work lines = audio_loop.getOutput().splitlines() - str_cmd = "multimon -t wav -a DTMF recorded.wav -q 2> /dev/null" + str_cmd = "multimon -t wav -a DTMF recorded.wav -q" dtmf_decoder = SysCommand("command-name", str_cmd) - if dtmf_decoder.execute() == 0: # BUG: Returns -1 but work + a=dtmf_decoder.execute() + if dtmf_decoder.execute() == -1: # BUG: Returns -1 but work self.__raw_out = dtmf_decoder.getOutput() if self.__raw_out == "": return -1 @@ -34,4 +35,4 @@ class Qaudio(unittest.TestCase): else: self.fail("failed: fail playing/recording file") return -1 - return 0 + return 0 \ No newline at end of file diff --git a/test-cli/test/tests/qbutton.py b/test-cli/test/tests/qbutton.py index 72a897e..4718924 100644 --- a/test-cli/test/tests/qbutton.py +++ b/test-cli/test/tests/qbutton.py @@ -5,8 +5,12 @@ import time class Qbutton(unittest.TestCase): - def __init__(self, testname, testfunc, gpio): - if gpio == "SOPA": + def __init__(self, testname, testfunc, varlist): + if "gpio" in varlist: + self.__gpio = varlist["gpio"] + else: + raise Exception('gpio param inside Qbutton must be defined') + if self.__gpio == "SOPA": super(Qbutton, self).__init__("buttonSopa") else: super(Qbutton, self).__init__("buttonGpio") @@ -34,19 +38,22 @@ class Qbutton(unittest.TestCase): get_button_val = SysCommand("get_button_val", str_cmd) print("\n\t --> PRESS button for 1 sec (TIMEOUT: 10s) \n") timeout = 0 - while timeout < 20: + while timeout < 7200: if get_button_val.execute() == 0: get_button_val.execute() button_value = get_button_val.getOutput() button_value=button_value.decode('ascii').split("x") if int(button_value[1]) == 4: - timeout = 20 + timeout = 7200 + led_off="echo 0 > /sys/class/leds/red\:usbhost/brightness" + ledoff = SysCommand("led_off", led_off) + ledoff.execute() time.sleep(0.5) timeout = timeout + 1 - if timeout==20 and int(button_value[1]) == 0: + if timeout==7200 and int(button_value[1]) == 0: self.fail("failed: timeout exceeded") else: - timeout = 20 + timeout = 7200 self.fail("failed: not button input") else: self.fail("failed: could not complete i2c reset button state") diff --git a/test-cli/test/tests/qduplex_ser.py b/test-cli/test/tests/qduplex_ser.py index 98bda81..837b4d0 100644 --- a/test-cli/test/tests/qduplex_ser.py +++ b/test-cli/test/tests/qduplex_ser.py @@ -6,15 +6,26 @@ import time class Qduplex(unittest.TestCase): - def __init__(self, testname, testfunc, port1, port2, baudrate): + def __init__(self, testname, testfunc, varlist): super(Qduplex, self).__init__(testfunc) - self.__port1 = port1 + if "port1" in varlist: + self.__port1 = varlist["port1"] + else: + raise Exception('port1 param inside Qduplex must be defined') self.__serial1 = serial.Serial(self.__port1, timeout=1) - self.__serial1.baudrate = baudrate - self.__port2 = port2 + if "port2" in varlist: + self.__port2 = varlist["port2"] + else: + raise Exception('port2 param inside Qduplex must be defined') self.__serial2 = serial.Serial(self.__port2, timeout=1) - self.__serial2.baudrate = baudrate + + if "baudrate" in varlist: + self.__serial1.baudrate = varlist["baudrate"] + self.__serial2.baudrate = varlist["baudrate"] + else: + raise Exception('baudrate param inside Qduplex must be defined') + self._testMethodDoc = testname def __del__(self): diff --git a/test-cli/test/tests/qeeprom.py b/test-cli/test/tests/qeeprom.py index f72f78f..2bab248 100644 --- a/test-cli/test/tests/qeeprom.py +++ b/test-cli/test/tests/qeeprom.py @@ -4,7 +4,7 @@ import uuid class Qeeprom(unittest.TestCase): - def __init__(self, testname, testfunc): + def __init__(self, testname, testfunc, varlist): super(Qeeprom, self).__init__(testfunc) self._testMethodDoc = testname diff --git a/test-cli/test/tests/qethernet.py b/test-cli/test/tests/qethernet.py index 2ac447c..be984f5 100644 --- a/test-cli/test/tests/qethernet.py +++ b/test-cli/test/tests/qethernet.py @@ -1,57 +1,51 @@ -from test.helpers.syscmd import SysCommand import unittest - +import sh +import ex class Qethernet(unittest.TestCase): __sip = None - __raw_out = None - __MB_req = None - __MB_real = None - __BW_real = None - __dat_list = None + __numbytestx = None __bind = None __OKBW = None - def __init__(self, testname, testfunc, sip = None, OKBW=100, bind=None): + def __init__(self, testname, testfunc, varlist): super(Qethernet, self).__init__(testfunc) - if sip is not None: - self.__sip = sip - if sip is not None: - self.__bind = bind - self.__MB_req = '10' - self.__OKBW=OKBW + if "sip" in varlist: + self.__sip = varlist["sip"] + else: + raise Exception('sip param inside Qethernet have been be defined') + if "bind" in varlist: + self.__bind = varlist["bind"] + else: + self.__bind = None + if "OKBW" in varlist: + self.__OKBW = varlist["OKBW"] + else: + raise Exception('OKBW param inside Qethernet must be defined') + self.__numbytestx = "10M" self._testMethodDoc = testname def execute(self): - print + # execute iperf command against the server if self.__bind is None: - str_cmd = "iperf -c {} -x CMSV -n {}M".format(self.__sip, self.__MB_req) + p = sh.iperf("-c", self.__sip, "-x", "CMSV", "-n", self.__numbytestx, "-f", "m") else: - str_cmd = "iperf -c {} -x CMSV -n {}M -B {}".format(self.__sip, self.__MB_req, self.__bind) - iperf_command = SysCommand("iperf", str_cmd) - if iperf_command.execute() == 0: - self.__raw_out = iperf_command.getOutput() - if self.__raw_out == "": - return -1 - lines = iperf_command.getOutput().splitlines() - dat = lines[1] - dat = dat.decode('ascii') - dat_list = dat.split( ) - for d in dat_list: - a = dat_list.pop(0) - if a == "sec": - break - self.__MB_real = dat_list[0] - self.__BW_real = dat_list[2] - self.__dat_list = dat_list - #print(self.__MB_real) - #print(self.__BW_real) - self.failUnless(float(self.__BW_real)>float(self.__OKBW)*0.9,"failed: speed is lower than spected. Speed(MB/s)" + str(self.__BW_real)) + p = sh.iperf("-c", self.__sip, "-x", "CMSV", "-n", self.__numbytestx, "-f", "m", "-B", self.__bind) + #check if it was executed succesfully + if p.exit_code == 0: + if p.stdout == "": + self.fail("failed: error executing iperf command") + # analyze output string + # split by lines + lines = p.stdout.splitlines() + # get first line + dat = lines[1].decode('ascii') + # search for the BW value + a = re.search("\d+(\.\d)? Mbits/sec",dat) + b = a.group().split( ) + BWreal = b[0] + + # check if BW is in the expected range + self.failUnless(float(BWreal)>float(self.__OKBW)*0.9,"failed: speed is lower than spected. Speed(MB/s)" + str(BWreal)) else: self.fail("failed: could not complete iperf command") - - def get_Total_MB(self): - return self.__MB_real; - - def get_Total_BW(self): - return self.__MB_real; diff --git a/test-cli/test/tests/qflash.py b/test-cli/test/tests/qflash.py index cdc4109..0c3fcb5 100644 --- a/test-cli/test/tests/qflash.py +++ b/test-cli/test/tests/qflash.py @@ -4,16 +4,13 @@ from test.helpers.globalVariables import globalVar class Qflasher(unittest.TestCase): - def __init__(self, testname, testfunc): + def __init__(self, testname, testfunc, varlist): super(Qflasher, self).__init__(testfunc) self._testMethodDoc = testname model=globalVar.g_mid if model.find("IGEP0046") == 0: self._flash_method = "mx6" self._binlocation="/boot/" - elif model.find("IGEP0000") == 0: - self._flash_method = "mx6" - self._binlocation="/boot/" elif model.find("IGEP0034") == 0: self._flash_method = "nandti" self._binlocation = "/boot/" diff --git a/test-cli/test/tests/qi2c.py b/test-cli/test/tests/qi2c.py index 409005c..2f14424 100644 --- a/test-cli/test/tests/qi2c.py +++ b/test-cli/test/tests/qi2c.py @@ -3,10 +3,16 @@ import unittest class Qi2c(unittest.TestCase): - def __init__(self, testname, testfunc, busnum, register): + def __init__(self, testname, testfunc, varlist): super(Qi2c, self).__init__(testfunc) - self.__busnum = busnum - self.__register = register.split("/") + if "busnum" in varlist: + self.__busnum = varlist["busnum"] + else: + raise Exception('busnum param inside Qi2c must be defined') + if "register" in varlist: + self.__register = varlist["register"].split("/") + else: + raise Exception('register param inside Qi2c must be defined') self.__devices=[] self._testMethodDoc = testname diff --git a/test-cli/test/tests/qnand.py b/test-cli/test/tests/qnand.py new file mode 100644 index 0000000..9f2cd47 --- /dev/null +++ b/test-cli/test/tests/qnand.py @@ -0,0 +1,22 @@ +import unittest +import sh + +class Qnand(unittest.TestCase): + + __device = "10M" + + # varlist: device + def __init__(self, testname, testfunc, varlist): + super(Qnand, self).__init__(testfunc) + + if "device" in varlist: + self.__device = varlist["device"] + else: + raise Exception('device param inside Qnand must be defined') + self._testMethodDoc = testname + + def execute(self): + try: + sh.nandtest("-m", self.__device) + except sh.ErrorReturnCode as e: + self.fail("failed: could not complete nandtest command") diff --git a/test-cli/test/tests/qram.py b/test-cli/test/tests/qram.py index 8ec0210..1b66e5c 100644 --- a/test-cli/test/tests/qram.py +++ b/test-cli/test/tests/qram.py @@ -1,22 +1,27 @@ -from test.helpers.syscmd import SysCommand import unittest +import sh class Qram(unittest.TestCase): - def __init__(self, testname, testfunc, memSize): + __memSize = "10M" + __loops = "1" + + # varlist: memSize, loops + def __init__(self, testname, testfunc, varlist): super(Qram, self).__init__(testfunc) - self.__memSize = memSize + + if "memSize" in varlist: + self.__memSize = varlist["memSize"] + else: + raise Exception('memSize param inside Qram must be defined') + if "loops" in varlist: + self.__loops = varlist["loops"] + else: + raise Exception('loops param inside Qram must be defined') self._testMethodDoc = testname def execute(self): - str_cmd= "free -m" - free_command = SysCommand("free_ram", str_cmd) - if free_command.execute() == 0: - self.__raw_out = free_command.getOutput() - if self.__raw_out == "": - return -1 - lines = free_command.getOutput().splitlines() - aux = [int(s) for s in lines[1].split() if s.isdigit()] - self.failUnless(int(aux[0])>int(self.__memSize),"failed: total ram memory size lower than expected") - else: - self.fail("failed: could not complete iperf command") + try: + sh.memtester(self.__memSize, "1") + except sh.ErrorReturnCode as e: + self.fail("failed: could not complete memtester command") diff --git a/test-cli/test/tests/qrtc.py b/test-cli/test/tests/qrtc.py index 1d02f78..8e31572 100644 --- a/test-cli/test/tests/qrtc.py +++ b/test-cli/test/tests/qrtc.py @@ -4,9 +4,14 @@ import time class Qrtc(unittest.TestCase): - def __init__(self, testname, testfunc, rtc): + __rtc = "/dev/rtc0" + + def __init__(self, testname, testfunc, varlist): super(Qrtc, self).__init__(testfunc) - self.__rtc = rtc + if "rtc" in varlist: + self.__rtc = varlist["rtc"] + else: + raise Exception('rtc param inside Qrtc must be defined') self._testMethodDoc = testname def execute(self): diff --git a/test-cli/test/tests/qscreen.py b/test-cli/test/tests/qscreen.py index b8a5a48..87e53b2 100644 --- a/test-cli/test/tests/qscreen.py +++ b/test-cli/test/tests/qscreen.py @@ -5,9 +5,13 @@ from test.helpers.cv_display_test import pattern_detect class Qscreen(unittest.TestCase): - def __init__(self, testname, testfunc, display): + #varlist: display + def __init__(self, testname, testfunc, varlist): super(Qscreen, self).__init__(testfunc) - self.__display = display + if "display" in varlist: + self.__display = varlist["display"] + else: + raise Exception('display param inside Qscreen have been be defined') self._testMethodDoc = testname def execute(self): @@ -17,15 +21,5 @@ class Qscreen(unittest.TestCase): test_screen = pattern_detect(1) if not test_screen=="0": self.fail("failed: {}".format(test_screen)) - str_cmd= "fbi -T 1 /home/root/result_hdmi_img.jpg -d /dev/fb0 --noverbose -a" - show_img = SysCommand("show-image", str_cmd) - show_img.execute() else: self.fail("failed: could not display the image") - try: - str_cmd= "fbi -T 1 /home/root/result_hdmi_img.jpg -d /dev/fb0 --noverbose -a" - show_img = SysCommand("show-image", str_cmd) - show_img.execute() - except ValueError: - print("COULD NOT DISPLAY IMAGE") - diff --git a/test-cli/test/tests/qserial.py b/test-cli/test/tests/qserial.py index 43ba3c8..d3e2ee6 100644 --- a/test-cli/test/tests/qserial.py +++ b/test-cli/test/tests/qserial.py @@ -6,11 +6,17 @@ import time class Qserial(unittest.TestCase): - def __init__(self, testname, testfunc, port, baudrate): + def __init__(self, testname, testfunc, varlist): super(Qserial, self).__init__(testfunc) - self.__port = port + if "port" in varlist: + self.__port = varlist["port"] + else: + raise Exception('port param inside Qserial must be defined') self.__serial = serial.Serial(self.__port, timeout=1) - self.__serial.baudrate = baudrate + if "baudrate" in varlist: + self.__baudrate = varlist["baudrate"] + else: + raise Exception('baudrate param inside Qserial must be defined') self._testMethodDoc = testname def __del__(self): @@ -19,12 +25,15 @@ class Qserial(unittest.TestCase): def execute(self): self.__serial.flushInput() self.__serial.flushOutput() + #generate a random uuid test_uuid = str(uuid.uuid4()).encode() + #send the uuid through serial port self.__serial.write(test_uuid) time.sleep(0.05) # there might be a small delay if self.__serial.inWaiting() == 0: self.fail("failed: PORT {} wait timeout exceded, wrong communication?".format(self.__port)) else: + # check if what it was sent is equal to what has been received if (self.__serial.readline() != test_uuid): self.fail("failed: PORT {} write/read mismatch".format(self.__port)) diff --git a/test-cli/test/tests/qusb.py b/test-cli/test/tests/qusb.py index 44490bc..0390143 100644 --- a/test-cli/test/tests/qusb.py +++ b/test-cli/test/tests/qusb.py @@ -3,17 +3,20 @@ import unittest class Qusb(unittest.TestCase): - def __init__(self, testname, testfunc, devLabel, numPorts): + def __init__(self, testname, testfunc, varlist): super(Qusb, self).__init__(testfunc) - self.__numPorts = numPorts + if "numPorts" in varlist: + self.__numPorts = varlist["numPorts"] + else: + raise Exception('numPorts param inside Qusb must be defined') self._testMethodDoc = testname - self.__devLabel = devLabel + if "devLabel" in varlist: + self.__devLabel = varlist["devLabel"] + else: + raise Exception('devLabel param inside Qusb must be defined') if testname=="USBOTG": self.__usbFileName = "/this_is_an_usb_otg" self.__usbtext = "USBOTG" - elif testname=="SATA": - self.__usbFileName = "/this_is_a_sata" - self.__usbtext = "SATA" else: self.__usbFileName = "/this_is_an_usb_host" self.__usbtext = "USBHOST" @@ -57,4 +60,4 @@ class Qusb(unittest.TestCase): else: self.fail("failed: reference and real usb host devices number mismatch") else: - self.fail("failed: couldn't execute lsblk command") + self.fail("failed: couldn't execute lsblk command") \ No newline at end of file diff --git a/test-cli/test/tests/qwifi.py b/test-cli/test/tests/qwifi.py index d08149b..188e300 100644 --- a/test-cli/test/tests/qwifi.py +++ b/test-cli/test/tests/qwifi.py @@ -1,45 +1,33 @@ from test.helpers.syscmd import SysCommand import unittest -import subprocess class Qwifi(unittest.TestCase): - def __init__(self, testname, testfunc, signal): + def __init__(self, testname, testfunc, varlist): super(Qwifi, self).__init__(testfunc) - self.__signal = signal + if "signal" in varlist: + self.__signal = varlist["signal"] + else: + raise Exception('signal param inside Qwifi must be defined') self._testMethodDoc = testname - # WiFi SERVERIP fixed at the moment. - self._serverip = "192.168.5.1" def execute(self): - # First check connection with the wifi server using ping command - #str_cmd = "ping -c 1 {} > /dev/null".format(self._serverip) - #wifi_ping = SysCommand("wifi_ping", str_cmd) - #wifi_ping.execute() - #res = subprocess.call(['ping', '-c', '1', self._serverip]) - p = subprocess.Popen(['ping','-c','1',self._serverip,'-W','2'],stdout=subprocess.PIPE) - p.wait() - res=p.poll() - if res == 0: - str_cmd= "iw wlan0 link" - wifi_stats = SysCommand("wifi_stats", str_cmd) - if wifi_stats.execute() == 0: - w_stats = wifi_stats.getOutput().decode('ascii').splitlines() - #self._longMessage = str(self.__raw_out).replace("'", "") - if not w_stats[0] == "Not connected.": - signal_st = w_stats[5].split(" ")[1] - try: - int(signal_st) - if -1*int(signal_st) > int(self.__signal): - self.fail("failed: signal to server lower than expected") - except ValueError: - self.fail("failed: error output (Bad connection?)") - else: + str_cmd= "iw wlan0 link" + wifi_stats = SysCommand("wifi_stats", str_cmd) + if wifi_stats.execute() == 0: + w_stats = wifi_stats.getOutput().decode('ascii').splitlines() + #self._longMessage = str(self.__raw_out).replace("'", "") + if not w_stats[0] == "Not connected.": + signal_st = w_stats[5].split(" ")[1] + try: + int(signal_st) + if -1*int(signal_st) > int(self.__signal): + self.fail("failed: signal to server lower than expected") + except ValueError: self.fail("failed: error output (Bad connection?)") - #tx_brate = float(w_stats[6].split(" ")[2]) else: - self.fail("failed: couldn't execute iw command") + self.fail("failed: error output (Bad connection?)") + #tx_brate = float(w_stats[6].split(" ")[2]) else: - self.fail("failed: ping to server {}".format(self._serverip)) - + self.fail("failed: couldn't execute iw command") -- cgit v1.1 From 7490324bc98248fc82be814920e2deff4114acc8 Mon Sep 17 00:00:00 2001 From: Manel Caro Date: Wed, 4 Mar 2020 19:38:10 +0100 Subject: Added station --- test-cli/test/helpers/testsrv_db.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'test-cli/test') diff --git a/test-cli/test/helpers/testsrv_db.py b/test-cli/test/helpers/testsrv_db.py index f08cb17..7ed02f3 100644 --- a/test-cli/test/helpers/testsrv_db.py +++ b/test-cli/test/helpers/testsrv_db.py @@ -119,9 +119,9 @@ class TestSrv_Database(object): #print(r) return None - def open_testbatch(self, board_uuid): + def open_testbatch(self, board_uuid, station): '''get the board test list''' - sql = "SELECT isee.open_testbatch('{}')".format(board_uuid) + sql = "SELECT * FROM isee.open_testbatch('{}','{}')".format(board_uuid, station) #print('>>>' + sql) try: res = str(self.__sqlObject.db_execute_query(sql)[0]) -- cgit v1.1 From 23e0cea58ba6ac5357db507b0ac7f8dfcf223326 Mon Sep 17 00:00:00 2001 From: Manel Caro Date: Wed, 4 Mar 2020 19:38:24 +0100 Subject: Modify typos --- test-cli/test/helpers/get_dieid.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) (limited to 'test-cli/test') diff --git a/test-cli/test/helpers/get_dieid.py b/test-cli/test/helpers/get_dieid.py index 029ddb5..48e724e 100644 --- a/test-cli/test/helpers/get_dieid.py +++ b/test-cli/test/helpers/get_dieid.py @@ -1,8 +1,11 @@ import mmap import os import struct + MAP_MASK = mmap.PAGESIZE - 1 WORD = 4 + + def read(addr): """ Read from any location in memory Returns the readed value in hexadecimal format @@ -30,8 +33,8 @@ def getRegisters(model): return registers def genDieid(modelid): - registers=getRegisters(modelid) - id="" + registers = getRegisters(modelid) + id = "" for i in range(len(registers)): id=id+(read(registers[i])) return id -- cgit v1.1 From a615dac03a9ea7897bf3947ba8d31278b2cea121 Mon Sep 17 00:00:00 2001 From: Hector Fernandez Date: Thu, 5 Mar 2020 16:29:31 +0100 Subject: Modify tests. --- test-cli/test/tests/qeeprom.py | 62 +++++++++++++++------------- test-cli/test/tests/qethernet.py | 24 +++++++---- test-cli/test/tests/qwifi.py | 88 +++++++++++++++++++++++++++++++--------- 3 files changed, 118 insertions(+), 56 deletions(-) (limited to 'test-cli/test') diff --git a/test-cli/test/tests/qeeprom.py b/test-cli/test/tests/qeeprom.py index 2bab248..5bb0755 100644 --- a/test-cli/test/tests/qeeprom.py +++ b/test-cli/test/tests/qeeprom.py @@ -1,38 +1,44 @@ -from test.helpers.syscmd import SysCommand +import sh import unittest -import uuid + class Qeeprom(unittest.TestCase): + __position = None + __uuid = None + __eeprompath = None + + # varlist: position, uuid, eeprompath def __init__(self, testname, testfunc, varlist): super(Qeeprom, self).__init__(testfunc) self._testMethodDoc = testname + if "position" in varlist: + self.__position = varlist["position"] + else: + raise Exception('position param inside Qeeprom must be defined') + if "uuid" in varlist: + self.__uuid = varlist["uuid"] + else: + raise Exception('uuid param inside Qeeprom must be defined') + if "eeprompath" in varlist: + self.__eeprompath = varlist["eeprompath"] + else: + raise Exception('eeprompath param inside Qeeprom must be defined') def execute(self): - str_cmd = "find /sys/ -iname 'eeprom'" - eeprom_location = SysCommand("eeprom_location", str_cmd) - if eeprom_location.execute() == 0: - self.__raw_out = eeprom_location.getOutput() - if self.__raw_out == "": - self.fail("Unable to get EEPROM location. IS EEPROM CONNECTED?") - return -1 - eeprom=self.__raw_out.decode('ascii') - test_uuid = uuid.uuid4() - str_cmd="echo '{}' > {}".format(str(test_uuid), eeprom) - eeprom_write = SysCommand("eeprom_write", str_cmd) - if eeprom_write.execute() == 0: - self.__raw_out = eeprom_write.getOutput() - if self.__raw_out == "": - self.fail("Unable to write on the EEPROM?") - return -1 - str_cmd = "head -2 {}".format(eeprom) - eeprom_read = SysCommand("eeprom_read", str_cmd) - if eeprom_read.execute() == 0: - self.__raw_out = eeprom_read.getOutput() - if self.__raw_out == "": - self.fail("Unable to read from the EEPROM?") - return -1 - if(str(self.__raw_out).find(str(test_uuid)) == -1): - self.fail("failed: READ/WRITE mismatch") + # write data into the eeprom + p = sh.dd(sh.echo(self._uuid), "of=" + self.__eeprompath, "bs=1", "seek=" + self.__position) + if p.exit_code == 0: + # read data from the eeprom + p = sh.dd("if=" + self.__eeprompath, "bs=1", "skip=" + self.__position, "count=" + len(self.__uuid)) + if p.exit_code == 0: + uuid_rx = p.stdout.decode('ascii') + # compare both values + if (uuid_rx != self.__uuid): + self.fail("failed: mismatch between written and received values.") + + else: + self.fail("failed: Unable to read from the EEPROM device.") else: - self.fail("failed: could not complete find eeprom command") + self.fail("failed: Unable to write on the EEPROM device.") + diff --git a/test-cli/test/tests/qethernet.py b/test-cli/test/tests/qethernet.py index be984f5..22d796c 100644 --- a/test-cli/test/tests/qethernet.py +++ b/test-cli/test/tests/qethernet.py @@ -1,12 +1,14 @@ import unittest import sh -import ex +import re + class Qethernet(unittest.TestCase): __sip = None __numbytestx = None __bind = None __OKBW = None + __port = None def __init__(self, testname, testfunc, varlist): super(Qethernet, self).__init__(testfunc) @@ -22,16 +24,21 @@ class Qethernet(unittest.TestCase): self.__OKBW = varlist["OKBW"] else: raise Exception('OKBW param inside Qethernet must be defined') + if "port" in varlist: + self.__port = varlist["port"] + else: + raise Exception('port param inside Qethernet must be defined') self.__numbytestx = "10M" self._testMethodDoc = testname def execute(self): # execute iperf command against the server if self.__bind is None: - p = sh.iperf("-c", self.__sip, "-x", "CMSV", "-n", self.__numbytestx, "-f", "m") + p = sh.iperf("-c", self.__sip, "-x", "CMSV", "-n", self.__numbytestx, "-f", "m", "-p", self.__port) else: - p = sh.iperf("-c", self.__sip, "-x", "CMSV", "-n", self.__numbytestx, "-f", "m", "-B", self.__bind) - #check if it was executed succesfully + p = sh.iperf("-c", self.__sip, "-x", "CMSV", "-n", self.__numbytestx, "-f", "m", "-p", self.__port, "-B", + self.__bind) + # check if it was executed succesfully if p.exit_code == 0: if p.stdout == "": self.fail("failed: error executing iperf command") @@ -41,11 +48,12 @@ class Qethernet(unittest.TestCase): # get first line dat = lines[1].decode('ascii') # search for the BW value - a = re.search("\d+(\.\d)? Mbits/sec",dat) - b = a.group().split( ) - BWreal = b[0] + a = re.search("\d+(\.\d)? Mbits/sec", dat) + b = a.group().split() + bwreal = b[0] # check if BW is in the expected range - self.failUnless(float(BWreal)>float(self.__OKBW)*0.9,"failed: speed is lower than spected. Speed(MB/s)" + str(BWreal)) + self.failUnless(float(bwreal) > float(self.__OKBW) * 0.9, + "failed: speed is lower than spected. Speed(MB/s)" + str(bwreal)) else: self.fail("failed: could not complete iperf command") diff --git a/test-cli/test/tests/qwifi.py b/test-cli/test/tests/qwifi.py index 188e300..154dd52 100644 --- a/test-cli/test/tests/qwifi.py +++ b/test-cli/test/tests/qwifi.py @@ -1,33 +1,81 @@ -from test.helpers.syscmd import SysCommand import unittest +import sh +import re + class Qwifi(unittest.TestCase): + __sip = None + __numbytestx = None + __bind = None + __OKBW = None + __port = None + #varlist: sip, bind, OKBW, port def __init__(self, testname, testfunc, varlist): super(Qwifi, self).__init__(testfunc) - if "signal" in varlist: - self.__signal = varlist["signal"] + if "sip" in varlist: + self.__sip = varlist["sip"] + else: + raise Exception('sip param inside Qwifi have been be defined') + if "OKBW" in varlist: + self.__OKBW = varlist["OKBW"] + else: + raise Exception('OKBW param inside Qwifi must be defined') + if "port" in varlist: + self.__port = varlist["port"] else: - raise Exception('signal param inside Qwifi must be defined') + raise Exception('port param inside Qwifi must be defined') + if "bind" in varlist: + self.__bind = varlist["bind"] + else: + self.__bind = None + self.__numbytestx = "10M" self._testMethodDoc = testname def execute(self): - str_cmd= "iw wlan0 link" - wifi_stats = SysCommand("wifi_stats", str_cmd) - if wifi_stats.execute() == 0: - w_stats = wifi_stats.getOutput().decode('ascii').splitlines() - #self._longMessage = str(self.__raw_out).replace("'", "") - if not w_stats[0] == "Not connected.": - signal_st = w_stats[5].split(" ")[1] - try: - int(signal_st) - if -1*int(signal_st) > int(self.__signal): - self.fail("failed: signal to server lower than expected") - except ValueError: - self.fail("failed: error output (Bad connection?)") + # check if the board is connected to the router by wifi + p = sh.iw("wlan0", "link") + if p.exit_code == 0: + # get the first line of the output stream + out1 = p.stdout.decode('ascii').splitlines()[0] + if out1 != "Not connected.": + #check if the board has ip in the wlan0 interface + p = sh.ifconfig("wlan0") + if p.exit_code == 0: + result = re.search("inet addr:(?!127\.0{1,3}\.0{1,3}\.0{0,2}1$)((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)", + p.stdout) + if result: + # execute iperf command against the server + if self.__bind is None: + p = sh.iperf("-c", self.__sip, "-x", "CMSV", "-n", self.__numbytestx, "-f", "m", "-p", + self.__port) + else: + p = sh.iperf("-c", self.__sip, "-x", "CMSV", "-n", self.__numbytestx, "-f", "m", "-p", + self.__port, "-B", self.__bind) + # check if it was executed succesfully + if p.exit_code == 0: + if p.stdout == "": + self.fail("failed: error executing iperf command") + # analyze output string + # split by lines + lines = p.stdout.splitlines() + # get first line + dat = lines[1].decode('ascii') + # search for the BW value + a = re.search("\d+(\.\d)? Mbits/sec", dat) + b = a.group().split() + bwreal = b[0] + + # check if BW is in the expected range + self.failUnless(float(bwreal) > float(self.__OKBW) * 0.9, + "failed: speed is lower than spected. Speed(MB/s)" + str(bwreal)) + else: + self.fail("failed: could not complete iperf command") + else: + self.fail("failed: wlan0 interface doesn't have any ip address.") + else: + self.fail("failed: could not complete ifconfig command.") else: - self.fail("failed: error output (Bad connection?)") - #tx_brate = float(w_stats[6].split(" ")[2]) + self.fail("failed: wifi module is not connected to the router.") else: self.fail("failed: couldn't execute iw command") - -- cgit v1.1 From dd9ffc52507c391271d0821636c683fd7562b46a Mon Sep 17 00:00:00 2001 From: Hector Fernandez Date: Thu, 5 Mar 2020 18:50:47 +0100 Subject: Modified postgre functions. --- test-cli/test/helpers/testsrv_db.py | 155 ++++++++++-------------------------- test-cli/test/runners/simple.py | 6 -- test-cli/test/tests/qeeprom.py | 17 ++-- 3 files changed, 51 insertions(+), 127 deletions(-) (limited to 'test-cli/test') diff --git a/test-cli/test/helpers/testsrv_db.py b/test-cli/test/helpers/testsrv_db.py index 7ed02f3..b7b75b1 100644 --- a/test-cli/test/helpers/testsrv_db.py +++ b/test-cli/test/helpers/testsrv_db.py @@ -1,10 +1,10 @@ from test.helpers.psqldb import PgSQLConnection -from test.helpers.setup_xml import XMLSetup -def find_between( s, first, last ): + +def find_between(s, first, last): try: - start = s.index( first ) + len( first ) - end = s.index( last, start ) + start = s.index(first) + len(first) + end = s.index(last, start) return s[start:end] except ValueError: return "" @@ -19,157 +19,90 @@ class TestSrv_Database(object): def __init__(self): pass - def open (self, xmlObj): - self.__xml_setup = xmlObj; + def open(self, xmlObj): + self.__xml_setup = xmlObj self.__sqlObject = PgSQLConnection() return self.__sqlObject.db_connect(self.__xml_setup.getdbConnectionStr()) - - def create_board(self, processor_id, model_id, variant, bmac = None): + def create_board(self, processor_id, model_id, variant, station, bmac=None): '''create a new board''' if bmac is None: - sql = "SELECT isee.create_board('{}', '{}', '{}', NULL);".format(processor_id, model_id, variant) + sql = "SELECT isee.f_create_board('{}', '{}', '{}', NULL, '{}');".format(processor_id, model_id, variant, + station) else: - sql = "SELECT isee.create_board('{}', '{}', '{}', '{}');".format(processor_id, model_id, variant, bmac) - #print('>>>' + sql) - try: - res = self.__sqlObject.db_execute_query(sql) - #print(res) - return res[0][0]; - except Exception as err: - r = find_between(str(err), '#', '#') - #print(r) - return None - - def create_model(self, modid, variant, descr, tgid): - '''create new model''' - sql = "SELECT isee.create_model('{}', '{}', '{}', '{}')".format(modid, variant, descr, tgid) - #print('>>>' + sql) - try: - res = self.__sqlObject.db_execute_query(sql) - #print(res) - return res[0][0]; - except Exception as err: - r = find_between(str(err), '#', '#') - #print(r) - return None - - def create_test_definition(self, testname, testdesc, testfunc): - '''Create a new definition and return definition id on fail (testname already exist) return -1''' - sql = "SELECT isee.define_test('{}', '{}', '{}')".format(testname, testdesc, testfunc) - #print('>>>' + sql) - try: - res = self.__sqlObject.db_execute_query(sql) - #print(res) - return res[0][0]; - except Exception as err: - r = find_between(str(err), '#', '#') - #print(r) - return None - - def add_testdef_to_group(self, testgroupid, testname, testparam): - '''Assign definition to group test return true on success or false if it fails''' - sql = "SELECT isee.add_test_to_group('{}', '{}', '{}')".format(testgroupid, testname, testparam) - #print('>>>' + sql) + sql = "SELECT isee.f_create_board('{}', '{}', '{}', '{}', '{}');".format(processor_id, model_id, variant, + bmac, station) + # print('>>>' + sql) try: res = self.__sqlObject.db_execute_query(sql) - #print(res) - return res[0][0]; + # print(res) + return res[0][0] except Exception as err: r = find_between(str(err), '#', '#') - #print(r) + # print(r) return None - def getboard_test_list(self, board_uuid): + def get_tests_list(self, board_uuid): '''get the board test list''' - sql = "SELECT isee.gettestlist('{}')".format(board_uuid) - #print('>>>' + sql) + sql = "SELECT * FROM isee.f_get_tests_list('{}')".format(board_uuid) + # print('>>>' + sql) try: res = self.__sqlObject.db_execute_query(sql) - #print(res) + # print(res) return res; except Exception as err: r = find_between(str(err), '#', '#') - #print(r) + # print(r) return None - def getboard_comp_test_list(self, board_uuid): + def get_test_params_list(self, testid): '''get the board test list''' - sql = "SELECT * FROM isee.gettestcompletelist('{}')".format(board_uuid) - #print('>>>' + sql) + sql = "SELECT * FROM isee.f_get_test_params_list('{}')".format(testid) + # print('>>>' + sql) try: res = self.__sqlObject.db_execute_query(sql) - #print(res) - return res; + # print(res) + return res except Exception as err: r = find_between(str(err), '#', '#') - #print(r) + # print(r) return None - def getboard_test_variables(self, board_uuid, testdefid): + def open_test(self, board_uuid): '''get the board test list''' - sql = "SELECT * FROM isee.getboardtestvariables('{}', '{}')".format(board_uuid, testdefid) - #print('>>>' + sql) + sql = "SELECT * FROM isee.f_open_test('{}')".format(board_uuid) + # print('>>>' + sql) try: res = self.__sqlObject.db_execute_query(sql) - #print(res) - return res; - except Exception as err: - r = find_between(str(err), '#', '#') - #print(r) - return None - - def open_testbatch(self, board_uuid, station): - '''get the board test list''' - sql = "SELECT * FROM isee.open_testbatch('{}','{}')".format(board_uuid, station) - #print('>>>' + sql) - try: - res = str(self.__sqlObject.db_execute_query(sql)[0]) - res = res.replace('(', '') - res = res.replace(')', '') - res = res.replace(',', '') - #print(res) - return res; + # print(res) + return res except Exception as err: r = find_between(str(err), '#', '#') - #print(r) + # print(r) return None - def add_test_to_batch(self, board_uuid, testid, testid_ctl, result, groupid, data): + def run_test(self, testid_ctl, testid): '''get the board test list''' - sql = "SELECT isee.add_test_to_batch_c('{}','{}','{}','{}','{}','{}')".format(board_uuid, testid, testid_ctl, result, groupid, data) - #print('>>>' + sql) + sql = "SELECT * FROM isee.f_run_test('{}','{}')".format(testid_ctl, testid) + # print('>>>' + sql) try: res = self.__sqlObject.db_execute_query(sql) - #print(res) - return res; + # print(res) + return res except Exception as err: r = find_between(str(err), '#', '#') - #print(r) + # print(r) return None - def close_testbatch(self, board_uuid, testid_ctl): + def finish_test(self, testid_ctl, testid, newstatus): '''get the board test list''' - sql = "SELECT isee.close_testbatch('{}','{}')".format(board_uuid, testid_ctl) - #print('>>>' + sql) + sql = "SELECT * FROM isee.f_finish_test('{}','{}','{}')".format(testid_ctl, testid, newstatus) + # print('>>>' + sql) try: res = self.__sqlObject.db_execute_query(sql) - #print(res) - return res; + # print(res) + return res except Exception as err: r = find_between(str(err), '#', '#') - #print(r) + # print(r) return None - - def update_set_test_row(self, nstation, testid_ctl, board_uuid, ctest, cstatus): - '''get the board test list''' - sql = "SELECT isee.update_set_test_row('{}','{}','{}','{}','{}')".format(nstation, testid_ctl ,board_uuid, ctest, cstatus) - #print('>>>' + sql) - try: - res = self.__sqlObject.db_execute_query(sql) - #print(res) - return res; - except Exception as err: - r = find_between(str(err), '#', '#') - #print(r) - return None \ No newline at end of file diff --git a/test-cli/test/runners/simple.py b/test-cli/test/runners/simple.py index 3537d0e..084a5b8 100644 --- a/test-cli/test/runners/simple.py +++ b/test-cli/test/runners/simple.py @@ -89,12 +89,6 @@ class TextTestResult(unittest.TestResult): dbdata['name'] = test.shortDescription() dbdata['result'] = self.result dbdata['msg'] = str(test.longMessage) - #DB: INSERT IN THE DATABASE - filename='test_results.dat' - testResult = open(filename, 'a') - testResult.write(str(dbdata)) - testResult.write("\n") - testResult.close() #CONVERT FANCY FAIL AND PASS if self.result==self.PASS: simple_result="TRUE" if self.result == self.FAIL: simple_result = "FALSE" diff --git a/test-cli/test/tests/qeeprom.py b/test-cli/test/tests/qeeprom.py index 5bb0755..c2293c2 100644 --- a/test-cli/test/tests/qeeprom.py +++ b/test-cli/test/tests/qeeprom.py @@ -5,10 +5,9 @@ import unittest class Qeeprom(unittest.TestCase): __position = None - __uuid = None __eeprompath = None - # varlist: position, uuid, eeprompath + # varlist: position, eeprompath def __init__(self, testname, testfunc, varlist): super(Qeeprom, self).__init__(testfunc) self._testMethodDoc = testname @@ -16,25 +15,23 @@ class Qeeprom(unittest.TestCase): self.__position = varlist["position"] else: raise Exception('position param inside Qeeprom must be defined') - if "uuid" in varlist: - self.__uuid = varlist["uuid"] - else: - raise Exception('uuid param inside Qeeprom must be defined') if "eeprompath" in varlist: self.__eeprompath = varlist["eeprompath"] else: raise Exception('eeprompath param inside Qeeprom must be defined') def execute(self): + # generate some data + data_tx = "isee_test" # write data into the eeprom - p = sh.dd(sh.echo(self._uuid), "of=" + self.__eeprompath, "bs=1", "seek=" + self.__position) + p = sh.dd(sh.echo(data_tx), "of=" + self.__eeprompath, "bs=1", "seek=" + self.__position) if p.exit_code == 0: # read data from the eeprom - p = sh.dd("if=" + self.__eeprompath, "bs=1", "skip=" + self.__position, "count=" + len(self.__uuid)) + p = sh.dd("if=" + self.__eeprompath, "bs=1", "skip=" + self.__position, "count=" + len(data_tx)) if p.exit_code == 0: - uuid_rx = p.stdout.decode('ascii') + data_rx = p.stdout.decode('ascii') # compare both values - if (uuid_rx != self.__uuid): + if data_rx != data_tx: self.fail("failed: mismatch between written and received values.") else: -- cgit v1.1 From 98d40cecc9818360984188755e455aa53933aab0 Mon Sep 17 00:00:00 2001 From: Hector Fernandez Date: Fri, 6 Mar 2020 09:38:18 +0100 Subject: changed parameter names of tests --- test-cli/test/tests/qeeprom.py | 2 +- test-cli/test/tests/qethernet.py | 20 ++++++++++---------- test-cli/test/tests/qram.py | 12 ++++++------ 3 files changed, 17 insertions(+), 17 deletions(-) (limited to 'test-cli/test') diff --git a/test-cli/test/tests/qeeprom.py b/test-cli/test/tests/qeeprom.py index c2293c2..acdc1f6 100644 --- a/test-cli/test/tests/qeeprom.py +++ b/test-cli/test/tests/qeeprom.py @@ -27,7 +27,7 @@ class Qeeprom(unittest.TestCase): p = sh.dd(sh.echo(data_tx), "of=" + self.__eeprompath, "bs=1", "seek=" + self.__position) if p.exit_code == 0: # read data from the eeprom - p = sh.dd("if=" + self.__eeprompath, "bs=1", "skip=" + self.__position, "count=" + len(data_tx)) + p = sh.dd("if=" + self.__eeprompath, "bs=1", "skip=" + self.__position, "count=" + str(len(data_tx))) if p.exit_code == 0: data_rx = p.stdout.decode('ascii') # compare both values diff --git a/test-cli/test/tests/qethernet.py b/test-cli/test/tests/qethernet.py index 22d796c..adee67f 100644 --- a/test-cli/test/tests/qethernet.py +++ b/test-cli/test/tests/qethernet.py @@ -4,26 +4,26 @@ import re class Qethernet(unittest.TestCase): - __sip = None + __serverip = None __numbytestx = None __bind = None - __OKBW = None + __bwexpected = None __port = None def __init__(self, testname, testfunc, varlist): super(Qethernet, self).__init__(testfunc) - if "sip" in varlist: - self.__sip = varlist["sip"] + if "serverip" in varlist: + self.__serverip = varlist["serverip"] else: raise Exception('sip param inside Qethernet have been be defined') if "bind" in varlist: self.__bind = varlist["bind"] else: self.__bind = None - if "OKBW" in varlist: - self.__OKBW = varlist["OKBW"] + if "bwexpected" in varlist: + self.__bwexpected = varlist["bwexpected"] else: - raise Exception('OKBW param inside Qethernet must be defined') + raise Exception('bwexpected param inside Qethernet must be defined') if "port" in varlist: self.__port = varlist["port"] else: @@ -34,9 +34,9 @@ class Qethernet(unittest.TestCase): def execute(self): # execute iperf command against the server if self.__bind is None: - p = sh.iperf("-c", self.__sip, "-x", "CMSV", "-n", self.__numbytestx, "-f", "m", "-p", self.__port) + p = sh.iperf("-c", self.__serverip, "-x", "CMSV", "-n", self.__numbytestx, "-f", "m", "-p", self.__port) else: - p = sh.iperf("-c", self.__sip, "-x", "CMSV", "-n", self.__numbytestx, "-f", "m", "-p", self.__port, "-B", + p = sh.iperf("-c", self.__serverip, "-x", "CMSV", "-n", self.__numbytestx, "-f", "m", "-p", self.__port, "-B", self.__bind) # check if it was executed succesfully if p.exit_code == 0: @@ -53,7 +53,7 @@ class Qethernet(unittest.TestCase): bwreal = b[0] # check if BW is in the expected range - self.failUnless(float(bwreal) > float(self.__OKBW) * 0.9, + self.failUnless(float(bwreal) > float(self.__bwexpected) * 0.9, "failed: speed is lower than spected. Speed(MB/s)" + str(bwreal)) else: self.fail("failed: could not complete iperf command") diff --git a/test-cli/test/tests/qram.py b/test-cli/test/tests/qram.py index 1b66e5c..ade7aeb 100644 --- a/test-cli/test/tests/qram.py +++ b/test-cli/test/tests/qram.py @@ -3,17 +3,17 @@ import sh class Qram(unittest.TestCase): - __memSize = "10M" + __memsize = "10M" __loops = "1" - # varlist: memSize, loops + # varlist: memsize, loops def __init__(self, testname, testfunc, varlist): super(Qram, self).__init__(testfunc) - if "memSize" in varlist: - self.__memSize = varlist["memSize"] + if "memsize" in varlist: + self.__memsize = varlist["memsize"] else: - raise Exception('memSize param inside Qram must be defined') + raise Exception('memsize param inside Qram must be defined') if "loops" in varlist: self.__loops = varlist["loops"] else: @@ -22,6 +22,6 @@ class Qram(unittest.TestCase): def execute(self): try: - sh.memtester(self.__memSize, "1") + sh.memtester(self.__memsize, "1") except sh.ErrorReturnCode as e: self.fail("failed: could not complete memtester command") -- cgit v1.1 From 9f07a57d89a927aa9b172c1bf20c7ab563658c73 Mon Sep 17 00:00:00 2001 From: Hector Fernandez Date: Fri, 6 Mar 2020 12:46:27 +0100 Subject: Fixed multiple errors. --- test-cli/test/helpers/get_dieid.py | 44 -------------------------- test-cli/test/helpers/int_registers.py | 56 ++++++++++++++++++++++++++++++++++ test-cli/test/helpers/testsrv_db.py | 26 ++++++++-------- test-cli/test/runners/simple.py | 39 ++++++++--------------- test-cli/test/tests/qamp.py | 25 ++++++++------- test-cli/test/tests/qaudio.py | 35 ++++++++++----------- test-cli/test/tests/qbutton.py | 5 ++- test-cli/test/tests/qduplex_ser.py | 4 ++- test-cli/test/tests/qeeprom.py | 3 +- test-cli/test/tests/qethernet.py | 3 ++ test-cli/test/tests/qflash.py | 3 ++ test-cli/test/tests/qi2c.py | 3 ++ test-cli/test/tests/qiperf.py | 53 -------------------------------- test-cli/test/tests/qnand.py | 5 +-- test-cli/test/tests/qram.py | 5 +-- test-cli/test/tests/qrtc.py | 4 ++- test-cli/test/tests/qscreen.py | 4 ++- test-cli/test/tests/qserial.py | 4 ++- test-cli/test/tests/qusb.py | 28 ++++++++++------- test-cli/test/tests/qwifi.py | 14 +++++---- 20 files changed, 168 insertions(+), 195 deletions(-) delete mode 100644 test-cli/test/helpers/get_dieid.py create mode 100644 test-cli/test/helpers/int_registers.py delete mode 100644 test-cli/test/tests/qiperf.py (limited to 'test-cli/test') diff --git a/test-cli/test/helpers/get_dieid.py b/test-cli/test/helpers/get_dieid.py deleted file mode 100644 index 48e724e..0000000 --- a/test-cli/test/helpers/get_dieid.py +++ /dev/null @@ -1,44 +0,0 @@ -import mmap -import os -import struct - -MAP_MASK = mmap.PAGESIZE - 1 -WORD = 4 - - -def read(addr): - """ Read from any location in memory - Returns the readed value in hexadecimal format - Keyword arguments: - - addr: The memory address to be readed. - """ - fd = os.open("/dev/mem", os.O_RDWR | os.O_SYNC) - # Map one page - mm = mmap.mmap(fd, mmap.PAGESIZE, mmap.MAP_SHARED, mmap.PROT_WRITE | mmap.PROT_READ, offset=addr & ~MAP_MASK) - mm.seek(addr & MAP_MASK) - retval = struct.unpack('I', mm.read(WORD)) - mm.close() - os.close(fd) - return "%08X" % retval[0] - -def getRegisters(model): - if model.find("IGEP0046") == 0: - registers = [0x021BC420, 0x021BC410] - elif model.find("IGEP0034") == 0 or model.find("SOPA0000") == 0: - registers = [0x44e10630, 0x44e10634, 0x44e10638, 0x44e1063C] - elif model.find("OMAP3") == 0: - registers = [0x4830A224, 0x4830A220, 0x4830A21C, 0x4830A218] - elif model.find("OMAP5") == 0: - registers = [0x4A002210, 0x4A00220C, 0x4A002208, 0x4A002200] - return registers - -def genDieid(modelid): - registers = getRegisters(modelid) - id = "" - for i in range(len(registers)): - id=id+(read(registers[i])) - return id - -#if __name__ == "__main__": - #registers = [0x021BC420, 0x021BC410] - #print(main(registers)) diff --git a/test-cli/test/helpers/int_registers.py b/test-cli/test/helpers/int_registers.py new file mode 100644 index 0000000..cf2e35b --- /dev/null +++ b/test-cli/test/helpers/int_registers.py @@ -0,0 +1,56 @@ +import mmap +import os +import struct + +MAP_MASK = mmap.PAGESIZE - 1 +WORD = 4 + + +def read(addr): + """ Read from any location in memory + Returns the readed value in hexadecimal format + Keyword arguments: + - addr: The memory address to be readed. + """ + fd = os.open("/dev/mem", os.O_RDWR | os.O_SYNC) + # Map one page + mm = mmap.mmap(fd, mmap.PAGESIZE, mmap.MAP_SHARED, mmap.PROT_WRITE | mmap.PROT_READ, offset=addr & ~MAP_MASK) + mm.seek(addr & MAP_MASK) + retval = struct.unpack('I', mm.read(WORD)) + mm.close() + os.close(fd) + return "%08X" % retval[0] + + +def get_die_id(modelid): + dieid = "" + + # get registers + if modelid.find("IGEP0046") == 0: + registers = [0x021BC420, 0x021BC410] + elif modelid.find("IGEP0034") == 0 or modelid.find("SOPA0000") == 0: + # registers: mac_id0_lo, mac_id0_hi, mac_id1_lo, mac_id1_hi + registers = [0x44e10630, 0x44e10634, 0x44e10638, 0x44e1063C] + elif modelid.find("OMAP3") == 0: + registers = [0x4830A224, 0x4830A220, 0x4830A21C, 0x4830A218] + elif modelid.find("OMAP5") == 0: + registers = [0x4A002210, 0x4A00220C, 0x4A002208, 0x4A002200] + else: + raise Exception('modelid not defined') + + for rg in registers: + dieid = dieid + read(rg) + return dieid + + +def get_mac(modelid): + mac = None + + if modelid.find("IGEP0034") == 0 or modelid.find("SOPA0000") == 0: + # registers: mac_id0_lo, mac_id0_hi + registers = [0x44e10630, 0x44e10634] + mac = "" + for rg in registers: + mac = mac + read(rg) + + return mac diff --git a/test-cli/test/helpers/testsrv_db.py b/test-cli/test/helpers/testsrv_db.py index b7b75b1..d937d3e 100644 --- a/test-cli/test/helpers/testsrv_db.py +++ b/test-cli/test/helpers/testsrv_db.py @@ -27,11 +27,13 @@ class TestSrv_Database(object): def create_board(self, processor_id, model_id, variant, station, bmac=None): '''create a new board''' if bmac is None: - sql = "SELECT isee.f_create_board('{}', '{}', '{}', NULL, '{}');".format(processor_id, model_id, variant, - station) + sql = "SELECT * FROM isee.f_create_board('{}', '{}', '{}', NULL, '{}');".format(processor_id, model_id, + variant, + station) else: - sql = "SELECT isee.f_create_board('{}', '{}', '{}', '{}', '{}');".format(processor_id, model_id, variant, - bmac, station) + sql = "SELECT * FROM isee.f_create_board('{}', '{}', '{}', '{}', '{}');".format(processor_id, model_id, + variant, + bmac, station) # print('>>>' + sql) try: res = self.__sqlObject.db_execute_query(sql) @@ -57,7 +59,7 @@ class TestSrv_Database(object): def get_test_params_list(self, testid): '''get the board test list''' - sql = "SELECT * FROM isee.f_get_test_params_list('{}')".format(testid) + sql = "SELECT * FROM isee.f_get_test_params_list({})".format(testid) # print('>>>' + sql) try: res = self.__sqlObject.db_execute_query(sql) @@ -75,7 +77,7 @@ class TestSrv_Database(object): try: res = self.__sqlObject.db_execute_query(sql) # print(res) - return res + return res[0][0] except Exception as err: r = find_between(str(err), '#', '#') # print(r) @@ -83,12 +85,10 @@ class TestSrv_Database(object): def run_test(self, testid_ctl, testid): '''get the board test list''' - sql = "SELECT * FROM isee.f_run_test('{}','{}')".format(testid_ctl, testid) + sql = "SELECT isee.f_run_test({},{})".format(testid_ctl, testid) # print('>>>' + sql) try: - res = self.__sqlObject.db_execute_query(sql) - # print(res) - return res + self.__sqlObject.db_execute_query(sql) except Exception as err: r = find_between(str(err), '#', '#') # print(r) @@ -96,12 +96,10 @@ class TestSrv_Database(object): def finish_test(self, testid_ctl, testid, newstatus): '''get the board test list''' - sql = "SELECT * FROM isee.f_finish_test('{}','{}','{}')".format(testid_ctl, testid, newstatus) + sql = "SELECT isee.f_finish_test({},{},'{}')".format(testid_ctl, testid, newstatus) # print('>>>' + sql) try: - res = self.__sqlObject.db_execute_query(sql) - # print(res) - return res + self.__sqlObject.db_execute_query(sql) except Exception as err: r = find_between(str(err), '#', '#') # print(r) diff --git a/test-cli/test/runners/simple.py b/test-cli/test/runners/simple.py index 084a5b8..dd7c74d 100644 --- a/test-cli/test/runners/simple.py +++ b/test-cli/test/runners/simple.py @@ -12,7 +12,6 @@ from test.helpers.globalVariables import globalVar from test.helpers.testsrv_db import TestSrv_Database - class SimpleTestRunner: """ A Test Runner that shows results in a simple human-readable format. @@ -33,15 +32,12 @@ class SimpleTestRunner: self.stream.write(message) def run(self, test): - """ Run the given test case or Test Suite. - - """ + """ Run the given test case or Test Suite. """ result = TextTestResult(self, self.__pgObj) test(result) - result.testsRun - # self.writeUpdate("---------------------------------------------\n") return result + class TextTestResult(unittest.TestResult): # Print in terminal with colors PASS = '\033[32mPASS\033[0m\n' @@ -60,14 +56,11 @@ class TextTestResult(unittest.TestResult): unittest.TestResult.startTest(self, test) self.runner.writeUpdate("%s : " % test.shortDescription()) # SEND TO DB THE UPDATE THAT WE RUN EACH TEST - self.__pgObj.update_set_test_row(globalVar.station, globalVar.testid_ctl, globalVar.g_uuid, test.shortDescription(), "RUNNING") - # psdb = TestSrv_Database() - # psdb.open("setup.xml") - # psdb.update_set_test_row(globalVar.station, globalVar.testid_ctl, globalVar.g_uuid, test.shortDescription(), "RUNNING") + self.__pgObj.run_test(test.params["testidctl"], test.params["testid"]) def addSuccess(self, test): unittest.TestResult.addSuccess(self, test) - self.result=self.PASS + self.result = self.PASS def addError(self, test, err): unittest.TestResult.addError(self, test, err) @@ -76,25 +69,17 @@ class TextTestResult(unittest.TestResult): def addFailure(self, test, err): unittest.TestResult.addFailure(self, test, err) - test.longMessage=err[1] + test.longMessage = err[1] self.result = self.FAIL def stopTest(self, test): unittest.TestResult.stopTest(self, test) # display: print test result self.runner.writeUpdate(self.result) - # DB: PREPARE THE DATA TO BE INSERTED - dbdata = {} - dbdata['uuid'] = globalVar.g_uuid - dbdata['name'] = test.shortDescription() - dbdata['result'] = self.result - dbdata['msg'] = str(test.longMessage) - #CONVERT FANCY FAIL AND PASS - if self.result==self.PASS: simple_result="TRUE" - if self.result == self.FAIL: simple_result = "FALSE" - elif self.result == self.ERROR: simple_result = "FALSE" - #SEND TO DB THE RESULT OF THE TEST - # psdb = TestSrv_Database() - # psdb.open("setup.xml") - self.__pgObj.add_test_to_batch(globalVar.g_uuid, test.shortDescription(), globalVar.testid_ctl, simple_result, globalVar.g_mid, test.longMessage) - # psdb.add_test_to_batch(globalVar.g_uuid, test.shortDescription(), globalVar.testid_ctl, simple_result, globalVar.g_mid, test.longMessage) + # SEND TO DB THE RESULT OF THE TEST + if self.result == self.PASS: + status = "TEST_COMPLETE" + else: + status = "TEST_FAILED" + self.__pgObj.finish_test(test.params["testidctl"], test.params["testid"], status) + diff --git a/test-cli/test/tests/qamp.py b/test-cli/test/tests/qamp.py index 3e38ce9..cf18fc5 100644 --- a/test-cli/test/tests/qamp.py +++ b/test-cli/test/tests/qamp.py @@ -3,10 +3,13 @@ import unittest import serial import time + class Qamp(unittest.TestCase): + params = None - #varlist: undercurrent, overcurrent + # varlist: undercurrent, overcurrent def __init__(self, testname, testfunc, varlist): + self.params = varlist self._current = 0.0 if "undercurrent" in varlist: self._undercurrent = varlist["undercurrent"] @@ -16,7 +19,7 @@ class Qamp(unittest.TestCase): self._overcurrent = varlist["overcurrent"] else: raise Exception('overcurrent param inside Qamp must be defined') - self._vshuntfactor=16384.0 + self._vshuntfactor = 16384.0 self._ser = serial.Serial() self._ser.port = '/dev/ttyUSB0' self._ser.baudrate = 115200 @@ -34,19 +37,19 @@ class Qamp(unittest.TestCase): def execute(self): # Open Serial port ttyUSB0 - error=0 + error = 0 try: self._ser.open() except: self.fail("failed: IMPOSSIBLE OPEN USB-SERIAL PORT ( {} )".format(self._ser.port)) - error=1 - if error==0: + error = 1 + if error == 0: # Clean input and output buffer of serial port self._ser.flushInput() self._ser.flushOutput() # Send command to read Voltage at Shunt resistor # Prepare cmd - cmd = ('at+in?\n\r') + cmd = 'at+in?\n\r' i = 0 # Write, 1 by 1 byte at a time to avoid hanging of serial receiver code of listener, emphasis being made at sleep of 50 ms. @@ -57,7 +60,7 @@ class Qamp(unittest.TestCase): # Read, 1 by 1 byte res = [] - while (self._ser.inWaiting() > 0): # if incoming bytes are waiting to be read from the serial input buffer + while self._ser.inWaiting() > 0: # if incoming bytes are waiting to be read from the serial input buffer res.append(self._ser.read(1).decode('ascii')) # read the bytes and convert from binary array to ASCII string = ''.join(res) @@ -65,12 +68,8 @@ class Qamp(unittest.TestCase): self._current = float(int(string, 0)) / self._vshuntfactor print(self._current) # In order to give a valid result it is importarnt to define an under current value - if (self._current > float(self._overcurrent)): + if self._current > float(self._overcurrent): self.fail("failed: OVERCURRENT DETECTED ( {} )".format(self._current)) - if (self._current < float(self._undercurrent)): + if self._current < float(self._undercurrent): self.fail("failed: UNDERCURRENT DETECTED ( {} )".format(self._current)) - - - - diff --git a/test-cli/test/tests/qaudio.py b/test-cli/test/tests/qaudio.py index fe57be2..ef4da67 100644 --- a/test-cli/test/tests/qaudio.py +++ b/test-cli/test/tests/qaudio.py @@ -1,38 +1,39 @@ from test.helpers.syscmd import SysCommand import unittest -#class name + + class Qaudio(unittest.TestCase): - # Initialize the variables + params = None - def __init__(self, testname, testfunc, dtmfFile): - # Doing this we will initialize the class and later on perform a particular method inside this class + def __init__(self, testname, testfunc, varlist): + self.params = varlist super(Qaudio, self).__init__(testfunc) self._testMethodDoc = testname - self._dtmfFile=dtmfFile - self.__sum=0 - self.__refSum = 25 # 1+3+5+7+9 + if "dtmfFile" in varlist: + self._dtmfFile = varlist["dtmfFile"] + else: + raise Exception('undercurrent param inside Qamp must be defined') + self.__sum = 0 + self.__refSum = 25 # 1+3+5+7+9 def execute(self): - str_cmd = "aplay test/files/dtmf-13579.wav & arecord -r 8000 -d 1 recorded.wav" #.format(self.__dtmfFile) + str_cmd = "aplay test/files/dtmf-13579.wav & arecord -r 8000 -d 1 recorded.wav" # .format(self.__dtmfFile) audio_loop = SysCommand("command-name", str_cmd) - if audio_loop.execute() == -1:# BUG: Returns -1 but work + if audio_loop.execute() == -1: # BUG: Returns -1 but work lines = audio_loop.getOutput().splitlines() str_cmd = "multimon -t wav -a DTMF recorded.wav -q" dtmf_decoder = SysCommand("command-name", str_cmd) - a=dtmf_decoder.execute() - if dtmf_decoder.execute() == -1: # BUG: Returns -1 but work + a = dtmf_decoder.execute() + if dtmf_decoder.execute() == -1: # BUG: Returns -1 but work self.__raw_out = dtmf_decoder.getOutput() if self.__raw_out == "": - return -1 + self.fail("failed: can not execute multimon command") lines = dtmf_decoder.getOutput().splitlines() for i in range(0, 5): - aux=[int(s) for s in lines[i].split() if s.isdigit()] - self.__sum=self.__sum+aux[0] + aux = [int(s) for s in lines[i].split() if s.isdigit()] + self.__sum = self.__sum + aux[0] self.failUnless(self.__sum == self.__refSum), "failed: incorrect dtmf code" + str(self.__sum) else: self.fail("failed: fail reading recorded file") - return -1 else: self.fail("failed: fail playing/recording file") - return -1 - return 0 \ No newline at end of file diff --git a/test-cli/test/tests/qbutton.py b/test-cli/test/tests/qbutton.py index 4718924..46ddde0 100644 --- a/test-cli/test/tests/qbutton.py +++ b/test-cli/test/tests/qbutton.py @@ -1,11 +1,14 @@ from test.helpers.syscmd import SysCommand import unittest -import uuid import time + class Qbutton(unittest.TestCase): + params = None def __init__(self, testname, testfunc, varlist): + self.params = varlist + super(Qbutton, self).__init__(testfunc) if "gpio" in varlist: self.__gpio = varlist["gpio"] else: diff --git a/test-cli/test/tests/qduplex_ser.py b/test-cli/test/tests/qduplex_ser.py index 837b4d0..46fb5db 100644 --- a/test-cli/test/tests/qduplex_ser.py +++ b/test-cli/test/tests/qduplex_ser.py @@ -1,12 +1,14 @@ -from test.helpers.syscmd import SysCommand import unittest import uuid import serial import time + class Qduplex(unittest.TestCase): + params = None def __init__(self, testname, testfunc, varlist): + self.params = varlist super(Qduplex, self).__init__(testfunc) if "port1" in varlist: self.__port1 = varlist["port1"] diff --git a/test-cli/test/tests/qeeprom.py b/test-cli/test/tests/qeeprom.py index acdc1f6..d2c55ef 100644 --- a/test-cli/test/tests/qeeprom.py +++ b/test-cli/test/tests/qeeprom.py @@ -3,12 +3,13 @@ import unittest class Qeeprom(unittest.TestCase): - + params = None __position = None __eeprompath = None # varlist: position, eeprompath def __init__(self, testname, testfunc, varlist): + self.params = varlist super(Qeeprom, self).__init__(testfunc) self._testMethodDoc = testname if "position" in varlist: diff --git a/test-cli/test/tests/qethernet.py b/test-cli/test/tests/qethernet.py index adee67f..1d4c9bc 100644 --- a/test-cli/test/tests/qethernet.py +++ b/test-cli/test/tests/qethernet.py @@ -9,8 +9,11 @@ class Qethernet(unittest.TestCase): __bind = None __bwexpected = None __port = None + params = None + #varlist content: serverip, bwexpected, port, (optional)bind def __init__(self, testname, testfunc, varlist): + self.params = varlist super(Qethernet, self).__init__(testfunc) if "serverip" in varlist: self.__serverip = varlist["serverip"] diff --git a/test-cli/test/tests/qflash.py b/test-cli/test/tests/qflash.py index 0c3fcb5..59ed13d 100644 --- a/test-cli/test/tests/qflash.py +++ b/test-cli/test/tests/qflash.py @@ -2,9 +2,12 @@ from test.helpers.syscmd import SysCommand import unittest from test.helpers.globalVariables import globalVar + class Qflasher(unittest.TestCase): + params = None def __init__(self, testname, testfunc, varlist): + self.params = varlist super(Qflasher, self).__init__(testfunc) self._testMethodDoc = testname model=globalVar.g_mid diff --git a/test-cli/test/tests/qi2c.py b/test-cli/test/tests/qi2c.py index 2f14424..71eb64e 100644 --- a/test-cli/test/tests/qi2c.py +++ b/test-cli/test/tests/qi2c.py @@ -1,9 +1,12 @@ from test.helpers.syscmd import SysCommand import unittest + class Qi2c(unittest.TestCase): + params = None def __init__(self, testname, testfunc, varlist): + self.params = varlist super(Qi2c, self).__init__(testfunc) if "busnum" in varlist: self.__busnum = varlist["busnum"] diff --git a/test-cli/test/tests/qiperf.py b/test-cli/test/tests/qiperf.py deleted file mode 100644 index 126b6ee..0000000 --- a/test-cli/test/tests/qiperf.py +++ /dev/null @@ -1,53 +0,0 @@ -from test.helpers.syscmd import SysCommand - - -class QIperf(object): - __sip = None - __raw_out = None - __MB_req = None - __MB_real = None - __BW_real = None - __dat_list = None - __bind = None - - def __init__(self, sip = None): - if sip is not None: - self.__sip = sip - self.__MB_req = '10' - - def execute(self, sip = None, bind = None): - if sip is not None: - self.__sip = sip - - if bind is None: - str_cmd = "iperf -c {} -x CMSV -n {}M".format(self.__sip, self.__MB_req) - else: - self.__bind = bind - str_cmd = "iperf -c {} -x CMSV -n {}M -B {}".format(self.__sip, self.__MB_req, self.__bind) - t = SysCommand("iperf", str_cmd) - if t.execute() == 0: - self.__raw_out = t.getOutput() - if self.__raw_out == "": - return -1 - lines = t.getOutput().splitlines() - dat = lines[1] - dat = dat.decode('ascii') - dat_list = dat.split( ) - for d in dat_list: - a = dat_list.pop(0) - if a == "sec": - break - self.__MB_real = dat_list[0] - self.__BW_real = dat_list[2] - self.__dat_list = dat_list - print(self.__MB_real) - print(self.__BW_real) - else: - return -1 - return 0 - - def get_Total_MB(self): - return self.__MB_real; - - def get_Total_BW(self): - return self.__MB_real; diff --git a/test-cli/test/tests/qnand.py b/test-cli/test/tests/qnand.py index 9f2cd47..5125c1c 100644 --- a/test-cli/test/tests/qnand.py +++ b/test-cli/test/tests/qnand.py @@ -1,14 +1,15 @@ import unittest import sh -class Qnand(unittest.TestCase): +class Qnand(unittest.TestCase): + params = None __device = "10M" # varlist: device def __init__(self, testname, testfunc, varlist): + self.params = varlist super(Qnand, self).__init__(testfunc) - if "device" in varlist: self.__device = varlist["device"] else: diff --git a/test-cli/test/tests/qram.py b/test-cli/test/tests/qram.py index ade7aeb..cc75b68 100644 --- a/test-cli/test/tests/qram.py +++ b/test-cli/test/tests/qram.py @@ -1,15 +1,16 @@ import unittest import sh -class Qram(unittest.TestCase): +class Qram(unittest.TestCase): + params = None __memsize = "10M" __loops = "1" # varlist: memsize, loops def __init__(self, testname, testfunc, varlist): + self.params = varlist super(Qram, self).__init__(testfunc) - if "memsize" in varlist: self.__memsize = varlist["memsize"] else: diff --git a/test-cli/test/tests/qrtc.py b/test-cli/test/tests/qrtc.py index 8e31572..884a290 100644 --- a/test-cli/test/tests/qrtc.py +++ b/test-cli/test/tests/qrtc.py @@ -2,11 +2,13 @@ from test.helpers.syscmd import SysCommand import unittest import time -class Qrtc(unittest.TestCase): +class Qrtc(unittest.TestCase): + params = None __rtc = "/dev/rtc0" def __init__(self, testname, testfunc, varlist): + self.params = varlist super(Qrtc, self).__init__(testfunc) if "rtc" in varlist: self.__rtc = varlist["rtc"] diff --git a/test-cli/test/tests/qscreen.py b/test-cli/test/tests/qscreen.py index 87e53b2..aaee628 100644 --- a/test-cli/test/tests/qscreen.py +++ b/test-cli/test/tests/qscreen.py @@ -1,12 +1,14 @@ from test.helpers.syscmd import SysCommand import unittest -import time from test.helpers.cv_display_test import pattern_detect + class Qscreen(unittest.TestCase): + params = None #varlist: display def __init__(self, testname, testfunc, varlist): + self.params = varlist super(Qscreen, self).__init__(testfunc) if "display" in varlist: self.__display = varlist["display"] diff --git a/test-cli/test/tests/qserial.py b/test-cli/test/tests/qserial.py index d3e2ee6..d798578 100644 --- a/test-cli/test/tests/qserial.py +++ b/test-cli/test/tests/qserial.py @@ -1,12 +1,14 @@ -from test.helpers.syscmd import SysCommand import unittest import uuid import serial import time + class Qserial(unittest.TestCase): + params = None def __init__(self, testname, testfunc, varlist): + self.params = varlist super(Qserial, self).__init__(testfunc) if "port" in varlist: self.__port = varlist["port"] diff --git a/test-cli/test/tests/qusb.py b/test-cli/test/tests/qusb.py index 0390143..70265a5 100644 --- a/test-cli/test/tests/qusb.py +++ b/test-cli/test/tests/qusb.py @@ -1,9 +1,14 @@ from test.helpers.syscmd import SysCommand import unittest + class Qusb(unittest.TestCase): + __numPorts = None + __devLabel = None + params = None def __init__(self, testname, testfunc, varlist): + self.params = varlist super(Qusb, self).__init__(testfunc) if "numPorts" in varlist: self.__numPorts = varlist["numPorts"] @@ -14,27 +19,27 @@ class Qusb(unittest.TestCase): self.__devLabel = varlist["devLabel"] else: raise Exception('devLabel param inside Qusb must be defined') - if testname=="USBOTG": + if testname == "USBOTG": self.__usbFileName = "/this_is_an_usb_otg" self.__usbtext = "USBOTG" else: self.__usbFileName = "/this_is_an_usb_host" self.__usbtext = "USBHOST" - self.__numUsbFail=[] + self.__numUsbFail = [] def execute(self): - str_cmd= "lsblk -o LABEL" + str_cmd = "lsblk -o LABEL" lsblk_command = SysCommand("lsblk", str_cmd) if lsblk_command.execute() == 0: self.__raw_out = lsblk_command.getOutput() if self.__raw_out == "": return -1 lines = lsblk_command.getOutput().splitlines() - host_list=[] + host_list = [] for i in range(len(lines)): - if str(lines[i].decode('ascii'))==self.__devLabel: + if str(lines[i].decode('ascii')) == self.__devLabel: host_list.append(i) - if len(host_list)==int(self.__numPorts): + if len(host_list) == int(self.__numPorts): str_cmd = "lsblk -o MOUNTPOINT" lsblk_command = SysCommand("lsblk", str_cmd) if lsblk_command.execute() == 0: @@ -45,13 +50,14 @@ class Qusb(unittest.TestCase): else: lines = lsblk_command.getOutput().splitlines() for i in range(len(host_list)): - file_path=str(lines[host_list[i]].decode('ascii')) + self.__usbFileName + file_path = str(lines[host_list[i]].decode('ascii')) + self.__usbFileName usb_file = open(file_path, 'r') - read=usb_file.read() - if read.find(self.__usbtext)!=-1: + read = usb_file.read() + if read.find(self.__usbtext) != -1: print(file_path + " --> OK!") else: - self.fail("failed: could not read from usb {}".format(lines[host_list[i]].decode('ascii'))) + self.fail( + "failed: could not read from usb {}".format(lines[host_list[i]].decode('ascii'))) self.__numUsbFail.append(host_list[i]) usb_file.close() else: @@ -60,4 +66,4 @@ class Qusb(unittest.TestCase): else: self.fail("failed: reference and real usb host devices number mismatch") else: - self.fail("failed: couldn't execute lsblk command") \ No newline at end of file + self.fail("failed: couldn't execute lsblk command") diff --git a/test-cli/test/tests/qwifi.py b/test-cli/test/tests/qwifi.py index 154dd52..2a5fa0c 100644 --- a/test-cli/test/tests/qwifi.py +++ b/test-cli/test/tests/qwifi.py @@ -9,14 +9,16 @@ class Qwifi(unittest.TestCase): __bind = None __OKBW = None __port = None + params = None - #varlist: sip, bind, OKBW, port + #varlist: serverip, bind, OKBW, port def __init__(self, testname, testfunc, varlist): + self.params = varlist super(Qwifi, self).__init__(testfunc) - if "sip" in varlist: - self.__sip = varlist["sip"] + if "serverip" in varlist: + self.__serverip = varlist["serverip"] else: - raise Exception('sip param inside Qwifi have been be defined') + raise Exception('serverip param inside Qwifi have been be defined') if "OKBW" in varlist: self.__OKBW = varlist["OKBW"] else: @@ -47,10 +49,10 @@ class Qwifi(unittest.TestCase): if result: # execute iperf command against the server if self.__bind is None: - p = sh.iperf("-c", self.__sip, "-x", "CMSV", "-n", self.__numbytestx, "-f", "m", "-p", + p = sh.iperf("-c", self.__serverip, "-x", "CMSV", "-n", self.__numbytestx, "-f", "m", "-p", self.__port) else: - p = sh.iperf("-c", self.__sip, "-x", "CMSV", "-n", self.__numbytestx, "-f", "m", "-p", + p = sh.iperf("-c", self.__serverip, "-x", "CMSV", "-n", self.__numbytestx, "-f", "m", "-p", self.__port, "-B", self.__bind) # check if it was executed succesfully if p.exit_code == 0: -- cgit v1.1 From a03055f657d2e970e45e7ea2a3e66857f821eabd Mon Sep 17 00:00:00 2001 From: Hector Fernandez Date: Mon, 9 Mar 2020 09:03:28 +0100 Subject: Solved problems with consumption test. Fixed error when getting mac address. --- test-cli/test/helpers/amper.py | 155 +++++++++++++++++++++++++++++++++ test-cli/test/helpers/int_registers.py | 15 ++-- test-cli/test/tests/qamp.py | 1 + test-cli/test/tests/qamper.py | 51 +++++++++++ 4 files changed, 217 insertions(+), 5 deletions(-) create mode 100644 test-cli/test/helpers/amper.py create mode 100644 test-cli/test/tests/qamper.py (limited to 'test-cli/test') diff --git a/test-cli/test/helpers/amper.py b/test-cli/test/helpers/amper.py new file mode 100644 index 0000000..45ec7db --- /dev/null +++ b/test-cli/test/helpers/amper.py @@ -0,0 +1,155 @@ +import serial +import scanf +import time + + +class Amper(object): + __ser = None + __port = '/dev/ttyUSB0' + __speed = 115200 + __parity = None + __rtscts = 0 + __timeout = 1 + __isThere = False + __version = None + __voltage = 0.0 + __current = 0.0 + __alarm_condition = 0 + + def __init__(self, port='/dev/ttyUSB0', serial_speed=115200, parity=serial.PARITY_NONE, rtscts=0): + self.__port = port + self.__speed = serial_speed + self.__parity = parity + self.__rtscts = rtscts + + def open(self): + try: + if self.__ser is not None: + self.close() + self.__ser = serial.Serial(port=self.__port, + baudrate=self.__speed, + timeout=self.__timeout, + parity=self.__parity, + rtscts=self.__rtscts, + bytesize=serial.EIGHTBITS, + stopbits=serial.STOPBITS_ONE, + xonxoff=0) + + self.__ser.flushInput() + self.__ser.flushOutput() + self.__ser.break_condition = False + return True + except serial.SerialException as err: + print(err) + return False + + def close(self): + if self.__ser is not None: + self.__ser.close() + self.__ser = None + self.__isThere = False + self.__version = None + self.__voltage = 0.0 + self.__current = 0.0 + self.__alarm_condition = 0 + + def __write(self, data): + data += "\n\r" + dat = data.encode('ascii') + self.__ser.write(dat) + + def __read(self): + return self.__ser.readline().decode().rstrip() + + def __set_voltage_underlimit(self, under_limit): + if self.__isThere and self.__ser is not None: + self.__write('AT+VIN_UV_W_LIM={}'.format(under_limit)) + dat = self.__read() + print(dat) + + def __get_voltage_underlimit(self): + self.__write('AT+VIN_UV_W_LIM=?') + dat = self.__read() + res = scanf.scanf("%f", dat) + return res[0] + + def __set_voltage_overlimit(self, over_limit): + if self.__isThere and self.__ser is not None: + self.__write('AT+VIN_OV_W_LIM={}'.format(over_limit)) + dat = self.__read() + print(dat) + + def __get_voltage_overlimit(self): + if self.__isThere and self.__ser is not None: + self.__write('AT+VIN_OV_W_LIM?') + dat = self.__read() + res = scanf.scanf("%f", dat) + return res[0] + + def __set_current_overlimit(self, over_limit): + if self.__isThere and self.__ser is not None: + self.__write('AT+IOUT_W_LIM={}'.format(over_limit)) + dat = self.__read() + print(dat) + + def __get_current_overlimit(self): + if self.__isThere and self.__ser is not None: + self.__write('AT+IOUT_W_LIM?') + dat = self.__read() + dat = self.__read() + res = scanf.scanf("%f", dat) + return res[0] + + def hello(self): + self.__isThere = False + if self.__ser is None: + return False + self.__write('at+ver?') + dat = self.__read() + res = scanf.scanf("ISEE Amper v%3c", dat) + if res is None: + return False + self.__isThere = True + self.__version = res[0] + return True + + def getVersion(self): + return self.__version + + def getVoltage(self): + if self.__isThere and self.__ser is not None: + self.__write('at+vin?') + dat = self.__read() + res = scanf.scanf("%f", dat) + self.__voltage = res[0] + # print(self.__voltage) + return self.__voltage + else: + return None + + def getCurrent(self): + if self.__isThere and self.__ser is not None: + self.__write('at+in?') + dat = self.__read() + res = scanf.scanf("%f", dat) + self.__current = res[0] + # print(self.__current) + else: + return None + return self.__current + + def getAlarm(self): + if self.__isThere and self.__ser is not None: + self.__write('at+st_mfr?') + dat = self.__read() + # print(dat) + self.__alarm_condition = (int(dat) & 0x0F) + # print(self.__alarm_condition) + return self.__alarm_condition + + def clearAlarm(self): + if self.__isThere and self.__ser is not None: + self.__write('at+CLRFAULT') + dat = self.__read() + # print(dat) + diff --git a/test-cli/test/helpers/int_registers.py b/test-cli/test/helpers/int_registers.py index cf2e35b..030035d 100644 --- a/test-cli/test/helpers/int_registers.py +++ b/test-cli/test/helpers/int_registers.py @@ -1,6 +1,7 @@ import mmap import os import struct +import sh MAP_MASK = mmap.PAGESIZE - 1 WORD = 4 @@ -47,10 +48,14 @@ def get_mac(modelid): mac = None if modelid.find("IGEP0034") == 0 or modelid.find("SOPA0000") == 0: - # registers: mac_id0_lo, mac_id0_hi - registers = [0x44e10630, 0x44e10634] - mac = "" - for rg in registers: - mac = mac + read(rg) + # # registers: mac_id0_lo, mac_id0_hi + # registers = [0x44e10630, 0x44e10634] + # mac = "" + # for rg in registers: + # mac = mac + read(rg) + # #erase trailing zeros + # mac = mac[4::1] + mac = sh.cat("/sys/class/net/eth0/address") + return mac diff --git a/test-cli/test/tests/qamp.py b/test-cli/test/tests/qamp.py index cf18fc5..56511c8 100644 --- a/test-cli/test/tests/qamp.py +++ b/test-cli/test/tests/qamp.py @@ -36,6 +36,7 @@ class Qamp(unittest.TestCase): self._ser.close() def execute(self): + # Open Serial port ttyUSB0 error = 0 try: diff --git a/test-cli/test/tests/qamper.py b/test-cli/test/tests/qamper.py new file mode 100644 index 0000000..2b02302 --- /dev/null +++ b/test-cli/test/tests/qamper.py @@ -0,0 +1,51 @@ +import unittest +from test.helpers.amper import Amper + + +class Qamper(unittest.TestCase): + params = None + + # varlist: undercurrent, overcurrent + def __init__(self, testname, testfunc, varlist): + self.params = varlist + super(Qamper, self).__init__(testfunc) + + if "undercurrent" in varlist: + self._undercurrent = varlist["undercurrent"] + else: + raise Exception('undercurrent param inside Qamp must be defined') + if "overcurrent" in varlist: + self._overcurrent = varlist["overcurrent"] + else: + raise Exception('overcurrent param inside Qamp must be defined') + self._testMethodDoc = testname + + def execute(self): + amp = Amper() + print(amp) + if not amp.open(): + print("1") + self.fail("failed: can not open serial port") + return + + if not amp.hello(): + print("2") + self.fail("failed: can not communicate") + return + + result = amp.getCurrent() + print(result) + + amp.close() + + + + + + + # # In order to give a valid result it is importarnt to define an under current value + # if self._current > float(self._overcurrent): + # self.fail("failed: OVERCURRENT DETECTED ( {} )".format(self._current)) + # + # if self._current < float(self._undercurrent): + # self.fail("failed: UNDERCURRENT DETECTED ( {} )".format(self._current)) -- cgit v1.1 From c685367cbd6abf1c6ae442df759e39b25a907d3b Mon Sep 17 00:00:00 2001 From: Hector Fernandez Date: Mon, 9 Mar 2020 12:39:50 +0100 Subject: Fixed several test procedures. --- test-cli/test/helpers/amper.py | 1 - test-cli/test/helpers/changedir.py | 14 ++++++ test-cli/test/helpers/usb.sh | 2 +- test-cli/test/tests/qamper.py | 27 ++++-------- test-cli/test/tests/qduplex_ser.py | 40 ++++++++++-------- test-cli/test/tests/qeeprom.py | 1 - test-cli/test/tests/qi2c.py | 6 +-- test-cli/test/tests/qrtc.py | 26 +++++++----- test-cli/test/tests/qserial.py | 22 ++++++---- test-cli/test/tests/qusb.py | 87 ++++++++++++++------------------------ 10 files changed, 110 insertions(+), 116 deletions(-) create mode 100644 test-cli/test/helpers/changedir.py (limited to 'test-cli/test') diff --git a/test-cli/test/helpers/amper.py b/test-cli/test/helpers/amper.py index 45ec7db..ea719f6 100644 --- a/test-cli/test/helpers/amper.py +++ b/test-cli/test/helpers/amper.py @@ -1,6 +1,5 @@ import serial import scanf -import time class Amper(object): diff --git a/test-cli/test/helpers/changedir.py b/test-cli/test/helpers/changedir.py new file mode 100644 index 0000000..fad9ade --- /dev/null +++ b/test-cli/test/helpers/changedir.py @@ -0,0 +1,14 @@ +import os + + +class changedir: + """Context manager for changing the current working directory""" + def __init__(self, newPath): + self.newPath = os.path.expanduser(newPath) + + def __enter__(self): + self.savedPath = os.getcwd() + os.chdir(self.newPath) + + def __exit__(self, etype, value, traceback): + os.chdir(self.savedPath) \ No newline at end of file diff --git a/test-cli/test/helpers/usb.sh b/test-cli/test/helpers/usb.sh index c8e6924..52ea4b2 100755 --- a/test-cli/test/helpers/usb.sh +++ b/test-cli/test/helpers/usb.sh @@ -11,4 +11,4 @@ for sysdevpath in $(find /sys/bus/usb/devices/usb*/ -name dev); do ) done -return 0 +exit 0 diff --git a/test-cli/test/tests/qamper.py b/test-cli/test/tests/qamper.py index 2b02302..b3ab8b1 100644 --- a/test-cli/test/tests/qamper.py +++ b/test-cli/test/tests/qamper.py @@ -22,30 +22,21 @@ class Qamper(unittest.TestCase): def execute(self): amp = Amper() - print(amp) + # open serial connection if not amp.open(): - print("1") self.fail("failed: can not open serial port") return - + # check if the amperimeter is connected and working if not amp.hello(): - print("2") self.fail("failed: can not communicate") return - + # get current value (in Amperes) result = amp.getCurrent() - print(result) - + # close serial connection amp.close() + # # In order to give a valid result it is importarnt to define an under current value + if result > float(self._overcurrent): + self.fail("failed: Overcurrent detected ( {} )".format(result)) - - - - - - # # In order to give a valid result it is importarnt to define an under current value - # if self._current > float(self._overcurrent): - # self.fail("failed: OVERCURRENT DETECTED ( {} )".format(self._current)) - # - # if self._current < float(self._undercurrent): - # self.fail("failed: UNDERCURRENT DETECTED ( {} )".format(self._current)) + if result < float(self._undercurrent): + self.fail("failed: Undercurrent detected ( {} )".format(result)) diff --git a/test-cli/test/tests/qduplex_ser.py b/test-cli/test/tests/qduplex_ser.py index 46fb5db..0666363 100644 --- a/test-cli/test/tests/qduplex_ser.py +++ b/test-cli/test/tests/qduplex_ser.py @@ -6,7 +6,11 @@ import time class Qduplex(unittest.TestCase): params = None + __port1 = None + __port2 = None + __baudrate = None + # varlist: port1, port2, baudrate def __init__(self, testname, testfunc, varlist): self.params = varlist super(Qduplex, self).__init__(testfunc) @@ -14,46 +18,46 @@ class Qduplex(unittest.TestCase): self.__port1 = varlist["port1"] else: raise Exception('port1 param inside Qduplex must be defined') - self.__serial1 = serial.Serial(self.__port1, timeout=1) - if "port2" in varlist: self.__port2 = varlist["port2"] else: raise Exception('port2 param inside Qduplex must be defined') - self.__serial2 = serial.Serial(self.__port2, timeout=1) - if "baudrate" in varlist: - self.__serial1.baudrate = varlist["baudrate"] - self.__serial2.baudrate = varlist["baudrate"] + self.__baudrate = varlist["baudrate"] else: raise Exception('baudrate param inside Qduplex must be defined') - self._testMethodDoc = testname + # open serial connection + self.__serial1 = serial.Serial(self.__port1, self.__baudrate, timeout=1) + self.__serial1.flushInput() + self.__serial1.flushOutput() + self.__serial2 = serial.Serial(self.__port2, self.__baudrate, timeout=1) + self.__serial2.flushInput() + self.__serial2.flushOutput() + def __del__(self): self.__serial1.close() self.__serial2.close() def execute(self): - self.__serial1.flushInput() - self.__serial1.flushOutput() - self.__serial2.flushInput() - self.__serial2.flushOutput() + # generate a random uuid test_uuid = str(uuid.uuid4()).encode() + # send the uuid through serial port self.__serial1.write(test_uuid) time.sleep(0.05) # there might be a small delay if self.__serial2.inWaiting() == 0: - self.fail("failed: PORT {} wait timeout exceded, wrong communication?".format(self.__port2)) + self.fail("failed: port {} wait timeout exceded".format(self.__port2)) else: - if (self.__serial2.readline() != test_uuid): - self.fail("failed: PORT {} write/read mismatch".format(self.__port2)) + if self.__serial2.readline() != test_uuid: + self.fail("failed: port {} write/read mismatch".format(self.__port2)) test_uuid = str(uuid.uuid4()).encode() + # send the uuid through serial port self.__serial2.write(test_uuid) time.sleep(0.05) # there might be a small delay if self.__serial1.inWaiting() == 0: - self.fail("failed: PORT {} wait timeout exceded, wrong communication?".format(self.__port1)) + self.fail("failed: port {} wait timeout exceded".format(self.__port1)) else: - if (self.__serial1.readline() != test_uuid): - self.fail("failed: PORT {} write/read mismatch".format(self.__port1)) - + if self.__serial1.readline() != test_uuid: + self.fail("failed: port {} write/read mismatch".format(self.__port1)) diff --git a/test-cli/test/tests/qeeprom.py b/test-cli/test/tests/qeeprom.py index d2c55ef..1921bf7 100644 --- a/test-cli/test/tests/qeeprom.py +++ b/test-cli/test/tests/qeeprom.py @@ -34,7 +34,6 @@ class Qeeprom(unittest.TestCase): # compare both values if data_rx != data_tx: self.fail("failed: mismatch between written and received values.") - else: self.fail("failed: Unable to read from the EEPROM device.") else: diff --git a/test-cli/test/tests/qi2c.py b/test-cli/test/tests/qi2c.py index 71eb64e..c59975e 100644 --- a/test-cli/test/tests/qi2c.py +++ b/test-cli/test/tests/qi2c.py @@ -20,7 +20,7 @@ class Qi2c(unittest.TestCase): self._testMethodDoc = testname def execute(self): - str_cmd= "i2cdetect -a -y -r {}".format(self.__busnum) + str_cmd = "i2cdetect -a -y -r {}".format(self.__busnum) i2c_command = SysCommand("i2cdetect", str_cmd) if i2c_command.execute() == 0: self.__raw_out = i2c_command.getOutput() @@ -28,8 +28,8 @@ class Qi2c(unittest.TestCase): return -1 lines=self.__raw_out.decode('ascii').splitlines() for i in range(len(lines)): - if (lines[i].count('UU')): - if (lines[i].find("UU")): + if lines[i].count('UU'): + if lines[i].find("UU"): self.__devices.append("0x{}{}".format((i - 1), hex(int((lines[i].find("UU") - 4) / 3)).split('x')[-1])) for i in range(len(self.__register)): if not(self.__register[i] in self.__devices): diff --git a/test-cli/test/tests/qrtc.py b/test-cli/test/tests/qrtc.py index 884a290..0be0f99 100644 --- a/test-cli/test/tests/qrtc.py +++ b/test-cli/test/tests/qrtc.py @@ -1,11 +1,12 @@ -from test.helpers.syscmd import SysCommand +import sh import unittest import time +import re class Qrtc(unittest.TestCase): params = None - __rtc = "/dev/rtc0" + __rtc = None def __init__(self, testname, testfunc, varlist): self.params = varlist @@ -17,16 +18,19 @@ class Qrtc(unittest.TestCase): self._testMethodDoc = testname def execute(self): - str_cmd = "hwclock -f {}".format(self.__rtc) - rtc_set = SysCommand("rtc_set", str_cmd) - if rtc_set.execute() == 0: - curr_hour = rtc_set.getOutput().decode('ascii').split(" ") - time1 = int((curr_hour[4].split(":"))[2]) + # get time from RTC peripheral + p = sh.hwclock("-f", self.__rtc) + if p.exit_code == 0: + time1 = re.search("([01]?[0-9]{1}|2[0-3]{1})[:][0-5]{1}[0-9]{1}[:][0-5]{1}[0-9]{1}", + p.stdout.decode('ascii')) time.sleep(1) - if rtc_set.execute() == 0: - curr_hour = rtc_set.getOutput().decode('ascii').split(" ") - time2 = int((curr_hour[4].split(":"))[2]) - if time1==time2: + # get time from RTC another time + p = sh.hwclock("-f", self.__rtc) + if p.exit_code == 0: + time2 = re.search("([01]?[0-9]{1}|2[0-3]{1})[:][0-5]{1}[0-9]{1}[:][0-5]{1}[0-9]{1}", + p.stdout.decode('ascii')) + # check if the seconds of both times are different + if time1 == time2: self.fail("failed: RTC is not running") else: self.fail("failed: couldn't execute hwclock command 2nd time") diff --git a/test-cli/test/tests/qserial.py b/test-cli/test/tests/qserial.py index d798578..67e3af1 100644 --- a/test-cli/test/tests/qserial.py +++ b/test-cli/test/tests/qserial.py @@ -6,7 +6,10 @@ import time class Qserial(unittest.TestCase): params = None + __port = None + __baudrate = None + #varlist: port, baudrate def __init__(self, testname, testfunc, varlist): self.params = varlist super(Qserial, self).__init__(testfunc) @@ -14,28 +17,31 @@ class Qserial(unittest.TestCase): self.__port = varlist["port"] else: raise Exception('port param inside Qserial must be defined') - self.__serial = serial.Serial(self.__port, timeout=1) + if "baudrate" in varlist: self.__baudrate = varlist["baudrate"] else: raise Exception('baudrate param inside Qserial must be defined') self._testMethodDoc = testname + # open serial connection + self.__serial = serial.Serial(self.__port, self.__baudrate, timeout=1) + self.__serial.flushInput() + self.__serial.flushOutput() + def __del__(self): self.__serial.close() def execute(self): - self.__serial.flushInput() - self.__serial.flushOutput() - #generate a random uuid + # generate a random uuid test_uuid = str(uuid.uuid4()).encode() - #send the uuid through serial port + # send the uuid through serial port self.__serial.write(test_uuid) time.sleep(0.05) # there might be a small delay if self.__serial.inWaiting() == 0: - self.fail("failed: PORT {} wait timeout exceded, wrong communication?".format(self.__port)) + self.fail("failed: port {} wait timeout exceded".format(self.__port)) else: # check if what it was sent is equal to what has been received - if (self.__serial.readline() != test_uuid): - self.fail("failed: PORT {} write/read mismatch".format(self.__port)) + if self.__serial.readline() != test_uuid: + self.fail("failed: port {} write/read mismatch".format(self.__port)) diff --git a/test-cli/test/tests/qusb.py b/test-cli/test/tests/qusb.py index 70265a5..7ecf31e 100644 --- a/test-cli/test/tests/qusb.py +++ b/test-cli/test/tests/qusb.py @@ -1,69 +1,46 @@ -from test.helpers.syscmd import SysCommand +import sh import unittest +import re +from test.helpers.changedir import changedir class Qusb(unittest.TestCase): - __numPorts = None - __devLabel = None params = None def __init__(self, testname, testfunc, varlist): self.params = varlist super(Qusb, self).__init__(testfunc) - if "numPorts" in varlist: - self.__numPorts = varlist["numPorts"] - else: - raise Exception('numPorts param inside Qusb must be defined') self._testMethodDoc = testname - if "devLabel" in varlist: - self.__devLabel = varlist["devLabel"] - else: - raise Exception('devLabel param inside Qusb must be defined') - if testname == "USBOTG": - self.__usbFileName = "/this_is_an_usb_otg" - self.__usbtext = "USBOTG" - else: - self.__usbFileName = "/this_is_an_usb_host" - self.__usbtext = "USBHOST" - self.__numUsbFail = [] def execute(self): - str_cmd = "lsblk -o LABEL" - lsblk_command = SysCommand("lsblk", str_cmd) - if lsblk_command.execute() == 0: - self.__raw_out = lsblk_command.getOutput() - if self.__raw_out == "": - return -1 - lines = lsblk_command.getOutput().splitlines() - host_list = [] - for i in range(len(lines)): - if str(lines[i].decode('ascii')) == self.__devLabel: - host_list.append(i) - if len(host_list) == int(self.__numPorts): - str_cmd = "lsblk -o MOUNTPOINT" - lsblk_command = SysCommand("lsblk", str_cmd) - if lsblk_command.execute() == 0: - self.__raw_out = lsblk_command.getOutput() - if self.__raw_out == "": - print("failed: no command output") - self.fail("failed: no command output") - else: - lines = lsblk_command.getOutput().splitlines() - for i in range(len(host_list)): - file_path = str(lines[host_list[i]].decode('ascii')) + self.__usbFileName - usb_file = open(file_path, 'r') - read = usb_file.read() - if read.find(self.__usbtext) != -1: - print(file_path + " --> OK!") - else: - self.fail( - "failed: could not read from usb {}".format(lines[host_list[i]].decode('ascii'))) - self.__numUsbFail.append(host_list[i]) - usb_file.close() - else: - self.fail("failed: couldn't execute lsblk command") - + # Execute script usb.sh + p = sh.bash('test/helpers/usb.sh') + # Search in the stdout a pattern "/dev/sd + {letter} + {number} + q = re.search("/dev/sd\w\d", p.stdout.decode('ascii')) + # get the first device which matches the pattern + device = q.group(0) + # create a new folder where the pendrive is going to be mounted + sh.mkdir("-p", "/mnt/pendrive") + # mount the device + p = sh.mount(device, "/mnt/pendrive") + if p.exit_code == 0: + # copy files + p = sh.cp("/root/usbtest/usbdatatest.bin", "/root/usbtest/usbdatatest.md5", "/mnt/pendrive") + if p.exit_code == 0: + # check md5 + with changedir("/mnt/pendrive/"): + p = sh.md5sum("-c", "usbdatatest.md5") + q = re.search("OK", p.stdout.decode('ascii')) + # delete files + sh.rm("-f", "/mnt/pendrive/usbdatatest.bin", "/mnt/pendrive/usbdatatest.md5") + # umount + sh.umount("/mnt/pendrive") + # check result + if q is None: + self.fail("failed: wrong md5 result.") else: - self.fail("failed: reference and real usb host devices number mismatch") + # umount + sh.umount("/mnt/pendrive") + self.fail("failed: unable to copy files.") else: - self.fail("failed: couldn't execute lsblk command") + self.fail("failed: unable to mount the device.") -- cgit v1.1 From d38c92bfd7b6abe3a52b51b87b1a2949b857d9b4 Mon Sep 17 00:00:00 2001 From: Hector Fernandez Date: Mon, 9 Mar 2020 19:16:08 +0100 Subject: Created function to flash the eeprom memory. --- test-cli/test/helpers/button_script.sh | 4 --- test-cli/test/helpers/testsrv_db.py | 13 +++++++ test-cli/test/helpers/usb.sh | 14 -------- test-cli/test/scripts/__init__.py | 0 test-cli/test/scripts/usb.sh | 14 ++++++++ test-cli/test/tests/qbutton.py | 64 ---------------------------------- test-cli/test/tests/qusb.py | 2 +- test-cli/test/tests/qwifi.py | 19 +++++----- 8 files changed, 38 insertions(+), 92 deletions(-) delete mode 100644 test-cli/test/helpers/button_script.sh delete mode 100755 test-cli/test/helpers/usb.sh create mode 100644 test-cli/test/scripts/__init__.py create mode 100755 test-cli/test/scripts/usb.sh delete mode 100644 test-cli/test/tests/qbutton.py (limited to 'test-cli/test') diff --git a/test-cli/test/helpers/button_script.sh b/test-cli/test/helpers/button_script.sh deleted file mode 100644 index 6908f22..0000000 --- a/test-cli/test/helpers/button_script.sh +++ /dev/null @@ -1,4 +0,0 @@ -#!/usr/bin/env bash -i2cset -f -y 1 0x2d 0x40 0x31 -i2cset -f -y 1 0x2d 0x50 0xff -i2cget -f -y 1 0x2d 0x50 diff --git a/test-cli/test/helpers/testsrv_db.py b/test-cli/test/helpers/testsrv_db.py index d937d3e..9fb61fd 100644 --- a/test-cli/test/helpers/testsrv_db.py +++ b/test-cli/test/helpers/testsrv_db.py @@ -104,3 +104,16 @@ class TestSrv_Database(object): r = find_between(str(err), '#', '#') # print(r) return None + + def get_board_variables(self, board_uuid): + sql = "SELECT * FROM isee.f_get_boardvariables('{}')".format(board_uuid) + # print('>>>' + sql) + try: + res = self.__sqlObject.db_execute_query(sql) + # print(res) + return res + except Exception as err: + r = find_between(str(err), '#', '#') + # print(r) + return None + diff --git a/test-cli/test/helpers/usb.sh b/test-cli/test/helpers/usb.sh deleted file mode 100755 index 52ea4b2..0000000 --- a/test-cli/test/helpers/usb.sh +++ /dev/null @@ -1,14 +0,0 @@ -#!/bin/bash - -for sysdevpath in $(find /sys/bus/usb/devices/usb*/ -name dev); do - ( - syspath="${sysdevpath%/dev}" - devname="$(udevadm info -q name -p $syspath)" - [[ "$devname" == "bus/"* ]] && continue - eval "$(udevadm info -q property --export -p $syspath)" - [[ -z "$ID_SERIAL" ]] && continue - echo "/dev/$devname - $ID_SERIAL" - ) -done - -exit 0 diff --git a/test-cli/test/scripts/__init__.py b/test-cli/test/scripts/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/test-cli/test/scripts/usb.sh b/test-cli/test/scripts/usb.sh new file mode 100755 index 0000000..52ea4b2 --- /dev/null +++ b/test-cli/test/scripts/usb.sh @@ -0,0 +1,14 @@ +#!/bin/bash + +for sysdevpath in $(find /sys/bus/usb/devices/usb*/ -name dev); do + ( + syspath="${sysdevpath%/dev}" + devname="$(udevadm info -q name -p $syspath)" + [[ "$devname" == "bus/"* ]] && continue + eval "$(udevadm info -q property --export -p $syspath)" + [[ -z "$ID_SERIAL" ]] && continue + echo "/dev/$devname - $ID_SERIAL" + ) +done + +exit 0 diff --git a/test-cli/test/tests/qbutton.py b/test-cli/test/tests/qbutton.py deleted file mode 100644 index 46ddde0..0000000 --- a/test-cli/test/tests/qbutton.py +++ /dev/null @@ -1,64 +0,0 @@ -from test.helpers.syscmd import SysCommand -import unittest -import time - - -class Qbutton(unittest.TestCase): - params = None - - def __init__(self, testname, testfunc, varlist): - self.params = varlist - super(Qbutton, self).__init__(testfunc) - if "gpio" in varlist: - self.__gpio = varlist["gpio"] - else: - raise Exception('gpio param inside Qbutton must be defined') - if self.__gpio == "SOPA": - super(Qbutton, self).__init__("buttonSopa") - else: - super(Qbutton, self).__init__("buttonGpio") - self._testMethodDoc = testname - - def buttonGpio(self): - print("normal-button-test-using-gpio") - self.fail("failed: GPIO BUTTON FAIL") - - def buttonSopa(self): - str_cmd = "i2cset -f -y 1 0x2d 0x40 0x31" - disable_pmic = SysCommand("disable_pmic", str_cmd) - disable_pmic.execute() - # BUG: REPEAT THIS EXECUTION TWICE BECAUSE FIRST TIME IT RETURNS AN ERROR - led_on="echo 1 > /sys/class/leds/red\:usbhost/brightness" - ledon = SysCommand("led_on", led_on) - ledon.execute() - time.sleep(0.1) - disable_pmic.execute() - if disable_pmic.execute() == 0: - str_cmd = "i2cset -f -y 1 0x2d 0x50 0xff" - reset_button = SysCommand("reset_button", str_cmd) - if reset_button.execute() == 0: - str_cmd = "i2cget -f -y 1 0x2d 0x50" - get_button_val = SysCommand("get_button_val", str_cmd) - print("\n\t --> PRESS button for 1 sec (TIMEOUT: 10s) \n") - timeout = 0 - while timeout < 7200: - if get_button_val.execute() == 0: - get_button_val.execute() - button_value = get_button_val.getOutput() - button_value=button_value.decode('ascii').split("x") - if int(button_value[1]) == 4: - timeout = 7200 - led_off="echo 0 > /sys/class/leds/red\:usbhost/brightness" - ledoff = SysCommand("led_off", led_off) - ledoff.execute() - time.sleep(0.5) - timeout = timeout + 1 - if timeout==7200 and int(button_value[1]) == 0: - self.fail("failed: timeout exceeded") - else: - timeout = 7200 - self.fail("failed: not button input") - else: - self.fail("failed: could not complete i2c reset button state") - else: - self.fail("failed: could not complete i2c disable PMIC") diff --git a/test-cli/test/tests/qusb.py b/test-cli/test/tests/qusb.py index 7ecf31e..6a004f0 100644 --- a/test-cli/test/tests/qusb.py +++ b/test-cli/test/tests/qusb.py @@ -14,7 +14,7 @@ class Qusb(unittest.TestCase): def execute(self): # Execute script usb.sh - p = sh.bash('test/helpers/usb.sh') + p = sh.bash('test/scripts/usb.sh') # Search in the stdout a pattern "/dev/sd + {letter} + {number} q = re.search("/dev/sd\w\d", p.stdout.decode('ascii')) # get the first device which matches the pattern diff --git a/test-cli/test/tests/qwifi.py b/test-cli/test/tests/qwifi.py index 2a5fa0c..8daf069 100644 --- a/test-cli/test/tests/qwifi.py +++ b/test-cli/test/tests/qwifi.py @@ -4,14 +4,14 @@ import re class Qwifi(unittest.TestCase): - __sip = None + __serverip = None __numbytestx = None __bind = None - __OKBW = None + __bwexpected = None __port = None params = None - #varlist: serverip, bind, OKBW, port + # varlist content: serverip, bwexpected, port, (optional)bind def __init__(self, testname, testfunc, varlist): self.params = varlist super(Qwifi, self).__init__(testfunc) @@ -19,8 +19,8 @@ class Qwifi(unittest.TestCase): self.__serverip = varlist["serverip"] else: raise Exception('serverip param inside Qwifi have been be defined') - if "OKBW" in varlist: - self.__OKBW = varlist["OKBW"] + if "bwexpected" in varlist: + self.__bwexpected = varlist["bwexpected"] else: raise Exception('OKBW param inside Qwifi must be defined') if "port" in varlist: @@ -41,11 +41,12 @@ class Qwifi(unittest.TestCase): # get the first line of the output stream out1 = p.stdout.decode('ascii').splitlines()[0] if out1 != "Not connected.": - #check if the board has ip in the wlan0 interface + # check if the board has ip in the wlan0 interface p = sh.ifconfig("wlan0") if p.exit_code == 0: - result = re.search("inet addr:(?!127\.0{1,3}\.0{1,3}\.0{0,2}1$)((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)", - p.stdout) + result = re.search( + 'inet addr:(?!127\.0{1,3}\.0{1,3}\.0{0,2}1$)((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)', + p.stdout.decode('ascii')) if result: # execute iperf command against the server if self.__bind is None: @@ -69,7 +70,7 @@ class Qwifi(unittest.TestCase): bwreal = b[0] # check if BW is in the expected range - self.failUnless(float(bwreal) > float(self.__OKBW) * 0.9, + self.failUnless(float(bwreal) > float(self.__bwexpected) * 0.9, "failed: speed is lower than spected. Speed(MB/s)" + str(bwreal)) else: self.fail("failed: could not complete iperf command") -- cgit v1.1 From 41ffba6a76a80a7ef4553cb8856393dd209d172e Mon Sep 17 00:00:00 2001 From: Hector Fernandez Date: Tue, 10 Mar 2020 17:37:16 +0100 Subject: First release of the test. All the tests work correctly for SOPA0000. --- test-cli/test/files/test_ok.png | Bin 18150 -> 0 bytes test-cli/test/files/usbtest/usbdatatest.bin | Bin 0 -> 33554431 bytes test-cli/test/files/usbtest/usbdatatest.md5 | 1 + test-cli/test/flashers/__init__.py | 0 test-cli/test/flashers/flasher.py | 10 ++++ test-cli/test/flashers/flasher_sopa0000.py | 13 +++++ test-cli/test/helpers/int_registers.py | 3 +- test-cli/test/helpers/uboot_flasher.py | 0 test-cli/test/runners/simple.py | 1 + test-cli/test/suites/__init__.py | 0 test-cli/test/tests/qduplex_ser.py | 18 +++++-- test-cli/test/tests/qflash.py | 77 ---------------------------- test-cli/test/tests/qserial.py | 8 +-- test-cli/test/tests/qusb.py | 10 +++- 14 files changed, 52 insertions(+), 89 deletions(-) delete mode 100644 test-cli/test/files/test_ok.png create mode 100644 test-cli/test/files/usbtest/usbdatatest.bin create mode 100644 test-cli/test/files/usbtest/usbdatatest.md5 create mode 100644 test-cli/test/flashers/__init__.py create mode 100644 test-cli/test/flashers/flasher.py create mode 100644 test-cli/test/flashers/flasher_sopa0000.py delete mode 100644 test-cli/test/helpers/uboot_flasher.py delete mode 100644 test-cli/test/suites/__init__.py delete mode 100644 test-cli/test/tests/qflash.py (limited to 'test-cli/test') diff --git a/test-cli/test/files/test_ok.png b/test-cli/test/files/test_ok.png deleted file mode 100644 index 6ccc7b3..0000000 Binary files a/test-cli/test/files/test_ok.png and /dev/null differ diff --git a/test-cli/test/files/usbtest/usbdatatest.bin b/test-cli/test/files/usbtest/usbdatatest.bin new file mode 100644 index 0000000..423eec3 Binary files /dev/null and b/test-cli/test/files/usbtest/usbdatatest.bin differ diff --git a/test-cli/test/files/usbtest/usbdatatest.md5 b/test-cli/test/files/usbtest/usbdatatest.md5 new file mode 100644 index 0000000..4358fb7 --- /dev/null +++ b/test-cli/test/files/usbtest/usbdatatest.md5 @@ -0,0 +1 @@ +6ef9717ac968b592803d0026f662a85e usbdatatest.bin diff --git a/test-cli/test/flashers/__init__.py b/test-cli/test/flashers/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/test-cli/test/flashers/flasher.py b/test-cli/test/flashers/flasher.py new file mode 100644 index 0000000..d962fca --- /dev/null +++ b/test-cli/test/flashers/flasher.py @@ -0,0 +1,10 @@ +from test.flashers.flasher_sopa0000 import flash_sopa0000 + + +def flash(modelid): + result = None + + if modelid.find("SOPA0000") == 0: + result = flash_sopa0000() + + return result diff --git a/test-cli/test/flashers/flasher_sopa0000.py b/test-cli/test/flashers/flasher_sopa0000.py new file mode 100644 index 0000000..818be91 --- /dev/null +++ b/test-cli/test/flashers/flasher_sopa0000.py @@ -0,0 +1,13 @@ +from test.helpers.syscmd import SysCommand + + +def flash_sopa0000(): + print("Sart programming Nand memory...") + str_cmd = "/usr/bin/igep-flash --skip-nandtest --image /opt/firmware/demo-ti-image-*-*.tar* >/dev/null 2>&1" + sync_command = SysCommand("sync_command", str_cmd) + if sync_command.execute() != 0: + print("Flasher: Could not complete flashing task.") + return 1 + else: + print("Flasher: NAND memory flashed succesfully.") + return 0 diff --git a/test-cli/test/helpers/int_registers.py b/test-cli/test/helpers/int_registers.py index 030035d..22a3d9b 100644 --- a/test-cli/test/helpers/int_registers.py +++ b/test-cli/test/helpers/int_registers.py @@ -55,7 +55,6 @@ def get_mac(modelid): # mac = mac + read(rg) # #erase trailing zeros # mac = mac[4::1] - mac = sh.cat("/sys/class/net/eth0/address") - + mac = sh.cat("/sys/class/net/eth0/address").strip() return mac diff --git a/test-cli/test/helpers/uboot_flasher.py b/test-cli/test/helpers/uboot_flasher.py deleted file mode 100644 index e69de29..0000000 diff --git a/test-cli/test/runners/simple.py b/test-cli/test/runners/simple.py index dd7c74d..f8b4dd4 100644 --- a/test-cli/test/runners/simple.py +++ b/test-cli/test/runners/simple.py @@ -65,6 +65,7 @@ class TextTestResult(unittest.TestResult): def addError(self, test, err): unittest.TestResult.addError(self, test, err) test.longMessage = err[1] + print(err[1]) self.result = self.ERROR def addFailure(self, test, err): diff --git a/test-cli/test/suites/__init__.py b/test-cli/test/suites/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/test-cli/test/tests/qduplex_ser.py b/test-cli/test/tests/qduplex_ser.py index 0666363..cb690cb 100644 --- a/test-cli/test/tests/qduplex_ser.py +++ b/test-cli/test/tests/qduplex_ser.py @@ -30,11 +30,7 @@ class Qduplex(unittest.TestCase): # open serial connection self.__serial1 = serial.Serial(self.__port1, self.__baudrate, timeout=1) - self.__serial1.flushInput() - self.__serial1.flushOutput() self.__serial2 = serial.Serial(self.__port2, self.__baudrate, timeout=1) - self.__serial2.flushInput() - self.__serial2.flushOutput() def __del__(self): self.__serial1.close() @@ -43,6 +39,12 @@ class Qduplex(unittest.TestCase): def execute(self): # generate a random uuid test_uuid = str(uuid.uuid4()).encode() + + # clean serial ports + self.__serial1.flushInput() + self.__serial1.flushOutput() + self.__serial2.flushInput() + self.__serial2.flushOutput() # send the uuid through serial port self.__serial1.write(test_uuid) time.sleep(0.05) # there might be a small delay @@ -52,7 +54,13 @@ class Qduplex(unittest.TestCase): if self.__serial2.readline() != test_uuid: self.fail("failed: port {} write/read mismatch".format(self.__port2)) - test_uuid = str(uuid.uuid4()).encode() + time.sleep(0.05) # there might be a small delay + + # clean serial ports + self.__serial1.flushInput() + self.__serial1.flushOutput() + self.__serial2.flushInput() + self.__serial2.flushOutput() # send the uuid through serial port self.__serial2.write(test_uuid) time.sleep(0.05) # there might be a small delay diff --git a/test-cli/test/tests/qflash.py b/test-cli/test/tests/qflash.py deleted file mode 100644 index 59ed13d..0000000 --- a/test-cli/test/tests/qflash.py +++ /dev/null @@ -1,77 +0,0 @@ -from test.helpers.syscmd import SysCommand -import unittest -from test.helpers.globalVariables import globalVar - - -class Qflasher(unittest.TestCase): - params = None - - def __init__(self, testname, testfunc, varlist): - self.params = varlist - super(Qflasher, self).__init__(testfunc) - self._testMethodDoc = testname - model=globalVar.g_mid - if model.find("IGEP0046") == 0: - self._flash_method = "mx6" - self._binlocation="/boot/" - elif model.find("IGEP0034") == 0: - self._flash_method = "nandti" - self._binlocation = "/boot/" - elif model.find("SOPA") == 0: - self._flash_method = "sopaflash" - elif model.find("OMAP3") == 0: - self._flash_method = "nandti" - self._binlocation = "/boot/" - elif model.find("OMAP5") == 0: - self._flash_method = "nandti" - self._binlocation = "/boot/" - - - def execute(self): - # CASE eMMC boards. - if(self._flash_method == "mx6"): - str_cmd= "dd if={}u-boot.imx of=/dev/mmcblk2 bs=512 seek=2 2>&1 >/dev/null".format(self._binlocation) - flash_command = SysCommand("flash_command", str_cmd) - if flash_command.execute() == 0: - str_cmd = "sync" - sync_command = SysCommand("sync_command", str_cmd) - if sync_command.execute() != 0: - self.fail("failed: could not sync") - else: - self.fail("failed: could not complete flash eMMC commands") - # CASE of nandflash boards - elif(self._flash_method == "nandti"): - str_cmd = "nandwrite -p -s 0x0 /dev/mtd0 {}u-boot.img 2>&1 >/dev/null; " \ - "nandwrite -p -s 0x20000 /dev/mtd0 {}u-boot.img 2>&1 >/dev/null; " \ - "nandwrite -p -s 0x40000 /dev/mtd0 {}u-boot.img 2>&1 >/dev/null; " \ - "nandwrite -p -s 0x60000 /dev/mtd0 {}u-boot.img 2>&1 >/dev/null; " \ - "".format(self._binlocation, self._binlocation, self._binlocation, self._binlocation,) - flash_MLO_command = SysCommand("flash_MLO_command", str_cmd) - if flash_MLO_command.execute() == 0: - str_cmd= "nandwrite -p /dev/mtd1 {}u-boot.img 2>&1 >/dev/null".format(self._binlocation) - flash_uBoot_command = SysCommand("flash_command", str_cmd) - if flash_uBoot_command.execute() == 0: - str_cmd = "sync" - sync_command = SysCommand("sync_command", str_cmd) - if sync_command.execute() != 0: - self.fail("failed: could not sync") - else: - self.fail("failed: could not complete flash u-boot commnds") - else: - self.fail("failed: could not complete flash MLO commnd") - - - # CASE of SOPA0000 BOARD. FULL FLASH (u-boot+kernel+rootfs) - elif (self._flash_method == "sopaflash"): - str_cmd = "nandtest /dev/mtd0 >/dev/null" - flash_command = SysCommand("flash_command", str_cmd) - if flash_command.execute() == 0: - str_cmd = "/usr/bin/igep-flash --skip-nandtest --image /opt/firmware/demo-ti-image-*-*.tar* >/dev/null 2>&1" - sync_command = SysCommand("sync_command", str_cmd) - if sync_command.execute() != 0: - self.fail("failed: could not complete flashing procces") - else: - self.fail("failed: could not complete nandtest mtd0") - - else: - self.fail("failed: could not find flash method") diff --git a/test-cli/test/tests/qserial.py b/test-cli/test/tests/qserial.py index 67e3af1..45c9d03 100644 --- a/test-cli/test/tests/qserial.py +++ b/test-cli/test/tests/qserial.py @@ -9,7 +9,7 @@ class Qserial(unittest.TestCase): __port = None __baudrate = None - #varlist: port, baudrate + # varlist: port, baudrate def __init__(self, testname, testfunc, varlist): self.params = varlist super(Qserial, self).__init__(testfunc) @@ -26,8 +26,6 @@ class Qserial(unittest.TestCase): # open serial connection self.__serial = serial.Serial(self.__port, self.__baudrate, timeout=1) - self.__serial.flushInput() - self.__serial.flushOutput() def __del__(self): self.__serial.close() @@ -35,6 +33,9 @@ class Qserial(unittest.TestCase): def execute(self): # generate a random uuid test_uuid = str(uuid.uuid4()).encode() + # clean serial port + self.__serial.flushInput() + self.__serial.flushOutput() # send the uuid through serial port self.__serial.write(test_uuid) time.sleep(0.05) # there might be a small delay @@ -44,4 +45,3 @@ class Qserial(unittest.TestCase): # check if what it was sent is equal to what has been received if self.__serial.readline() != test_uuid: self.fail("failed: port {} write/read mismatch".format(self.__port)) - diff --git a/test-cli/test/tests/qusb.py b/test-cli/test/tests/qusb.py index 6a004f0..6c22c48 100644 --- a/test-cli/test/tests/qusb.py +++ b/test-cli/test/tests/qusb.py @@ -21,11 +21,19 @@ class Qusb(unittest.TestCase): device = q.group(0) # create a new folder where the pendrive is going to be mounted sh.mkdir("-p", "/mnt/pendrive") + # check if the device is mounted, and umount it + try: + p = sh.findmnt("-n", device) + if p.exit_code == 0: + sh.umount(device) + except sh.ErrorReturnCode_1: + # error = 1 means "no found" + pass # mount the device p = sh.mount(device, "/mnt/pendrive") if p.exit_code == 0: # copy files - p = sh.cp("/root/usbtest/usbdatatest.bin", "/root/usbtest/usbdatatest.md5", "/mnt/pendrive") + p = sh.cp("test/files/usbtest/usbdatatest.bin", "test/files/usbtest/usbdatatest.md5", "/mnt/pendrive") if p.exit_code == 0: # check md5 with changedir("/mnt/pendrive/"): -- cgit v1.1 From e74e0a36d9ad6a01c04500f3a24cb0ef5dd0b283 Mon Sep 17 00:00:00 2001 From: Hector Fernandez Date: Fri, 13 Mar 2020 12:17:51 +0100 Subject: Added final flashing tasks: eeprom and nand. --- test-cli/test/flashers/flasheeprom.py | 36 +++++++ test-cli/test/flashers/flasher.py | 10 -- test-cli/test/flashers/flasher_sopa0000.py | 13 --- test-cli/test/flashers/flashmemory.py | 12 +++ test-cli/test/helpers/finisher.py | 151 ----------------------------- test-cli/test/helpers/globalVariables.py | 1 + test-cli/test/helpers/int_registers.py | 1 + test-cli/test/helpers/syscmd.py | 1 - test-cli/test/helpers/testsrv_db.py | 49 +++++++++- test-cli/test/runners/simple.py | 6 -- 10 files changed, 94 insertions(+), 186 deletions(-) create mode 100644 test-cli/test/flashers/flasheeprom.py delete mode 100644 test-cli/test/flashers/flasher.py delete mode 100644 test-cli/test/flashers/flasher_sopa0000.py create mode 100644 test-cli/test/flashers/flashmemory.py delete mode 100644 test-cli/test/helpers/finisher.py (limited to 'test-cli/test') diff --git a/test-cli/test/flashers/flasheeprom.py b/test-cli/test/flashers/flasheeprom.py new file mode 100644 index 0000000..e427b87 --- /dev/null +++ b/test-cli/test/flashers/flasheeprom.py @@ -0,0 +1,36 @@ +import os +import binascii + + +def flash_eeprom(eeprompath, boarduuid, mac0, mac1=None): + print("Start programming Eeprom...") + # check if eeprompath is correct + if os.path.isfile(eeprompath): + # create u-boot data struct + data = bytearray() + data += (2029785358).to_bytes(4, 'big') # magicid --> 0x78FC110E + data += bytearray([0, 0, 0, 0]) # crc32 = 0 + data += bytearray(boarduuid + "\0", + 'ascii') # uuid --> 'c0846c8a-5fa5-11ea-8576-f8b156ac62d7' and \0 at the end + data += binascii.unhexlify(mac0.replace(':', '')) # mac0 --> 'f8:b1:56:ac:62:d7' + if mac1 is not None: + data += binascii.unhexlify(mac1.replace(':', '')) # mac1 --> 'f8:b1:56:ac:62:d7' + else: + data += bytearray([0, 0, 0, 0, 0, 0]) # mac1 --> 0:0:0:0:0:0 + # calculate crc + crc = (binascii.crc32(data, 0)).to_bytes(4, 'big') + data[4:8] = crc + # write into eeprom and read back + f = open(eeprompath, "r+b") + f.write(data) + f.seek(0) + data_rx = f.read(57) + for i in range(57): + if data_rx[i] != data[i]: + print("Error while programming eeprom memory.") + return 1 + print("Eeprom programmed succesfully.") + return 0 + else: + print("eeprom memory not found.") + return 1 diff --git a/test-cli/test/flashers/flasher.py b/test-cli/test/flashers/flasher.py deleted file mode 100644 index d962fca..0000000 --- a/test-cli/test/flashers/flasher.py +++ /dev/null @@ -1,10 +0,0 @@ -from test.flashers.flasher_sopa0000 import flash_sopa0000 - - -def flash(modelid): - result = None - - if modelid.find("SOPA0000") == 0: - result = flash_sopa0000() - - return result diff --git a/test-cli/test/flashers/flasher_sopa0000.py b/test-cli/test/flashers/flasher_sopa0000.py deleted file mode 100644 index 818be91..0000000 --- a/test-cli/test/flashers/flasher_sopa0000.py +++ /dev/null @@ -1,13 +0,0 @@ -from test.helpers.syscmd import SysCommand - - -def flash_sopa0000(): - print("Sart programming Nand memory...") - str_cmd = "/usr/bin/igep-flash --skip-nandtest --image /opt/firmware/demo-ti-image-*-*.tar* >/dev/null 2>&1" - sync_command = SysCommand("sync_command", str_cmd) - if sync_command.execute() != 0: - print("Flasher: Could not complete flashing task.") - return 1 - else: - print("Flasher: NAND memory flashed succesfully.") - return 0 diff --git a/test-cli/test/flashers/flashmemory.py b/test-cli/test/flashers/flashmemory.py new file mode 100644 index 0000000..ac59be5 --- /dev/null +++ b/test-cli/test/flashers/flashmemory.py @@ -0,0 +1,12 @@ +import sh + + +def flash_memory(imagefile): + print("Sart programming Nand memory...") + p = sh.bash("/usr/bin/igep-flash", "--skip-nandtest", "--image", "/opt/firmware/" + imagefile) + if p.exit_code != 0: + print("Flasher: Could not complete flashing task.") + return 1 + else: + print("Flasher: NAND memory flashed succesfully.") + return 0 diff --git a/test-cli/test/helpers/finisher.py b/test-cli/test/helpers/finisher.py deleted file mode 100644 index 73142d9..0000000 --- a/test-cli/test/helpers/finisher.py +++ /dev/null @@ -1,151 +0,0 @@ -from test.helpers.syscmd import SysCommand -from test.helpers.globalVariables import globalVar -import binascii -import uuid -import subprocess -from PIL import Image, ImageDraw, ImageFont -import qrcode -import PIL - -class Finisher(object): - __muhb = None - __final_to_burn_to_eeprom = None - __qr_image = None - - def __init__(self, muhb = None): - self.__muhb = muhb - self.__final_to_burn_to_eeprom = bytearray() - self.__qr_image = None - pass - - def eeprom_burn(self): - ## Create binary file - str_cmd2 = "find /sys/ -iname 'eeprom'" - eeprom_location = SysCommand("eeprom_location", str_cmd2) - if eeprom_location.execute() == 0: - raw_out = eeprom_location.getOutput() - if raw_out == "": - self.fail("Unable to get EEPROM location. IS EEPROM CONNECTED?") - eeprom = raw_out.decode('ascii') - eeprom = eeprom.strip('\n') - ## push binary data to eeprom like if working with files - file2 = open(eeprom, "w+b") - file2.write(self.__final_to_burn_to_eeprom) - else: - self.fail("failed: could not complete find eeprom command") - - def generate_qr_stamp(self): - # Generate QR to put in a stamp - qr = qrcode.QRCode( - version=1, - error_correction=qrcode.constants.ERROR_CORRECT_L, - box_size=10, - border=4, - ) - # Use board_uuid to generate the QR code - qr.add_data(globalVar.g_uuid) - qr.make(fit=True) - # Save QR as image stamp.png - img = qr.make_image() - # Store QR as a class atrib - self.__qr_image = img - img.save('/home/root/stamp.png') - - def print_stamp(self): - # Print stamp by sending a cmd to the printer - str_cmd3 = "lpr -o scaling=4 stamp.png".format(self.__display) - printstamp = SysCommand("printstamp", str_cmd3) - if printstamp.execute() != 0: - self.fail("failed: could not print stamp") - - def generate_screen(self): - # Generate green image with board uuid and QR maybe pasted on top of green image - # Define image size - W = 1250 - H = 703 - # Create blank rectangle to write on - image = Image.new('RGB', (W, H), (46, 204, 113, 0)) - draw = ImageDraw.Draw(image) - message = "TEST OK\n\n" + "Board UUID: "+ globalVar.g_uuid - font = ImageFont.truetype('/usr/share/fonts/truetype/dejavuu/DejaVuSans.ttf', 40) - # Calculate the width and height of the text to be drawn, given font size - w, h = draw.textsize(message, font=font) - # Write the text to the image, where (x,y) is the top left corner of the text - draw.text(((W-w)/2,(H-h)/2), message, align='center', font=font) - #draw.image(self.__qr_image) - image.save('/home/root/test/files/test_ok.png') - - def show_result_screen(self): - # If test OK show test_OK.png located in /home/root, If test fail show test_fail.png, located in /home/root/test/files/test_KO.png - if globalVar.fstatus: - str_cmd4 = "fbi -T 1 --noverbose -d /dev/{} test/files/test_ok.png".format('fb0') - else: - str_cmd4 = "fbi -T 1 --noverbose -d /dev/{} test/files/test_ko.png".format('fb0') - - display_image = SysCommand("display_image", str_cmd4) - #print(display_image.execute()) - if display_image.execute() != -1: - self.fail("failed: could not display the image") - - - def end_ok(self): - # Burn retrieved igep eeprom struct - new = self.__muhb[0][0] - - # Convert from string to hex - hnew = new.encode() - # Magic_id and default crc32 0x6d, 0x6a, 0x6d, 0xe4 with endianess changed so that u-boot loads it correctly - # IF magic ever changes this magic_id should be changed. At the end always magic_id of test and u-boot should - # be the same - magic_id = bytes([0xe4, 0x6d, 0x6a, 0x6d]) - default_igep_crc32 = bytes([0x00, 0x00, 0x00, 0x00]) - - # Create bytearray - to_calculate = bytearray() - # Build the final hex binary for crc32 operation - to_calculate.extend(magic_id) - to_calculate.extend(default_igep_crc32) - to_calculate.extend(hnew) - - # Calculate crc32! - new_crc32 = binascii.crc32(to_calculate) - hnew_crc32 = new_crc32.to_bytes(4, byteorder="little") - - # Recreate final eeprom struct in bytearray - self.__final_to_burn_to_eeprom = bytearray() - self.__final_to_burn_to_eeprom.extend(magic_id) - self.__final_to_burn_to_eeprom.extend(hnew_crc32) - self.__final_to_burn_to_eeprom.extend(hnew) - self.eeprom_burn() - - # Generate QR stamp - self.generate_qr_stamp() - # Send print stamp command - #self.print_stamp() - # Generate green image with board uuid and QR maybe pasted on top of green image - self.generate_screen() - # Show test_ok.png image in screen - self.show_result_screen() - - def end_fail(self): - # Burn igep eeprom bug struct - hnew = self.__muhb.encode() - default_fail = bytes([0xD0, 0xBA, 0xD0, 0xBA]) - self.__final_burn_to_eeprom = bytearray() - self.__final_to_burn_to_eeprom.extend(default_fail) - self.__final_to_burn_to_eeprom.extend(default_fail) - self.__final_to_burn_to_eeprom.extend(hnew) - self.__final_to_burn_to_eeprom.extend(default_fail) - self.__final_to_burn_to_eeprom.extend(default_fail) - self.__final_to_burn_to_eeprom.extend(default_fail) - self.__final_to_burn_to_eeprom.extend(default_fail) - self.__final_to_burn_to_eeprom.extend(default_fail) - self.__final_to_burn_to_eeprom.extend(default_fail) - self.__final_to_burn_to_eeprom.extend(default_fail) - self.__final_to_burn_to_eeprom.extend(default_fail) - self.__final_to_burn_to_eeprom.extend(default_fail) - self.__final_to_burn_to_eeprom.extend(default_fail) - self.__final_to_burn_to_eeprom.extend(default_fail) - self.eeprom_burn() - # Show test_ko.png image in screen - self.show_result_screen() \ No newline at end of file diff --git a/test-cli/test/helpers/globalVariables.py b/test-cli/test/helpers/globalVariables.py index 6b89f4d..baaae57 100644 --- a/test-cli/test/helpers/globalVariables.py +++ b/test-cli/test/helpers/globalVariables.py @@ -6,3 +6,4 @@ def globalVar(): g_mid = "" outdata = "NONE" station = "" + taskid_ctl = "" diff --git a/test-cli/test/helpers/int_registers.py b/test-cli/test/helpers/int_registers.py index 22a3d9b..0feb8da 100644 --- a/test-cli/test/helpers/int_registers.py +++ b/test-cli/test/helpers/int_registers.py @@ -55,6 +55,7 @@ def get_mac(modelid): # mac = mac + read(rg) # #erase trailing zeros # mac = mac[4::1] + # # To be finished... mac = sh.cat("/sys/class/net/eth0/address").strip() return mac diff --git a/test-cli/test/helpers/syscmd.py b/test-cli/test/helpers/syscmd.py index a869bd7..6114449 100644 --- a/test-cli/test/helpers/syscmd.py +++ b/test-cli/test/helpers/syscmd.py @@ -1,6 +1,5 @@ import unittest import subprocess -from test.helpers.globalVariables import globalVar class TestSysCommand(unittest.TestCase): diff --git a/test-cli/test/helpers/testsrv_db.py b/test-cli/test/helpers/testsrv_db.py index 9fb61fd..c9372fc 100644 --- a/test-cli/test/helpers/testsrv_db.py +++ b/test-cli/test/helpers/testsrv_db.py @@ -51,14 +51,13 @@ class TestSrv_Database(object): try: res = self.__sqlObject.db_execute_query(sql) # print(res) - return res; + return res except Exception as err: r = find_between(str(err), '#', '#') # print(r) return None def get_test_params_list(self, testid): - '''get the board test list''' sql = "SELECT * FROM isee.f_get_test_params_list({})".format(testid) # print('>>>' + sql) try: @@ -71,7 +70,6 @@ class TestSrv_Database(object): return None def open_test(self, board_uuid): - '''get the board test list''' sql = "SELECT * FROM isee.f_open_test('{}')".format(board_uuid) # print('>>>' + sql) try: @@ -84,7 +82,6 @@ class TestSrv_Database(object): return None def run_test(self, testid_ctl, testid): - '''get the board test list''' sql = "SELECT isee.f_run_test({},{})".format(testid_ctl, testid) # print('>>>' + sql) try: @@ -95,7 +92,6 @@ class TestSrv_Database(object): return None def finish_test(self, testid_ctl, testid, newstatus): - '''get the board test list''' sql = "SELECT isee.f_finish_test({},{},'{}')".format(testid_ctl, testid, newstatus) # print('>>>' + sql) try: @@ -117,3 +113,46 @@ class TestSrv_Database(object): # print(r) return None + def get_board_macaddr(self, board_uuid): + sql = "SELECT * FROM isee.f_get_board_macaddr('{}')".format(board_uuid) + # print('>>>' + sql) + try: + res = self.__sqlObject.db_execute_query(sql) + # print(res) + return res[0][0] + except Exception as err: + r = find_between(str(err), '#', '#') + # print(r) + return None + + def create_process(self, testid_ctl): + sql = "SELECT * FROM isee.f_create_process({})".format(testid_ctl) + # print('>>>' + sql) + try: + res = self.__sqlObject.db_execute_query(sql) + # print(res) + return res[0][0] + except Exception as err: + r = find_between(str(err), '#', '#') + # print(r) + return None + + def create_task_result(self, taskid_ctl, name, newstatus): + sql = "SELECT isee.f_create_task_result({},'{}','{}')".format(taskid_ctl, name, newstatus) + # print('>>>' + sql) + try: + self.__sqlObject.db_execute_query(sql) + except Exception as err: + r = find_between(str(err), '#', '#') + # print(r) + return None + + def update_taskctl_status(self, taskid_ctl, newstatus): + sql = "SELECT isee.f_update_taskctl_status({},'{}')".format(taskid_ctl, newstatus) + # print('>>>' + sql) + try: + self.__sqlObject.db_execute_query(sql) + except Exception as err: + r = find_between(str(err), '#', '#') + # print(r) + return None diff --git a/test-cli/test/runners/simple.py b/test-cli/test/runners/simple.py index f8b4dd4..a165406 100644 --- a/test-cli/test/runners/simple.py +++ b/test-cli/test/runners/simple.py @@ -1,5 +1,3 @@ -#!/usr/bin/env python - """ Simple Test Runner for unittest module @@ -7,9 +5,6 @@ Simple Test Runner for unittest module import sys import unittest -import os -from test.helpers.globalVariables import globalVar -from test.helpers.testsrv_db import TestSrv_Database class SimpleTestRunner: @@ -65,7 +60,6 @@ class TextTestResult(unittest.TestResult): def addError(self, test, err): unittest.TestResult.addError(self, test, err) test.longMessage = err[1] - print(err[1]) self.result = self.ERROR def addFailure(self, test, err): -- cgit v1.1 From 71d9a1f0b6bb4389cb9b0760ce4e847574fdcd45 Mon Sep 17 00:00:00 2001 From: Hector Fernandez Date: Fri, 13 Mar 2020 12:36:14 +0100 Subject: SOPA0000 test: Saved the variable data used during the eeprom and nand flashing. --- test-cli/test/helpers/testsrv_db.py | 4 ++-- test-cli/test/tests/qnand.py | 2 +- test-cli/test/tests/qram.py | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) (limited to 'test-cli/test') diff --git a/test-cli/test/helpers/testsrv_db.py b/test-cli/test/helpers/testsrv_db.py index c9372fc..a6a5545 100644 --- a/test-cli/test/helpers/testsrv_db.py +++ b/test-cli/test/helpers/testsrv_db.py @@ -137,8 +137,8 @@ class TestSrv_Database(object): # print(r) return None - def create_task_result(self, taskid_ctl, name, newstatus): - sql = "SELECT isee.f_create_task_result({},'{}','{}')".format(taskid_ctl, name, newstatus) + def create_task_result(self, taskid_ctl, name, newstatus, info=None): + sql = "SELECT isee.f_create_task_result({},'{}','{}','{}')".format(taskid_ctl, name, newstatus, info) # print('>>>' + sql) try: self.__sqlObject.db_execute_query(sql) diff --git a/test-cli/test/tests/qnand.py b/test-cli/test/tests/qnand.py index 5125c1c..10a68f2 100644 --- a/test-cli/test/tests/qnand.py +++ b/test-cli/test/tests/qnand.py @@ -18,6 +18,6 @@ class Qnand(unittest.TestCase): def execute(self): try: - sh.nandtest("-m", self.__device) + sh.nandtest("-m", self.__device, _out="/dev/null") except sh.ErrorReturnCode as e: self.fail("failed: could not complete nandtest command") diff --git a/test-cli/test/tests/qram.py b/test-cli/test/tests/qram.py index cc75b68..5a7734a 100644 --- a/test-cli/test/tests/qram.py +++ b/test-cli/test/tests/qram.py @@ -23,6 +23,6 @@ class Qram(unittest.TestCase): def execute(self): try: - sh.memtester(self.__memsize, "1") + sh.memtester(self.__memsize, "1", _out="/dev/null") except sh.ErrorReturnCode as e: self.fail("failed: could not complete memtester command") -- cgit v1.1 From a85534544fad3c51d8af8d65e7fde6cb5d07978b Mon Sep 17 00:00:00 2001 From: Hector Fernandez Date: Fri, 13 Mar 2020 14:30:21 +0100 Subject: Changed tasks to be independent of tests. --- test-cli/test/helpers/testsrv_db.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'test-cli/test') diff --git a/test-cli/test/helpers/testsrv_db.py b/test-cli/test/helpers/testsrv_db.py index a6a5545..27024ce 100644 --- a/test-cli/test/helpers/testsrv_db.py +++ b/test-cli/test/helpers/testsrv_db.py @@ -101,8 +101,8 @@ class TestSrv_Database(object): # print(r) return None - def get_board_variables(self, board_uuid): - sql = "SELECT * FROM isee.f_get_boardvariables('{}')".format(board_uuid) + def get_task_variables_list(self, board_uuid): + sql = "SELECT * FROM isee.f_get_task_variables_list('{}')".format(board_uuid) # print('>>>' + sql) try: res = self.__sqlObject.db_execute_query(sql) @@ -125,8 +125,8 @@ class TestSrv_Database(object): # print(r) return None - def create_process(self, testid_ctl): - sql = "SELECT * FROM isee.f_create_process({})".format(testid_ctl) + def open_task(self, uuid): + sql = "SELECT * FROM isee.f_open_task('{}')".format(uuid) # print('>>>' + sql) try: res = self.__sqlObject.db_execute_query(sql) -- cgit v1.1 From f013d0a76976a52fce979036df404826dcbf385b Mon Sep 17 00:00:00 2001 From: Hector Fernandez Date: Tue, 17 Mar 2020 18:27:59 +0100 Subject: Added return values after flashing, to be saved in the DB. --- test-cli/test/flashers/flasheeprom.py | 53 ++++++++++++++++++++++++----------- test-cli/test/flashers/flashmemory.py | 2 +- 2 files changed, 37 insertions(+), 18 deletions(-) (limited to 'test-cli/test') diff --git a/test-cli/test/flashers/flasheeprom.py b/test-cli/test/flashers/flasheeprom.py index e427b87..bdeb7e6 100644 --- a/test-cli/test/flashers/flasheeprom.py +++ b/test-cli/test/flashers/flasheeprom.py @@ -2,24 +2,41 @@ import os import binascii +def _generate_data_bytes(boarduuid, mac0, mac1): + data = bytearray() + data += (2029785358).to_bytes(4, 'big') # magicid --> 0x78FC110E + data += bytearray([0, 0, 0, 0]) # crc32 = 0 + data += bytearray(boarduuid + "\0", + 'ascii') # uuid --> 'c0846c8a-5fa5-11ea-8576-f8b156ac62d7' and \0 at the end + data += binascii.unhexlify(mac0.replace(':', '')) # mac0 --> 'f8:b1:56:ac:62:d7' + if mac1 is not None: + data += binascii.unhexlify(mac1.replace(':', '')) # mac1 --> 'f8:b1:56:ac:62:d7' + else: + data += bytearray([0, 0, 0, 0, 0, 0]) # mac1 --> 0:0:0:0:0:0 + # calculate crc + crc = (binascii.crc32(data, 0)).to_bytes(4, 'big') + data[4:8] = crc + return data + + +def _generate_output_data(data_rx): + boarduuid = data_rx[8:45].decode + mac0 = binascii.hexlify(data_rx[45:53]).decode() + mac1 = binascii.hexlify(data_rx[53:61]).decode() + smac0 = '-'.join(mac0[i:i + 2] for i in range(0, len(mac0), 2)) + smac1 = '-'.join(mac1[i:i + 2] for i in range(0, len(mac1), 2)) + eepromdata = "UUID :" + boarduuid + " MAC0:" + smac0 + " MAC1:" + smac1 + + return eepromdata + + +# returns exitcode and data saved into eeprom def flash_eeprom(eeprompath, boarduuid, mac0, mac1=None): print("Start programming Eeprom...") # check if eeprompath is correct if os.path.isfile(eeprompath): # create u-boot data struct - data = bytearray() - data += (2029785358).to_bytes(4, 'big') # magicid --> 0x78FC110E - data += bytearray([0, 0, 0, 0]) # crc32 = 0 - data += bytearray(boarduuid + "\0", - 'ascii') # uuid --> 'c0846c8a-5fa5-11ea-8576-f8b156ac62d7' and \0 at the end - data += binascii.unhexlify(mac0.replace(':', '')) # mac0 --> 'f8:b1:56:ac:62:d7' - if mac1 is not None: - data += binascii.unhexlify(mac1.replace(':', '')) # mac1 --> 'f8:b1:56:ac:62:d7' - else: - data += bytearray([0, 0, 0, 0, 0, 0]) # mac1 --> 0:0:0:0:0:0 - # calculate crc - crc = (binascii.crc32(data, 0)).to_bytes(4, 'big') - data[4:8] = crc + data = _generate_data_bytes(boarduuid, mac0, mac1) # write into eeprom and read back f = open(eeprompath, "r+b") f.write(data) @@ -28,9 +45,11 @@ def flash_eeprom(eeprompath, boarduuid, mac0, mac1=None): for i in range(57): if data_rx[i] != data[i]: print("Error while programming eeprom memory.") - return 1 + return 1, None print("Eeprom programmed succesfully.") - return 0 + # generated eeprom read data + eepromdata = _generate_output_data(data_rx) + return 0, eepromdata else: - print("eeprom memory not found.") - return 1 + print("Eeprom memory not found.") + return 1, None diff --git a/test-cli/test/flashers/flashmemory.py b/test-cli/test/flashers/flashmemory.py index ac59be5..c7267c6 100644 --- a/test-cli/test/flashers/flashmemory.py +++ b/test-cli/test/flashers/flashmemory.py @@ -2,7 +2,7 @@ import sh def flash_memory(imagefile): - print("Sart programming Nand memory...") + print("Start programming Nand memory...") p = sh.bash("/usr/bin/igep-flash", "--skip-nandtest", "--image", "/opt/firmware/" + imagefile) if p.exit_code != 0: print("Flasher: Could not complete flashing task.") -- cgit v1.1 From 686893803c05fedd38a24bb1f661f8aeb7c652fe Mon Sep 17 00:00:00 2001 From: Hector Fernandez Date: Thu, 19 Mar 2020 16:33:53 +0100 Subject: Fixed problem generating dataepprom string. --- test-cli/test/flashers/flasheeprom.py | 12 ++++++------ test-cli/test/helpers/testsrv_db.py | 4 ++-- 2 files changed, 8 insertions(+), 8 deletions(-) (limited to 'test-cli/test') diff --git a/test-cli/test/flashers/flasheeprom.py b/test-cli/test/flashers/flasheeprom.py index bdeb7e6..fe1a4b2 100644 --- a/test-cli/test/flashers/flasheeprom.py +++ b/test-cli/test/flashers/flasheeprom.py @@ -20,12 +20,12 @@ def _generate_data_bytes(boarduuid, mac0, mac1): def _generate_output_data(data_rx): - boarduuid = data_rx[8:45].decode - mac0 = binascii.hexlify(data_rx[45:53]).decode() - mac1 = binascii.hexlify(data_rx[53:61]).decode() - smac0 = '-'.join(mac0[i:i + 2] for i in range(0, len(mac0), 2)) - smac1 = '-'.join(mac1[i:i + 2] for i in range(0, len(mac1), 2)) - eepromdata = "UUID :" + boarduuid + " MAC0:" + smac0 + " MAC1:" + smac1 + boarduuid = data_rx[8:45].decode() + mac0 = binascii.hexlify(data_rx[45:51]).decode() + mac1 = binascii.hexlify(data_rx[51:57]).decode() + smac0 = ':'.join(mac0[i:i + 2] for i in range(0, len(mac0), 2)) + smac1 = ':'.join(mac1[i:i + 2] for i in range(0, len(mac1), 2)) + eepromdata = "UUID:" + boarduuid + " MAC0:" + smac0 + " MAC1:" + smac1 return eepromdata diff --git a/test-cli/test/helpers/testsrv_db.py b/test-cli/test/helpers/testsrv_db.py index 27024ce..bf51acf 100644 --- a/test-cli/test/helpers/testsrv_db.py +++ b/test-cli/test/helpers/testsrv_db.py @@ -137,8 +137,8 @@ class TestSrv_Database(object): # print(r) return None - def create_task_result(self, taskid_ctl, name, newstatus, info=None): - sql = "SELECT isee.f_create_task_result({},'{}','{}','{}')".format(taskid_ctl, name, newstatus, info) + def create_task_result(self, taskid_ctl, name, newstatus, newinfo=None): + sql = "SELECT isee.f_create_task_result({},'{}','{}','{}')".format(taskid_ctl, name, newstatus, newinfo) # print('>>>' + sql) try: self.__sqlObject.db_execute_query(sql) -- cgit v1.1 From 0c610ebbef5928f17ec8c14d872b4d4298d3c4fb Mon Sep 17 00:00:00 2001 From: Hector Fernandez Date: Wed, 1 Apr 2020 11:45:07 +0200 Subject: Modificada la IP del servidor. Arreglado error al enviar los datos de la eeprom grabada a la BD. --- test-cli/test/flashers/flasheeprom.py | 9 +++++---- test-cli/test/helpers/testsrv_db.py | 4 ++-- 2 files changed, 7 insertions(+), 6 deletions(-) (limited to 'test-cli/test') diff --git a/test-cli/test/flashers/flasheeprom.py b/test-cli/test/flashers/flasheeprom.py index fe1a4b2..71c1bdd 100644 --- a/test-cli/test/flashers/flasheeprom.py +++ b/test-cli/test/flashers/flasheeprom.py @@ -1,5 +1,6 @@ import os import binascii +from test.helpers.globalVariables import globalVar def _generate_data_bytes(boarduuid, mac0, mac1): @@ -20,12 +21,12 @@ def _generate_data_bytes(boarduuid, mac0, mac1): def _generate_output_data(data_rx): - boarduuid = data_rx[8:45].decode() - mac0 = binascii.hexlify(data_rx[45:51]).decode() - mac1 = binascii.hexlify(data_rx[51:57]).decode() + boarduuid = data_rx[8:44].decode('ascii') # no 8:45 porque el \0 final hace que no funcione postgresql + mac0 = binascii.hexlify(data_rx[45:51]).decode('ascii') + mac1 = binascii.hexlify(data_rx[51:57]).decode('ascii') smac0 = ':'.join(mac0[i:i + 2] for i in range(0, len(mac0), 2)) smac1 = ':'.join(mac1[i:i + 2] for i in range(0, len(mac1), 2)) - eepromdata = "UUID:" + boarduuid + " MAC0:" + smac0 + " MAC1:" + smac1 + eepromdata = "UUID " + boarduuid + " , MAC0 " + smac0 + " , MAC1 " + smac1 return eepromdata diff --git a/test-cli/test/helpers/testsrv_db.py b/test-cli/test/helpers/testsrv_db.py index bf51acf..d563e74 100644 --- a/test-cli/test/helpers/testsrv_db.py +++ b/test-cli/test/helpers/testsrv_db.py @@ -139,12 +139,12 @@ class TestSrv_Database(object): def create_task_result(self, taskid_ctl, name, newstatus, newinfo=None): sql = "SELECT isee.f_create_task_result({},'{}','{}','{}')".format(taskid_ctl, name, newstatus, newinfo) - # print('>>>' + sql) + print('>>>' + sql) try: self.__sqlObject.db_execute_query(sql) except Exception as err: r = find_between(str(err), '#', '#') - # print(r) + print(r) return None def update_taskctl_status(self, taskid_ctl, newstatus): -- cgit v1.1 From f86887baef80509460da0bff8f48b2900a627282 Mon Sep 17 00:00:00 2001 From: Hector Fernandez Date: Mon, 13 Apr 2020 09:49:51 +0200 Subject: Added new DB functions. Added Qrreader.py file. --- test-cli/test/helpers/qrreader.py | 120 ++++++++++++++++++++++++++++++++++++ test-cli/test/helpers/testsrv_db.py | 25 +++++++- test-cli/test/tests/qethernet.py | 11 +--- test-cli/test/tests/qwifi.py | 1 + 4 files changed, 146 insertions(+), 11 deletions(-) create mode 100644 test-cli/test/helpers/qrreader.py (limited to 'test-cli/test') diff --git a/test-cli/test/helpers/qrreader.py b/test-cli/test/helpers/qrreader.py new file mode 100644 index 0000000..1d3768b --- /dev/null +++ b/test-cli/test/helpers/qrreader.py @@ -0,0 +1,120 @@ +import evdev +from evdev import InputDevice, categorize, ecodes +import threading +import time +import selectors +from selectors import DefaultSelector, EVENT_READ + +selector = selectors.DefaultSelector() + +qrdevice_list = [ + "Honeywell Imaging & Mobility 1900", + "Manufacturer Barcode Reader" +] + + +qrkey_list = { 'KEY_0':'0', + 'KEY_1':'1', + 'KEY_2':'2', + 'KEY_3':'3', + 'KEY_4':'4', + 'KEY_5':'5', + 'KEY_6':'6', + 'KEY_7':'7', + 'KEY_8':'8', + 'KEY_9':'9' + } + + +class QRReader: + __qrstr = "" + __myReader = {} + __numdigits = 10 + __dev = None + + def __init__(self): + self.getQRlist() + + def getQRlist(self): + devices = [evdev.InputDevice(path) for path in evdev.list_devices()] + for device in devices: + if device.name in qrdevice_list: + self.__myReader['NAME'] = device.name + print(self.__myReader['NAME']) + self.__myReader['PATH'] = device.path + print(self.__myReader['PATH']) + self.__myReader['PHYS'] = device.phys + print(self.__myReader['PHYS']) + + def IsQR (self): + return 'NAME' in self.__myReader + + def getQRNumber(self): + return self.__qrstr + + def openQR(self): + if self.IsQR(): + self.closeQR() + self.__dev = InputDevice(self.__myReader['PATH']) + return True + return False + + def closeQR(self): + if self.__dev: + del self.__dev + self.__dev = None + + def readQR(self): + """" Sync Read up to numdigits """ + count = 0 + self.__qrstr = "" + if self.__dev: + self.__dev.grab() + for event in self.__dev.read_loop(): + if event.type == evdev.ecodes.EV_KEY: + c_event = categorize(event) + if c_event.keycode in qrkey_list: + if c_event.keystate == 0: + self.__qrstr += qrkey_list[c_event.keycode] + count += 1 + if count == self.__numdigits: + break + self.__dev.ungrab() + return True + return False + + def wait_event (self, timeout): + selector.register(self.__dev, selectors.EVENT_READ) + while True: + events = selector.select(timeout); + if not events: + return False + else: + return True + + def readQRasync(self, timeout): + count = 0 + r = False + self.__qrstr = "" + if self.__dev: + self.__dev.grab() + if self.wait_event(timeout): + for event in self.__dev.read_loop(): + if event.type == evdev.ecodes.EV_KEY: + c_event = categorize(event) + if c_event.keycode in qrkey_list: + if c_event.keystate == 0: + self.__qrstr += qrkey_list[c_event.keycode] + count += 1 + if count == self.__numdigits: + r = True + break + self.__dev.ungrab() + return r + return False + + +#qr = QRReader() +#if qr.openQR(): +# print(qr.readQRasync(2)) +#qr.closeQR() \ No newline at end of file diff --git a/test-cli/test/helpers/testsrv_db.py b/test-cli/test/helpers/testsrv_db.py index d563e74..dc4fb55 100644 --- a/test-cli/test/helpers/testsrv_db.py +++ b/test-cli/test/helpers/testsrv_db.py @@ -139,12 +139,12 @@ class TestSrv_Database(object): def create_task_result(self, taskid_ctl, name, newstatus, newinfo=None): sql = "SELECT isee.f_create_task_result({},'{}','{}','{}')".format(taskid_ctl, name, newstatus, newinfo) - print('>>>' + sql) + # print('>>>' + sql) try: self.__sqlObject.db_execute_query(sql) except Exception as err: r = find_between(str(err), '#', '#') - print(r) + # print(r) return None def update_taskctl_status(self, taskid_ctl, newstatus): @@ -156,3 +156,24 @@ class TestSrv_Database(object): r = find_between(str(err), '#', '#') # print(r) return None + + def set_factorycode(self, uuid, factorycode): + sql = "SELECT isee.f_set_factorycode('{}','{}')".format(uuid, factorycode) + # print('>>>' + sql) + try: + self.__sqlObject.db_execute_query(sql) + except Exception as err: + r = find_between(str(err), '#', '#') + # print(r) + return None + + def bond_to_station(self, uuid, station): + sql = "SELECT station.bond_to_station('{}','{}')".format(uuid, station) + # print('>>>' + sql) + try: + self.__sqlObject.db_execute_query(sql) + except Exception as err: + r = find_between(str(err), '#', '#') + # print(r) + return None + diff --git a/test-cli/test/tests/qethernet.py b/test-cli/test/tests/qethernet.py index 1d4c9bc..027931c 100644 --- a/test-cli/test/tests/qethernet.py +++ b/test-cli/test/tests/qethernet.py @@ -19,10 +19,6 @@ class Qethernet(unittest.TestCase): self.__serverip = varlist["serverip"] else: raise Exception('sip param inside Qethernet have been be defined') - if "bind" in varlist: - self.__bind = varlist["bind"] - else: - self.__bind = None if "bwexpected" in varlist: self.__bwexpected = varlist["bwexpected"] else: @@ -36,11 +32,8 @@ class Qethernet(unittest.TestCase): def execute(self): # execute iperf command against the server - if self.__bind is None: - p = sh.iperf("-c", self.__serverip, "-x", "CMSV", "-n", self.__numbytestx, "-f", "m", "-p", self.__port) - else: - p = sh.iperf("-c", self.__serverip, "-x", "CMSV", "-n", self.__numbytestx, "-f", "m", "-p", self.__port, "-B", - self.__bind) + p = sh.iperf("-c", self.__serverip, "-x", "CMSV", "-n", self.__numbytestx, "-f", "m", "-p", self.__port) + # check if it was executed succesfully if p.exit_code == 0: if p.stdout == "": diff --git a/test-cli/test/tests/qwifi.py b/test-cli/test/tests/qwifi.py index 8daf069..b0b8d6b 100644 --- a/test-cli/test/tests/qwifi.py +++ b/test-cli/test/tests/qwifi.py @@ -44,6 +44,7 @@ class Qwifi(unittest.TestCase): # check if the board has ip in the wlan0 interface p = sh.ifconfig("wlan0") if p.exit_code == 0: + # check if wlan0 has an IP result = re.search( 'inet addr:(?!127\.0{1,3}\.0{1,3}\.0{0,2}1$)((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)', p.stdout.decode('ascii')) -- cgit v1.1 From 99d74b02c7d3ff7eea51f59a2d67651aeab1297f Mon Sep 17 00:00:00 2001 From: Hector Fernandez Date: Wed, 15 Apr 2020 10:33:56 +0200 Subject: Added code scanner code after doing all tests. It waits for a valid code from the code scanner. --- test-cli/test/helpers/qrreader.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'test-cli/test') diff --git a/test-cli/test/helpers/qrreader.py b/test-cli/test/helpers/qrreader.py index 1d3768b..0954a70 100644 --- a/test-cli/test/helpers/qrreader.py +++ b/test-cli/test/helpers/qrreader.py @@ -9,7 +9,8 @@ selector = selectors.DefaultSelector() qrdevice_list = [ "Honeywell Imaging & Mobility 1900", - "Manufacturer Barcode Reader" + "Manufacturer Barcode Reader", + "SM SM-2D PRODUCT HID KBW" ] @@ -117,4 +118,4 @@ class QRReader: #qr = QRReader() #if qr.openQR(): # print(qr.readQRasync(2)) -#qr.closeQR() \ No newline at end of file +#qr.closeQR() -- cgit v1.1 From 47b65a71d5db142c73a0566f132af6eee3b0c2a9 Mon Sep 17 00:00:00 2001 From: Hector Fernandez Date: Wed, 15 Apr 2020 17:22:21 +0200 Subject: Every 5s teh qr scanner is refreshed to detect a new devices in case it is unplugged and plugged again. --- test-cli/test/helpers/qrreader.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'test-cli/test') diff --git a/test-cli/test/helpers/qrreader.py b/test-cli/test/helpers/qrreader.py index 0954a70..908c9db 100644 --- a/test-cli/test/helpers/qrreader.py +++ b/test-cli/test/helpers/qrreader.py @@ -41,11 +41,11 @@ class QRReader: for device in devices: if device.name in qrdevice_list: self.__myReader['NAME'] = device.name - print(self.__myReader['NAME']) + #print(self.__myReader['NAME']) self.__myReader['PATH'] = device.path - print(self.__myReader['PATH']) + #print(self.__myReader['PATH']) self.__myReader['PHYS'] = device.phys - print(self.__myReader['PHYS']) + #print(self.__myReader['PHYS']) def IsQR (self): return 'NAME' in self.__myReader -- cgit v1.1 From 9f613e33f27f772682ab7d7bd2261a9c4bd014c5 Mon Sep 17 00:00:00 2001 From: Hector Fernandez Date: Wed, 15 Apr 2020 17:59:38 +0200 Subject: Allow 2 attempts to communicate to amperimeter. --- test-cli/test/tests/qamper.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'test-cli/test') diff --git a/test-cli/test/tests/qamper.py b/test-cli/test/tests/qamper.py index b3ab8b1..c611fdb 100644 --- a/test-cli/test/tests/qamper.py +++ b/test-cli/test/tests/qamper.py @@ -27,9 +27,11 @@ class Qamper(unittest.TestCase): self.fail("failed: can not open serial port") return # check if the amperimeter is connected and working + # 2 ATTEMTS if not amp.hello(): - self.fail("failed: can not communicate") - return + if not amp.hello(): + self.fail("failed: can not communicate") + return # get current value (in Amperes) result = amp.getCurrent() # close serial connection -- cgit v1.1 From 6a680137694233008005415e22cf889b85baa292 Mon Sep 17 00:00:00 2001 From: Hector Fernandez Date: Thu, 16 Apr 2020 17:09:19 +0200 Subject: First release --- test-cli/test/tests/qethernet.py | 9 ++++++--- test-cli/test/tests/qusb.py | 9 +++++++-- test-cli/test/tests/qwifi.py | 17 ++++++----------- 3 files changed, 19 insertions(+), 16 deletions(-) (limited to 'test-cli/test') diff --git a/test-cli/test/tests/qethernet.py b/test-cli/test/tests/qethernet.py index 027931c..2246029 100644 --- a/test-cli/test/tests/qethernet.py +++ b/test-cli/test/tests/qethernet.py @@ -6,12 +6,11 @@ import re class Qethernet(unittest.TestCase): __serverip = None __numbytestx = None - __bind = None __bwexpected = None __port = None params = None - #varlist content: serverip, bwexpected, port, (optional)bind + # varlist content: serverip, bwexpected, port def __init__(self, testname, testfunc, varlist): self.params = varlist super(Qethernet, self).__init__(testfunc) @@ -32,7 +31,11 @@ class Qethernet(unittest.TestCase): def execute(self): # execute iperf command against the server - p = sh.iperf("-c", self.__serverip, "-x", "CMSV", "-n", self.__numbytestx, "-f", "m", "-p", self.__port) + try: + p = sh.iperf("-c", self.__serverip, "-x", "CMSV", "-n", self.__numbytestx, "-f", "m", "-p", self.__port, + _timeout=20) + except sh.TimeoutException: + self.fail("failed: iperf timeout reached") # check if it was executed succesfully if p.exit_code == 0: diff --git a/test-cli/test/tests/qusb.py b/test-cli/test/tests/qusb.py index 6c22c48..4c177d9 100644 --- a/test-cli/test/tests/qusb.py +++ b/test-cli/test/tests/qusb.py @@ -1,6 +1,7 @@ import sh import unittest import re +import os from test.helpers.changedir import changedir @@ -14,7 +15,9 @@ class Qusb(unittest.TestCase): def execute(self): # Execute script usb.sh - p = sh.bash('test/scripts/usb.sh') + test_abspath = os.path.dirname(os.path.abspath(__file__)) + test_abspath = os.path.join(test_abspath, "..", "..") + p = sh.bash(os.path.join(test_abspath, 'test/scripts/usb.sh')) # Search in the stdout a pattern "/dev/sd + {letter} + {number} q = re.search("/dev/sd\w\d", p.stdout.decode('ascii')) # get the first device which matches the pattern @@ -33,7 +36,9 @@ class Qusb(unittest.TestCase): p = sh.mount(device, "/mnt/pendrive") if p.exit_code == 0: # copy files - p = sh.cp("test/files/usbtest/usbdatatest.bin", "test/files/usbtest/usbdatatest.md5", "/mnt/pendrive") + p = sh.cp(os.path.join(test_abspath, "test/files/usbtest/usbdatatest.bin"), + os.path.join(test_abspath, "test/files/usbtest/usbdatatest.md5"), + "/mnt/pendrive") if p.exit_code == 0: # check md5 with changedir("/mnt/pendrive/"): diff --git a/test-cli/test/tests/qwifi.py b/test-cli/test/tests/qwifi.py index b0b8d6b..684cb34 100644 --- a/test-cli/test/tests/qwifi.py +++ b/test-cli/test/tests/qwifi.py @@ -6,12 +6,11 @@ import re class Qwifi(unittest.TestCase): __serverip = None __numbytestx = None - __bind = None __bwexpected = None __port = None params = None - # varlist content: serverip, bwexpected, port, (optional)bind + # varlist content: serverip, bwexpected, port def __init__(self, testname, testfunc, varlist): self.params = varlist super(Qwifi, self).__init__(testfunc) @@ -27,10 +26,6 @@ class Qwifi(unittest.TestCase): self.__port = varlist["port"] else: raise Exception('port param inside Qwifi must be defined') - if "bind" in varlist: - self.__bind = varlist["bind"] - else: - self.__bind = None self.__numbytestx = "10M" self._testMethodDoc = testname @@ -50,12 +45,12 @@ class Qwifi(unittest.TestCase): p.stdout.decode('ascii')) if result: # execute iperf command against the server - if self.__bind is None: - p = sh.iperf("-c", self.__serverip, "-x", "CMSV", "-n", self.__numbytestx, "-f", "m", "-p", - self.__port) - else: + try: p = sh.iperf("-c", self.__serverip, "-x", "CMSV", "-n", self.__numbytestx, "-f", "m", "-p", - self.__port, "-B", self.__bind) + self.__port, _timeout=20) + except sh.TimeoutException: + self.fail("failed: iperf timeout reached") + # check if it was executed succesfully if p.exit_code == 0: if p.stdout == "": -- cgit v1.1 From d4020f0bce8c7841879736cd00ec64d617111c80 Mon Sep 17 00:00:00 2001 From: Hector Fernandez Date: Thu, 23 Apr 2020 14:14:02 +0200 Subject: Modified nand memory flasher --- test-cli/test/__init__.pyc | Bin 114 -> 124 bytes test-cli/test/flashers/flashmemory.py | 4 ++-- test-cli/test/helpers/__init__.pyc | Bin 122 -> 132 bytes 3 files changed, 2 insertions(+), 2 deletions(-) (limited to 'test-cli/test') diff --git a/test-cli/test/__init__.pyc b/test-cli/test/__init__.pyc index cd50092..3248efc 100644 Binary files a/test-cli/test/__init__.pyc and b/test-cli/test/__init__.pyc differ diff --git a/test-cli/test/flashers/flashmemory.py b/test-cli/test/flashers/flashmemory.py index c7267c6..3be56d7 100644 --- a/test-cli/test/flashers/flashmemory.py +++ b/test-cli/test/flashers/flashmemory.py @@ -1,9 +1,9 @@ import sh -def flash_memory(imagefile): +def flash_memory(imagepath): print("Start programming Nand memory...") - p = sh.bash("/usr/bin/igep-flash", "--skip-nandtest", "--image", "/opt/firmware/" + imagefile) + p = sh.bash("/usr/bin/igep-flash", "--skip-nandtest", "--image", imagepath) if p.exit_code != 0: print("Flasher: Could not complete flashing task.") return 1 diff --git a/test-cli/test/helpers/__init__.pyc b/test-cli/test/helpers/__init__.pyc index 7d1c907..01014e2 100644 Binary files a/test-cli/test/helpers/__init__.pyc and b/test-cli/test/helpers/__init__.pyc differ -- cgit v1.1 From 09b3bb38fc7305c9b47c29bc90ebc9c636827307 Mon Sep 17 00:00:00 2001 From: Hector Fernandez Date: Wed, 17 Jun 2020 09:44:56 +0200 Subject: SOPA0000: Added support for saving results (strings or files) in the DB. It also saves a final DMESG file. --- test-cli/test/helpers/psqldb.py | 29 ++++++++++++------- test-cli/test/helpers/testsrv_db.py | 37 +++++++++++++++++++++++- test-cli/test/runners/simple.py | 11 ++++++- test-cli/test/tasks/__init__.py | 0 test-cli/test/tasks/flasheeprom.py | 56 ++++++++++++++++++++++++++++++++++++ test-cli/test/tasks/flashmemory.py | 12 ++++++++ test-cli/test/tasks/generatedmesg.py | 17 +++++++++++ test-cli/test/tests/qamper.py | 23 +++++++++++---- test-cli/test/tests/qduplex_ser.py | 5 ++++ test-cli/test/tests/qeeprom.py | 4 +++ test-cli/test/tests/qethernet.py | 38 ++++++++++++++++-------- test-cli/test/tests/qi2c.py | 14 ++++++--- test-cli/test/tests/qnand.py | 17 ++++++++++- test-cli/test/tests/qram.py | 8 +++++- test-cli/test/tests/qrtc.py | 4 +++ test-cli/test/tests/qserial.py | 5 ++++ test-cli/test/tests/qusb.py | 5 ++++ test-cli/test/tests/qwifi.py | 34 ++++++++++++++-------- 18 files changed, 270 insertions(+), 49 deletions(-) create mode 100644 test-cli/test/tasks/__init__.py create mode 100644 test-cli/test/tasks/flasheeprom.py create mode 100644 test-cli/test/tasks/flashmemory.py create mode 100644 test-cli/test/tasks/generatedmesg.py (limited to 'test-cli/test') diff --git a/test-cli/test/helpers/psqldb.py b/test-cli/test/helpers/psqldb.py index 1d0e422..c98338a 100644 --- a/test-cli/test/helpers/psqldb.py +++ b/test-cli/test/helpers/psqldb.py @@ -1,29 +1,30 @@ import psycopg2 + class PgSQLConnection(object): """aaaaaaa""" __conection_object = None __db_config = {'dbname': 'testsrv', 'host': '192.168.2.171', - 'password': 'Idkfa2009', 'port': 5432, 'user': 'admin'} + 'password': 'Idkfa2009', 'port': 5432, 'user': 'admin'} - def __init__ (self, connect_str = None): + def __init__(self, connect_str=None): self.__conection_object = None if connect_str is not None: self.__db_config = connect_str else: self.__db_config = {'dbname': 'testsrv', 'host': '192.168.2.171', - 'password': 'Idkfa2009', 'port': 5432, 'user': 'admin'} + 'password': 'Idkfa2009', 'port': 5432, 'user': 'admin'} - def db_connect (self, connect_str = None): + def db_connect(self, connect_str=None): result = False try: if connect_str == None: self.__conection_object = psycopg2.connect(**self.__db_config) else: - self.__db_config = connect_str; + self.__db_config = connect_str self.__conection_object = psycopg2.connect(**self.__db_config) - + self.__conection_object.autocommit = True result = True except Exception as error: @@ -37,20 +38,26 @@ class PgSQLConnection(object): cur.close() return data + def db_upload_large_file(self, filepath): + # a new connection must be created to use large objects + __conn = psycopg2.connect(**self.__db_config) + lobj = __conn.lobject(oid=0, mode="rw", new_oid=0, new_file=filepath) + fileoid = lobj.oid + lobj.close() + __conn.commit() + __conn.close() + return fileoid + def commit(self): self.__conection_object.commit() - def db_close(self): if self.__conection_object is not None: self.__conection_object.close() del self.__conection_object self.__conection_object = None - def __del__(self): if self.__conection_object is not None: self.__conection_object.close() - #print("disconnected") - - + # print("disconnected") diff --git a/test-cli/test/helpers/testsrv_db.py b/test-cli/test/helpers/testsrv_db.py index dc4fb55..dfb4d15 100644 --- a/test-cli/test/helpers/testsrv_db.py +++ b/test-cli/test/helpers/testsrv_db.py @@ -101,6 +101,42 @@ class TestSrv_Database(object): # print(r) return None + def upload_result_string(self, testid_ctl, testid, descrip, strdata): + sql = "SELECT isee.f_upload_result_string({},{},'{}','{}')".format(testid_ctl, testid, descrip, strdata) + # print('>>>' + sql) + try: + self.__sqlObject.db_execute_query(sql) + except Exception as err: + r = find_between(str(err), '#', '#') + # print(r) + return None + + def upload_result_file(self, testid_ctl, testid, descrip, filepath): + try: + # generate a new oid + fileoid = self.__sqlObject.db_upload_large_file(filepath) + # insert into a table + sql = "SELECT isee.f_upload_result_file({},{},'{}','{}')".format(testid_ctl, testid, descrip, fileoid) + # print('>>>' + sql) + self.__sqlObject.db_execute_query(sql) + except Exception as err: + r = find_between(str(err), '#', '#') + # print(r) + return None + + def upload_dmesg(self, testid_ctl, filepath): + try: + # generate a new oid + fileoid = self.__sqlObject.db_upload_large_file(filepath) + # insert into a table + sql = "SELECT isee.f_upload_dmesg_file({},'{}')".format(testid_ctl, fileoid) + # print('>>>' + sql) + self.__sqlObject.db_execute_query(sql) + except Exception as err: + r = find_between(str(err), '#', '#') + # print(r) + return None + def get_task_variables_list(self, board_uuid): sql = "SELECT * FROM isee.f_get_task_variables_list('{}')".format(board_uuid) # print('>>>' + sql) @@ -176,4 +212,3 @@ class TestSrv_Database(object): r = find_between(str(err), '#', '#') # print(r) return None - diff --git a/test-cli/test/runners/simple.py b/test-cli/test/runners/simple.py index a165406..e0418d2 100644 --- a/test-cli/test/runners/simple.py +++ b/test-cli/test/runners/simple.py @@ -71,10 +71,19 @@ class TextTestResult(unittest.TestResult): unittest.TestResult.stopTest(self, test) # display: print test result self.runner.writeUpdate(self.result) + # save result data + for result in test.getresults(): + if "desc" in result.keys() and result["desc"]: + if "type" in result.keys() and "data" in result.keys(): + if result["type"] == "string": + self.__pgObj.upload_result_string(test.params["testidctl"], test.params["testid"], + result["desc"], result["data"]) + elif result["type"] == "file": + self.__pgObj.upload_result_file(test.params["testidctl"], test.params["testid"], result["desc"], + result["data"]) # SEND TO DB THE RESULT OF THE TEST if self.result == self.PASS: status = "TEST_COMPLETE" else: status = "TEST_FAILED" self.__pgObj.finish_test(test.params["testidctl"], test.params["testid"], status) - diff --git a/test-cli/test/tasks/__init__.py b/test-cli/test/tasks/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/test-cli/test/tasks/flasheeprom.py b/test-cli/test/tasks/flasheeprom.py new file mode 100644 index 0000000..71c1bdd --- /dev/null +++ b/test-cli/test/tasks/flasheeprom.py @@ -0,0 +1,56 @@ +import os +import binascii +from test.helpers.globalVariables import globalVar + + +def _generate_data_bytes(boarduuid, mac0, mac1): + data = bytearray() + data += (2029785358).to_bytes(4, 'big') # magicid --> 0x78FC110E + data += bytearray([0, 0, 0, 0]) # crc32 = 0 + data += bytearray(boarduuid + "\0", + 'ascii') # uuid --> 'c0846c8a-5fa5-11ea-8576-f8b156ac62d7' and \0 at the end + data += binascii.unhexlify(mac0.replace(':', '')) # mac0 --> 'f8:b1:56:ac:62:d7' + if mac1 is not None: + data += binascii.unhexlify(mac1.replace(':', '')) # mac1 --> 'f8:b1:56:ac:62:d7' + else: + data += bytearray([0, 0, 0, 0, 0, 0]) # mac1 --> 0:0:0:0:0:0 + # calculate crc + crc = (binascii.crc32(data, 0)).to_bytes(4, 'big') + data[4:8] = crc + return data + + +def _generate_output_data(data_rx): + boarduuid = data_rx[8:44].decode('ascii') # no 8:45 porque el \0 final hace que no funcione postgresql + mac0 = binascii.hexlify(data_rx[45:51]).decode('ascii') + mac1 = binascii.hexlify(data_rx[51:57]).decode('ascii') + smac0 = ':'.join(mac0[i:i + 2] for i in range(0, len(mac0), 2)) + smac1 = ':'.join(mac1[i:i + 2] for i in range(0, len(mac1), 2)) + eepromdata = "UUID " + boarduuid + " , MAC0 " + smac0 + " , MAC1 " + smac1 + + return eepromdata + + +# returns exitcode and data saved into eeprom +def flash_eeprom(eeprompath, boarduuid, mac0, mac1=None): + print("Start programming Eeprom...") + # check if eeprompath is correct + if os.path.isfile(eeprompath): + # create u-boot data struct + data = _generate_data_bytes(boarduuid, mac0, mac1) + # write into eeprom and read back + f = open(eeprompath, "r+b") + f.write(data) + f.seek(0) + data_rx = f.read(57) + for i in range(57): + if data_rx[i] != data[i]: + print("Error while programming eeprom memory.") + return 1, None + print("Eeprom programmed succesfully.") + # generated eeprom read data + eepromdata = _generate_output_data(data_rx) + return 0, eepromdata + else: + print("Eeprom memory not found.") + return 1, None diff --git a/test-cli/test/tasks/flashmemory.py b/test-cli/test/tasks/flashmemory.py new file mode 100644 index 0000000..3be56d7 --- /dev/null +++ b/test-cli/test/tasks/flashmemory.py @@ -0,0 +1,12 @@ +import sh + + +def flash_memory(imagepath): + print("Start programming Nand memory...") + p = sh.bash("/usr/bin/igep-flash", "--skip-nandtest", "--image", imagepath) + if p.exit_code != 0: + print("Flasher: Could not complete flashing task.") + return 1 + else: + print("Flasher: NAND memory flashed succesfully.") + return 0 diff --git a/test-cli/test/tasks/generatedmesg.py b/test-cli/test/tasks/generatedmesg.py new file mode 100644 index 0000000..f0a3418 --- /dev/null +++ b/test-cli/test/tasks/generatedmesg.py @@ -0,0 +1,17 @@ +import sh + + +def generate_dmesg(tidctl, pgObj): + print("Start getting DMESG...") + p = sh.dmesg() + if p.exit_code != 0: + print("DMESG: Unknown error.") + return 1 + else: + # save dmesg in a file + with open('/tmp/dmesg.txt', 'w') as outfile: + n = outfile.write(p.stdout.decode('ascii')) + # save dmesg result in DB + pgObj.upload_dmesg(tidctl, '/tmp/dmesg.txt') + print("DMESG: saved succesfully.") + return 0 diff --git a/test-cli/test/tests/qamper.py b/test-cli/test/tests/qamper.py index c611fdb..51aa469 100644 --- a/test-cli/test/tests/qamper.py +++ b/test-cli/test/tests/qamper.py @@ -4,6 +4,7 @@ from test.helpers.amper import Amper class Qamper(unittest.TestCase): params = None + __current = None # varlist: undercurrent, overcurrent def __init__(self, testname, testfunc, varlist): @@ -33,12 +34,22 @@ class Qamper(unittest.TestCase): self.fail("failed: can not communicate") return # get current value (in Amperes) - result = amp.getCurrent() + self.__current = amp.getCurrent() # close serial connection amp.close() - # # In order to give a valid result it is importarnt to define an under current value - if result > float(self._overcurrent): - self.fail("failed: Overcurrent detected ( {} )".format(result)) + # Check current range + if float(self.__current) > float(self._overcurrent): + self.fail("failed: Overcurrent detected ( {} )".format(self.__current)) + if float(self.__current) < float(self._undercurrent): + self.fail("failed: Undercurrent detected ( {} )".format(self.__current)) - if result < float(self._undercurrent): - self.fail("failed: Undercurrent detected ( {} )".format(result)) + def getresults(self): + # resultlist is a python list of python dictionaries + resultlist = [ + { + "desc": "current (Ampers)", + "data": self.__current, + "type": "string" + } + ] + return resultlist diff --git a/test-cli/test/tests/qduplex_ser.py b/test-cli/test/tests/qduplex_ser.py index cb690cb..c7231c2 100644 --- a/test-cli/test/tests/qduplex_ser.py +++ b/test-cli/test/tests/qduplex_ser.py @@ -69,3 +69,8 @@ class Qduplex(unittest.TestCase): else: if self.__serial1.readline() != test_uuid: self.fail("failed: port {} write/read mismatch".format(self.__port1)) + + def getresults(self): + # resultlist is a python list of python dictionaries + resultlist = [] + return resultlist diff --git a/test-cli/test/tests/qeeprom.py b/test-cli/test/tests/qeeprom.py index 1921bf7..a65ca97 100644 --- a/test-cli/test/tests/qeeprom.py +++ b/test-cli/test/tests/qeeprom.py @@ -39,3 +39,7 @@ class Qeeprom(unittest.TestCase): else: self.fail("failed: Unable to write on the EEPROM device.") + def getresults(self): + # resultlist is a python list of python dictionaries + resultlist = [] + return resultlist diff --git a/test-cli/test/tests/qethernet.py b/test-cli/test/tests/qethernet.py index 2246029..da085d8 100644 --- a/test-cli/test/tests/qethernet.py +++ b/test-cli/test/tests/qethernet.py @@ -1,6 +1,7 @@ import unittest import sh import re +import json class Qethernet(unittest.TestCase): @@ -9,11 +10,16 @@ class Qethernet(unittest.TestCase): __bwexpected = None __port = None params = None + __bwreal = None # varlist content: serverip, bwexpected, port def __init__(self, testname, testfunc, varlist): + # save the parameters list self.params = varlist + # configure the function to be executed when the test runs. "testfunc" is a name of a method inside this + # class, that in this situation, it can only be "execute". super(Qethernet, self).__init__(testfunc) + # validate and get the parameters if "serverip" in varlist: self.__serverip = varlist["serverip"] else: @@ -32,8 +38,8 @@ class Qethernet(unittest.TestCase): def execute(self): # execute iperf command against the server try: - p = sh.iperf("-c", self.__serverip, "-x", "CMSV", "-n", self.__numbytestx, "-f", "m", "-p", self.__port, - _timeout=20) + p = sh.iperf3("-c", self.__serverip, "-n", self.__numbytestx, "-f", "m", "-p", self.__port, "-J", + _timeout=20) except sh.TimeoutException: self.fail("failed: iperf timeout reached") @@ -42,17 +48,25 @@ class Qethernet(unittest.TestCase): if p.stdout == "": self.fail("failed: error executing iperf command") # analyze output string - # split by lines - lines = p.stdout.splitlines() - # get first line - dat = lines[1].decode('ascii') - # search for the BW value - a = re.search("\d+(\.\d)? Mbits/sec", dat) - b = a.group().split() - bwreal = b[0] + data = json.loads(p.stdout.decode('ascii')) + self.__bwreal = float(data['end']['sum_received']['bits_per_second'])/1024/1024 + # save result file + with open('/tmp/ethernet-iperf.json', 'w') as outfile: + json.dump(data, outfile) # check if BW is in the expected range - self.failUnless(float(bwreal) > float(self.__bwexpected) * 0.9, - "failed: speed is lower than spected. Speed(MB/s)" + str(bwreal)) + self.failUnless(self.__bwreal > float(self.__bwexpected) * 0.9, + "failed: speed is lower than spected. Speed(Mbits/s)" + str(self.__bwreal)) else: self.fail("failed: could not complete iperf command") + + def getresults(self): + # resultlist is a python list of python dictionaries + resultlist = [ + { + "desc": "iperf3 output", + "data": "/tmp/ethernet-iperf.json", + "type": "file" + } + ] + return resultlist diff --git a/test-cli/test/tests/qi2c.py b/test-cli/test/tests/qi2c.py index c59975e..ad7ddf0 100644 --- a/test-cli/test/tests/qi2c.py +++ b/test-cli/test/tests/qi2c.py @@ -16,7 +16,7 @@ class Qi2c(unittest.TestCase): self.__register = varlist["register"].split("/") else: raise Exception('register param inside Qi2c must be defined') - self.__devices=[] + self.__devices = [] self._testMethodDoc = testname def execute(self): @@ -26,13 +26,19 @@ class Qi2c(unittest.TestCase): self.__raw_out = i2c_command.getOutput() if self.__raw_out == "": return -1 - lines=self.__raw_out.decode('ascii').splitlines() + lines = self.__raw_out.decode('ascii').splitlines() for i in range(len(lines)): if lines[i].count('UU'): if lines[i].find("UU"): - self.__devices.append("0x{}{}".format((i - 1), hex(int((lines[i].find("UU") - 4) / 3)).split('x')[-1])) + self.__devices.append( + "0x{}{}".format((i - 1), hex(int((lines[i].find("UU") - 4) / 3)).split('x')[-1])) for i in range(len(self.__register)): - if not(self.__register[i] in self.__devices): + if not (self.__register[i] in self.__devices): self.fail("failed: device {} not found in bus i2c-{}".format(self.__register[i], self.__busnum)) else: self.fail("failed: could not complete i2cdedtect command") + + def getresults(self): + # resultlist is a python list of python dictionaries + resultlist = [] + return resultlist diff --git a/test-cli/test/tests/qnand.py b/test-cli/test/tests/qnand.py index 10a68f2..7ff7cb2 100644 --- a/test-cli/test/tests/qnand.py +++ b/test-cli/test/tests/qnand.py @@ -18,6 +18,21 @@ class Qnand(unittest.TestCase): def execute(self): try: - sh.nandtest("-m", self.__device, _out="/dev/null") + p = sh.nandtest("-m", self.__device) + # save result + with open('/tmp/nand-nandtest.txt', 'w') as outfile: + n = outfile.write(p.stdout.decode('ascii')) + except sh.ErrorReturnCode as e: self.fail("failed: could not complete nandtest command") + + def getresults(self): + # resultlist is a python list of python dictionaries + resultlist = [ + { + "desc": "nandtest output", + "data": "/tmp/nand-nandtest.txt", + "type": "file" + } + ] + return resultlist diff --git a/test-cli/test/tests/qram.py b/test-cli/test/tests/qram.py index 5a7734a..561e980 100644 --- a/test-cli/test/tests/qram.py +++ b/test-cli/test/tests/qram.py @@ -23,6 +23,12 @@ class Qram(unittest.TestCase): def execute(self): try: - sh.memtester(self.__memsize, "1", _out="/dev/null") + p = sh.memtester(self.__memsize, "1", _out="/dev/null") + except sh.ErrorReturnCode as e: self.fail("failed: could not complete memtester command") + + def getresults(self): + # resultlist is a python list of python dictionaries + resultlist = [] + return resultlist diff --git a/test-cli/test/tests/qrtc.py b/test-cli/test/tests/qrtc.py index 0be0f99..715bcb7 100644 --- a/test-cli/test/tests/qrtc.py +++ b/test-cli/test/tests/qrtc.py @@ -37,3 +37,7 @@ class Qrtc(unittest.TestCase): else: self.fail("failed: couldn't execute hwclock command") + def getresults(self): + # resultlist is a python list of python dictionaries + resultlist = [] + return resultlist diff --git a/test-cli/test/tests/qserial.py b/test-cli/test/tests/qserial.py index 45c9d03..0cb5563 100644 --- a/test-cli/test/tests/qserial.py +++ b/test-cli/test/tests/qserial.py @@ -45,3 +45,8 @@ class Qserial(unittest.TestCase): # check if what it was sent is equal to what has been received if self.__serial.readline() != test_uuid: self.fail("failed: port {} write/read mismatch".format(self.__port)) + + def getresults(self): + # resultlist is a python list of python dictionaries + resultlist = [] + return resultlist diff --git a/test-cli/test/tests/qusb.py b/test-cli/test/tests/qusb.py index 4c177d9..316cef5 100644 --- a/test-cli/test/tests/qusb.py +++ b/test-cli/test/tests/qusb.py @@ -57,3 +57,8 @@ class Qusb(unittest.TestCase): self.fail("failed: unable to copy files.") else: self.fail("failed: unable to mount the device.") + + def getresults(self): + # resultlist is a python list of python dictionaries + resultlist = [] + return resultlist diff --git a/test-cli/test/tests/qwifi.py b/test-cli/test/tests/qwifi.py index 684cb34..0944dd7 100644 --- a/test-cli/test/tests/qwifi.py +++ b/test-cli/test/tests/qwifi.py @@ -1,6 +1,7 @@ import unittest import sh import re +import json class Qwifi(unittest.TestCase): @@ -9,6 +10,7 @@ class Qwifi(unittest.TestCase): __bwexpected = None __port = None params = None + __bwreal = None # varlist content: serverip, bwexpected, port def __init__(self, testname, testfunc, varlist): @@ -46,8 +48,8 @@ class Qwifi(unittest.TestCase): if result: # execute iperf command against the server try: - p = sh.iperf("-c", self.__serverip, "-x", "CMSV", "-n", self.__numbytestx, "-f", "m", "-p", - self.__port, _timeout=20) + p = sh.iperf3("-c", self.__serverip, "-n", self.__numbytestx, "-f", "m", "-p", self.__port, + "-J", _timeout=20) except sh.TimeoutException: self.fail("failed: iperf timeout reached") @@ -56,18 +58,15 @@ class Qwifi(unittest.TestCase): if p.stdout == "": self.fail("failed: error executing iperf command") # analyze output string - # split by lines - lines = p.stdout.splitlines() - # get first line - dat = lines[1].decode('ascii') - # search for the BW value - a = re.search("\d+(\.\d)? Mbits/sec", dat) - b = a.group().split() - bwreal = b[0] + data = json.loads(p.stdout.decode('ascii')) + self.__bwreal = float(data['end']['sum_received']['bits_per_second']) / 1024 / 1024 + # save result file + with open('/tmp/wifi-iperf.json', 'w') as outfile: + json.dump(data, outfile) # check if BW is in the expected range - self.failUnless(float(bwreal) > float(self.__bwexpected) * 0.9, - "failed: speed is lower than spected. Speed(MB/s)" + str(bwreal)) + self.failUnless(self.__bwreal > float(self.__bwexpected) * 0.9, + "failed: speed is lower than spected. Speed(Mbits/s)" + str(self.__bwreal)) else: self.fail("failed: could not complete iperf command") else: @@ -78,3 +77,14 @@ class Qwifi(unittest.TestCase): self.fail("failed: wifi module is not connected to the router.") else: self.fail("failed: couldn't execute iw command") + + def getresults(self): + # resultlist is a python list of python dictionaries + resultlist = [ + { + "desc": "iperf3 output", + "data": "/tmp/wifi-iperf.json", + "type": "file" + } + ] + return resultlist -- cgit v1.1 From 7f13bbf84bec700c82e0cc2fea78a4026962f340 Mon Sep 17 00:00:00 2001 From: Hector Fernandez Date: Wed, 17 Jun 2020 10:30:48 +0200 Subject: SOPA0000: Erased colors in DMESG to have a clean file. --- test-cli/test/flashers/__init__.py | 0 test-cli/test/flashers/flasheeprom.py | 56 ----------------------------------- test-cli/test/flashers/flashmemory.py | 12 -------- test-cli/test/tasks/generatedmesg.py | 2 +- 4 files changed, 1 insertion(+), 69 deletions(-) delete mode 100644 test-cli/test/flashers/__init__.py delete mode 100644 test-cli/test/flashers/flasheeprom.py delete mode 100644 test-cli/test/flashers/flashmemory.py (limited to 'test-cli/test') diff --git a/test-cli/test/flashers/__init__.py b/test-cli/test/flashers/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/test-cli/test/flashers/flasheeprom.py b/test-cli/test/flashers/flasheeprom.py deleted file mode 100644 index 71c1bdd..0000000 --- a/test-cli/test/flashers/flasheeprom.py +++ /dev/null @@ -1,56 +0,0 @@ -import os -import binascii -from test.helpers.globalVariables import globalVar - - -def _generate_data_bytes(boarduuid, mac0, mac1): - data = bytearray() - data += (2029785358).to_bytes(4, 'big') # magicid --> 0x78FC110E - data += bytearray([0, 0, 0, 0]) # crc32 = 0 - data += bytearray(boarduuid + "\0", - 'ascii') # uuid --> 'c0846c8a-5fa5-11ea-8576-f8b156ac62d7' and \0 at the end - data += binascii.unhexlify(mac0.replace(':', '')) # mac0 --> 'f8:b1:56:ac:62:d7' - if mac1 is not None: - data += binascii.unhexlify(mac1.replace(':', '')) # mac1 --> 'f8:b1:56:ac:62:d7' - else: - data += bytearray([0, 0, 0, 0, 0, 0]) # mac1 --> 0:0:0:0:0:0 - # calculate crc - crc = (binascii.crc32(data, 0)).to_bytes(4, 'big') - data[4:8] = crc - return data - - -def _generate_output_data(data_rx): - boarduuid = data_rx[8:44].decode('ascii') # no 8:45 porque el \0 final hace que no funcione postgresql - mac0 = binascii.hexlify(data_rx[45:51]).decode('ascii') - mac1 = binascii.hexlify(data_rx[51:57]).decode('ascii') - smac0 = ':'.join(mac0[i:i + 2] for i in range(0, len(mac0), 2)) - smac1 = ':'.join(mac1[i:i + 2] for i in range(0, len(mac1), 2)) - eepromdata = "UUID " + boarduuid + " , MAC0 " + smac0 + " , MAC1 " + smac1 - - return eepromdata - - -# returns exitcode and data saved into eeprom -def flash_eeprom(eeprompath, boarduuid, mac0, mac1=None): - print("Start programming Eeprom...") - # check if eeprompath is correct - if os.path.isfile(eeprompath): - # create u-boot data struct - data = _generate_data_bytes(boarduuid, mac0, mac1) - # write into eeprom and read back - f = open(eeprompath, "r+b") - f.write(data) - f.seek(0) - data_rx = f.read(57) - for i in range(57): - if data_rx[i] != data[i]: - print("Error while programming eeprom memory.") - return 1, None - print("Eeprom programmed succesfully.") - # generated eeprom read data - eepromdata = _generate_output_data(data_rx) - return 0, eepromdata - else: - print("Eeprom memory not found.") - return 1, None diff --git a/test-cli/test/flashers/flashmemory.py b/test-cli/test/flashers/flashmemory.py deleted file mode 100644 index 3be56d7..0000000 --- a/test-cli/test/flashers/flashmemory.py +++ /dev/null @@ -1,12 +0,0 @@ -import sh - - -def flash_memory(imagepath): - print("Start programming Nand memory...") - p = sh.bash("/usr/bin/igep-flash", "--skip-nandtest", "--image", imagepath) - if p.exit_code != 0: - print("Flasher: Could not complete flashing task.") - return 1 - else: - print("Flasher: NAND memory flashed succesfully.") - return 0 diff --git a/test-cli/test/tasks/generatedmesg.py b/test-cli/test/tasks/generatedmesg.py index f0a3418..aa9d9ce 100644 --- a/test-cli/test/tasks/generatedmesg.py +++ b/test-cli/test/tasks/generatedmesg.py @@ -3,7 +3,7 @@ import sh def generate_dmesg(tidctl, pgObj): print("Start getting DMESG...") - p = sh.dmesg() + p = sh.dmesg("--color=never") if p.exit_code != 0: print("DMESG: Unknown error.") return 1 -- cgit v1.1 From 736ddcfe6dc3b5edbab6773f1c6687f6597fa7a3 Mon Sep 17 00:00:00 2001 From: Hector Fernandez Date: Wed, 17 Jun 2020 10:50:02 +0200 Subject: SOPA0000: Beatified JSON files generated by tests which use iperf3. --- test-cli/test/tests/qethernet.py | 2 +- test-cli/test/tests/qwifi.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'test-cli/test') diff --git a/test-cli/test/tests/qethernet.py b/test-cli/test/tests/qethernet.py index da085d8..d7354bf 100644 --- a/test-cli/test/tests/qethernet.py +++ b/test-cli/test/tests/qethernet.py @@ -52,7 +52,7 @@ class Qethernet(unittest.TestCase): self.__bwreal = float(data['end']['sum_received']['bits_per_second'])/1024/1024 # save result file with open('/tmp/ethernet-iperf.json', 'w') as outfile: - json.dump(data, outfile) + json.dump(data, outfile, indent=4) # check if BW is in the expected range self.failUnless(self.__bwreal > float(self.__bwexpected) * 0.9, diff --git a/test-cli/test/tests/qwifi.py b/test-cli/test/tests/qwifi.py index 0944dd7..a5b66e9 100644 --- a/test-cli/test/tests/qwifi.py +++ b/test-cli/test/tests/qwifi.py @@ -62,7 +62,7 @@ class Qwifi(unittest.TestCase): self.__bwreal = float(data['end']['sum_received']['bits_per_second']) / 1024 / 1024 # save result file with open('/tmp/wifi-iperf.json', 'w') as outfile: - json.dump(data, outfile) + json.dump(data, outfile, indent=4) # check if BW is in the expected range self.failUnless(self.__bwreal > float(self.__bwexpected) * 0.9, -- cgit v1.1 From 278b5729a44837e37fe13611518c1babc8de00df Mon Sep 17 00:00:00 2001 From: Hector Fernandez Date: Fri, 19 Jun 2020 13:15:56 +0200 Subject: Model and variant type are obtained from kernel cmdline instead of setup.xml. Python checks if they exist and can generate an error message to the DB if they are missing. --- test-cli/test/helpers/cmdline.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 test-cli/test/helpers/cmdline.py (limited to 'test-cli/test') diff --git a/test-cli/test/helpers/cmdline.py b/test-cli/test/helpers/cmdline.py new file mode 100644 index 0000000..fad81ac --- /dev/null +++ b/test-cli/test/helpers/cmdline.py @@ -0,0 +1,28 @@ + +class LinuxKernel: + + __kernel_vars = {} + + def __init__(self): + self.parse_kernel_cmdline() + + def parse_kernel_cmdline(self): + cmdline = open('/proc/cmdline', 'rb').read().decode() + cmd_array = cmdline.split() + i = 0 + for f in cmdline.split(): + pos = f.find('=') + if pos == -1: + cmd_array[i - 1] = cmd_array[i - 1] + " " + f + cmd_array.remove(cmd_array[i]) + else: + i += 1 + self.__kernel_vars = {} + for f in cmd_array: + dat = f.split('=') + self.__kernel_vars[dat[0]] = dat[1] + + def getkvar(self, vName, vdefault): + if vName in self.__kernel_vars: + return self.__kernel_vars[vName] + return vdefault -- cgit v1.1 From db3b1e45c47a1ef23c1ad67114a09cbec0976681 Mon Sep 17 00:00:00 2001 From: Hector Fernandez Date: Thu, 25 Jun 2020 11:45:31 +0200 Subject: Solved bugs. Adapted to DB changes. --- test-cli/test/enums/StationStates.py | 20 ++++++++++ test-cli/test/enums/__init__.py | 0 test-cli/test/helpers/testsrv_db.py | 18 +++++++-- test-cli/test/runners/simple.py | 4 +- test-cli/test/tests/qamp.py | 76 ------------------------------------ test-cli/test/tests/qamper.py | 64 ++++++++++++++++++++++-------- test-cli/test/tests/qaudio.py | 39 ------------------ test-cli/test/tests/qduplex_ser.py | 43 ++++++++++++++++++-- test-cli/test/tests/qeeprom.py | 37 ++++++++++++++++-- test-cli/test/tests/qethernet.py | 47 ++++++++++++++++------ test-cli/test/tests/qi2c.py | 31 +++++++++++++-- test-cli/test/tests/qnand.py | 33 ++++++++++++---- test-cli/test/tests/qram.py | 22 +++++++++-- test-cli/test/tests/qrtc.py | 38 ++++++++++++++++-- test-cli/test/tests/qscreen.py | 27 ------------- test-cli/test/tests/qserial.py | 29 ++++++++++++-- test-cli/test/tests/qtemplate.py | 51 ------------------------ test-cli/test/tests/qusb.py | 56 ++++++++++++++++++++++---- test-cli/test/tests/qwifi.py | 76 ++++++++++++++++++++++++++++++------ 19 files changed, 437 insertions(+), 274 deletions(-) create mode 100644 test-cli/test/enums/StationStates.py create mode 100644 test-cli/test/enums/__init__.py delete mode 100644 test-cli/test/tests/qamp.py delete mode 100644 test-cli/test/tests/qaudio.py delete mode 100644 test-cli/test/tests/qscreen.py delete mode 100644 test-cli/test/tests/qtemplate.py (limited to 'test-cli/test') diff --git a/test-cli/test/enums/StationStates.py b/test-cli/test/enums/StationStates.py new file mode 100644 index 0000000..9de5e15 --- /dev/null +++ b/test-cli/test/enums/StationStates.py @@ -0,0 +1,20 @@ +from enum import Enum, unique + + +@unique +class StationStates(Enum): + UNDEFINED = 1000 + FTP_KERNEL = 1 + FTP_DTB = 2 + MOUNT_NFS = 3 + KERNEL_BOOT = 4 + WAIT_TEST_START = 5 + STATION_ERROR = 2000 + TESTS_CHECKING_ENV = 6 + TESTS_RUNNING = 10 + TESTS_FAILED = 40 + TESTS_OK = 30 + EXTRATASKS_RUNNING = 100 + WAITING_FOR_SCANNER = 50 + FINISHED = 60 + diff --git a/test-cli/test/enums/__init__.py b/test-cli/test/enums/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/test-cli/test/helpers/testsrv_db.py b/test-cli/test/helpers/testsrv_db.py index dfb4d15..637d45c 100644 --- a/test-cli/test/helpers/testsrv_db.py +++ b/test-cli/test/helpers/testsrv_db.py @@ -202,9 +202,21 @@ class TestSrv_Database(object): r = find_between(str(err), '#', '#') # print(r) return None - - def bond_to_station(self, uuid, station): - sql = "SELECT station.bond_to_station('{}','{}')".format(uuid, station) + + def read_station_state(self, station): + sql = "SELECT * FROM station.getmystate('{}');".format(station) + # print('>>>' + sql) + try: + res = self.__sqlObject.db_execute_query(sql) + # print(res) + return res[0][0] + except Exception as err: + r = find_between(str(err), '#', '#') + # print(r) + return None + + def change_station_state(self, station, newstate): + sql = "SELECT station.setmystate('{}', '{}', NULL)".format(newstate, station) # print('>>>' + sql) try: self.__sqlObject.db_execute_query(sql) diff --git a/test-cli/test/runners/simple.py b/test-cli/test/runners/simple.py index e0418d2..22fe449 100644 --- a/test-cli/test/runners/simple.py +++ b/test-cli/test/runners/simple.py @@ -79,8 +79,8 @@ class TextTestResult(unittest.TestResult): self.__pgObj.upload_result_string(test.params["testidctl"], test.params["testid"], result["desc"], result["data"]) elif result["type"] == "file": - self.__pgObj.upload_result_file(test.params["testidctl"], test.params["testid"], result["desc"], - result["data"]) + self.__pgObj.upload_result_file(test.params["testidctl"], test.params["testid"], + result["desc"], result["data"]) # SEND TO DB THE RESULT OF THE TEST if self.result == self.PASS: status = "TEST_COMPLETE" diff --git a/test-cli/test/tests/qamp.py b/test-cli/test/tests/qamp.py deleted file mode 100644 index 56511c8..0000000 --- a/test-cli/test/tests/qamp.py +++ /dev/null @@ -1,76 +0,0 @@ -from test.helpers.syscmd import SysCommand -import unittest -import serial -import time - - -class Qamp(unittest.TestCase): - params = None - - # varlist: undercurrent, overcurrent - def __init__(self, testname, testfunc, varlist): - self.params = varlist - self._current = 0.0 - if "undercurrent" in varlist: - self._undercurrent = varlist["undercurrent"] - else: - raise Exception('undercurrent param inside Qamp must be defined') - if "overcurrent" in varlist: - self._overcurrent = varlist["overcurrent"] - else: - raise Exception('overcurrent param inside Qamp must be defined') - self._vshuntfactor = 16384.0 - self._ser = serial.Serial() - self._ser.port = '/dev/ttyUSB0' - self._ser.baudrate = 115200 - self._ser.parity = serial.PARITY_NONE - self._ser.timeout = 0 - self._ser.writeTimout = 0 - self._ser.xonxoff = False - self._ser.rtscts = False - self._ser.dsrdtr = False - super(Qamp, self).__init__(testfunc) - self._testMethodDoc = testname - - def __del__(self): - self._ser.close() - - def execute(self): - - # Open Serial port ttyUSB0 - error = 0 - try: - self._ser.open() - except: - self.fail("failed: IMPOSSIBLE OPEN USB-SERIAL PORT ( {} )".format(self._ser.port)) - error = 1 - if error == 0: - # Clean input and output buffer of serial port - self._ser.flushInput() - self._ser.flushOutput() - # Send command to read Voltage at Shunt resistor - # Prepare cmd - cmd = 'at+in?\n\r' - i = 0 - - # Write, 1 by 1 byte at a time to avoid hanging of serial receiver code of listener, emphasis being made at sleep of 50 ms. - while (i < len(cmd)): - i = i + self._ser.write(cmd[i].encode('ascii')) - time.sleep(0.05) - self._ser.read(1) - - # Read, 1 by 1 byte - res = [] - while self._ser.inWaiting() > 0: # if incoming bytes are waiting to be read from the serial input buffer - res.append(self._ser.read(1).decode('ascii')) # read the bytes and convert from binary array to ASCII - - string = ''.join(res) - string = string.replace('\n', '') - self._current = float(int(string, 0)) / self._vshuntfactor - print(self._current) - # In order to give a valid result it is importarnt to define an under current value - if self._current > float(self._overcurrent): - self.fail("failed: OVERCURRENT DETECTED ( {} )".format(self._current)) - - if self._current < float(self._undercurrent): - self.fail("failed: UNDERCURRENT DETECTED ( {} )".format(self._current)) diff --git a/test-cli/test/tests/qamper.py b/test-cli/test/tests/qamper.py index 51aa469..7a31615 100644 --- a/test-cli/test/tests/qamper.py +++ b/test-cli/test/tests/qamper.py @@ -4,7 +4,7 @@ from test.helpers.amper import Amper class Qamper(unittest.TestCase): params = None - __current = None + __resultlist = None # resultlist is a python list of python dictionaries # varlist: undercurrent, overcurrent def __init__(self, testname, testfunc, varlist): @@ -20,36 +20,66 @@ class Qamper(unittest.TestCase): else: raise Exception('overcurrent param inside Qamp must be defined') self._testMethodDoc = testname + self.__resultlist = [] def execute(self): amp = Amper() # open serial connection if not amp.open(): - self.fail("failed: can not open serial port") - return + self.__resultlist.append( + { + "desc": "Test result", + "data": "FAILED: can not open a serial port", + "type": "string" + } + ) + self.fail("Error: can not open a serial port") # check if the amperimeter is connected and working # 2 ATTEMTS if not amp.hello(): if not amp.hello(): - self.fail("failed: can not communicate") - return + self.__resultlist.append( + { + "desc": "Test result", + "data": "FAILED: can not communicate with the amperimeter", + "type": "string" + } + ) + self.fail("Error: can not communicate") # get current value (in Amperes) - self.__current = amp.getCurrent() + current = amp.getCurrent() # close serial connection amp.close() # Check current range - if float(self.__current) > float(self._overcurrent): - self.fail("failed: Overcurrent detected ( {} )".format(self.__current)) - if float(self.__current) < float(self._undercurrent): - self.fail("failed: Undercurrent detected ( {} )".format(self.__current)) + if float(current) > float(self._overcurrent): + # Overcurrent detected + self.__resultlist.append( + { + "desc": "Test result", + "data": "FAILED: Overcurrent detected ( {} A)".format(current), + "type": "string" + } + ) + self.fail("failed: Overcurrent detected ( {} )".format(current)) + elif float(current) < float(self._undercurrent): + # Undercurrent detected + self.__resultlist.append( + { + "desc": "Test result", + "data": "FAILED: Undercurrent detected ( {} A)".format(current), + "type": "string" + } + ) + self.fail("failed: Undercurrent detected ( {} )".format(current)) - def getresults(self): - # resultlist is a python list of python dictionaries - resultlist = [ + # Test successful + self.__resultlist.append( { - "desc": "current (Ampers)", - "data": self.__current, + "desc": "Test result", + "data": "OK: Current {} A".format(current), "type": "string" } - ] - return resultlist + ) + + def getresults(self): + return self.__resultlist diff --git a/test-cli/test/tests/qaudio.py b/test-cli/test/tests/qaudio.py deleted file mode 100644 index ef4da67..0000000 --- a/test-cli/test/tests/qaudio.py +++ /dev/null @@ -1,39 +0,0 @@ -from test.helpers.syscmd import SysCommand -import unittest - - -class Qaudio(unittest.TestCase): - params = None - - def __init__(self, testname, testfunc, varlist): - self.params = varlist - super(Qaudio, self).__init__(testfunc) - self._testMethodDoc = testname - if "dtmfFile" in varlist: - self._dtmfFile = varlist["dtmfFile"] - else: - raise Exception('undercurrent param inside Qamp must be defined') - self.__sum = 0 - self.__refSum = 25 # 1+3+5+7+9 - - def execute(self): - str_cmd = "aplay test/files/dtmf-13579.wav & arecord -r 8000 -d 1 recorded.wav" # .format(self.__dtmfFile) - audio_loop = SysCommand("command-name", str_cmd) - if audio_loop.execute() == -1: # BUG: Returns -1 but work - lines = audio_loop.getOutput().splitlines() - str_cmd = "multimon -t wav -a DTMF recorded.wav -q" - dtmf_decoder = SysCommand("command-name", str_cmd) - a = dtmf_decoder.execute() - if dtmf_decoder.execute() == -1: # BUG: Returns -1 but work - self.__raw_out = dtmf_decoder.getOutput() - if self.__raw_out == "": - self.fail("failed: can not execute multimon command") - lines = dtmf_decoder.getOutput().splitlines() - for i in range(0, 5): - aux = [int(s) for s in lines[i].split() if s.isdigit()] - self.__sum = self.__sum + aux[0] - self.failUnless(self.__sum == self.__refSum), "failed: incorrect dtmf code" + str(self.__sum) - else: - self.fail("failed: fail reading recorded file") - else: - self.fail("failed: fail playing/recording file") diff --git a/test-cli/test/tests/qduplex_ser.py b/test-cli/test/tests/qduplex_ser.py index c7231c2..020844a 100644 --- a/test-cli/test/tests/qduplex_ser.py +++ b/test-cli/test/tests/qduplex_ser.py @@ -9,6 +9,7 @@ class Qduplex(unittest.TestCase): __port1 = None __port2 = None __baudrate = None + __resultlist = None # resultlist is a python list of python dictionaries # varlist: port1, port2, baudrate def __init__(self, testname, testfunc, varlist): @@ -27,6 +28,7 @@ class Qduplex(unittest.TestCase): else: raise Exception('baudrate param inside Qduplex must be defined') self._testMethodDoc = testname + self.__resultlist = [] # open serial connection self.__serial1 = serial.Serial(self.__port1, self.__baudrate, timeout=1) @@ -49,9 +51,23 @@ class Qduplex(unittest.TestCase): self.__serial1.write(test_uuid) time.sleep(0.05) # there might be a small delay if self.__serial2.inWaiting() == 0: + self.__resultlist.append( + { + "desc": "Test result", + "data": "FAILED: port {} wait timeout exceded".format(self.__port2), + "type": "string" + } + ) self.fail("failed: port {} wait timeout exceded".format(self.__port2)) else: if self.__serial2.readline() != test_uuid: + self.__resultlist.append( + { + "desc": "Test result", + "data": "FAILED: port {} write/read mismatch".format(self.__port2), + "type": "string" + } + ) self.fail("failed: port {} write/read mismatch".format(self.__port2)) time.sleep(0.05) # there might be a small delay @@ -65,12 +81,33 @@ class Qduplex(unittest.TestCase): self.__serial2.write(test_uuid) time.sleep(0.05) # there might be a small delay if self.__serial1.inWaiting() == 0: + self.__resultlist.append( + { + "desc": "Test result", + "data": "FAILED: port {} wait timeout exceded".format(self.__port1), + "type": "string" + } + ) self.fail("failed: port {} wait timeout exceded".format(self.__port1)) else: if self.__serial1.readline() != test_uuid: + self.__resultlist.append( + { + "desc": "Test result", + "data": "FAILED: port {} write/read mismatch".format(self.__port1), + "type": "string" + } + ) self.fail("failed: port {} write/read mismatch".format(self.__port1)) + # Test successful + self.__resultlist.append( + { + "desc": "Test OK", + "data": "OK", + "type": "string" + } + ) + def getresults(self): - # resultlist is a python list of python dictionaries - resultlist = [] - return resultlist + return self.__resultlist diff --git a/test-cli/test/tests/qeeprom.py b/test-cli/test/tests/qeeprom.py index a65ca97..cafbc7f 100644 --- a/test-cli/test/tests/qeeprom.py +++ b/test-cli/test/tests/qeeprom.py @@ -6,12 +6,14 @@ class Qeeprom(unittest.TestCase): params = None __position = None __eeprompath = None + __resultlist = None # resultlist is a python list of python dictionaries # varlist: position, eeprompath def __init__(self, testname, testfunc, varlist): self.params = varlist super(Qeeprom, self).__init__(testfunc) self._testMethodDoc = testname + self.__resultlist = [] if "position" in varlist: self.__position = varlist["position"] else: @@ -33,13 +35,42 @@ class Qeeprom(unittest.TestCase): data_rx = p.stdout.decode('ascii') # compare both values if data_rx != data_tx: + # Both data are different + self.__resultlist.append( + { + "desc": "Test result", + "data": "FAILED: mismatch between written and received values.", + "type": "string" + } + ) self.fail("failed: mismatch between written and received values.") else: + self.__resultlist.append( + { + "desc": "Test result", + "data": "FAILED: Unable to read from the EEPROM device.", + "type": "string" + } + ) self.fail("failed: Unable to read from the EEPROM device.") else: + self.__resultlist.append( + { + "desc": "Test result", + "data": "FAILED: Unable to write on the EEPROM device.", + "type": "string" + } + ) self.fail("failed: Unable to write on the EEPROM device.") + # Test successful + self.__resultlist.append( + { + "desc": "Test result", + "data": "OK", + "type": "string" + } + ) + def getresults(self): - # resultlist is a python list of python dictionaries - resultlist = [] - return resultlist + return self.__resultlist diff --git a/test-cli/test/tests/qethernet.py b/test-cli/test/tests/qethernet.py index d7354bf..878c0a0 100644 --- a/test-cli/test/tests/qethernet.py +++ b/test-cli/test/tests/qethernet.py @@ -11,6 +11,7 @@ class Qethernet(unittest.TestCase): __port = None params = None __bwreal = None + __resultlist = None # resultlist is a python list of python dictionaries # varlist content: serverip, bwexpected, port def __init__(self, testname, testfunc, varlist): @@ -34,6 +35,7 @@ class Qethernet(unittest.TestCase): raise Exception('port param inside Qethernet must be defined') self.__numbytestx = "10M" self._testMethodDoc = testname + self.__resultlist = [] def execute(self): # execute iperf command against the server @@ -53,20 +55,43 @@ class Qethernet(unittest.TestCase): # save result file with open('/tmp/ethernet-iperf.json', 'w') as outfile: json.dump(data, outfile, indent=4) + self.__resultlist.append( + { + "desc": "iperf3 output", + "data": "/tmp/ethernet-iperf.json", + "type": "file" + } + ) # check if BW is in the expected range - self.failUnless(self.__bwreal > float(self.__bwexpected) * 0.9, - "failed: speed is lower than spected. Speed(Mbits/s)" + str(self.__bwreal)) + if self.__bwreal < float(self.__bwexpected): + self.__resultlist.append( + { + "desc": "Test result", + "data": "FAILED: speed is lower than spected. Speed(Mbits/s): " + str(self.__bwreal), + "type": "string" + } + ) + self.fail("failed: speed is lower than spected. Speed(Mbits/s): " + str(self.__bwreal)) else: - self.fail("failed: could not complete iperf command") + self.__resultlist.append( + { + "desc": "Test result", + "data": "FAILED: could not complete iperf command.", + "type": "string" + } + ) + self.fail("failed: could not complete iperf command.") - def getresults(self): - # resultlist is a python list of python dictionaries - resultlist = [ + # Test successful + self.__resultlist.append( { - "desc": "iperf3 output", - "data": "/tmp/ethernet-iperf.json", - "type": "file" + "desc": "Test result", + "data": "OK", + "type": "string" } - ] - return resultlist + ) + + def getresults(self): + + return self.__resultlist diff --git a/test-cli/test/tests/qi2c.py b/test-cli/test/tests/qi2c.py index ad7ddf0..3afedfa 100644 --- a/test-cli/test/tests/qi2c.py +++ b/test-cli/test/tests/qi2c.py @@ -4,6 +4,7 @@ import unittest class Qi2c(unittest.TestCase): params = None + __resultlist = None # resultlist is a python list of python dictionaries def __init__(self, testname, testfunc, varlist): self.params = varlist @@ -18,6 +19,7 @@ class Qi2c(unittest.TestCase): raise Exception('register param inside Qi2c must be defined') self.__devices = [] self._testMethodDoc = testname + self.__resultlist = [] def execute(self): str_cmd = "i2cdetect -a -y -r {}".format(self.__busnum) @@ -34,11 +36,32 @@ class Qi2c(unittest.TestCase): "0x{}{}".format((i - 1), hex(int((lines[i].find("UU") - 4) / 3)).split('x')[-1])) for i in range(len(self.__register)): if not (self.__register[i] in self.__devices): + self.__resultlist.append( + { + "desc": "Test result", + "data": "FAILED: device {} not found in bus i2c-{}".format(self.__register[i], self.__busnum), + "type": "string" + } + ) self.fail("failed: device {} not found in bus i2c-{}".format(self.__register[i], self.__busnum)) else: - self.fail("failed: could not complete i2cdedtect command") + self.__resultlist.append( + { + "desc": "Test result", + "data": "FAILED: could not complete i2cdedtect command", + "type": "string" + } + ) + self.fail("failed: could not complete i2cdedtect command.") + + # Test successful + self.__resultlist.append( + { + "desc": "Test result", + "data": "OK", + "type": "string" + } + ) def getresults(self): - # resultlist is a python list of python dictionaries - resultlist = [] - return resultlist + return self.__resultlist diff --git a/test-cli/test/tests/qnand.py b/test-cli/test/tests/qnand.py index 7ff7cb2..d7c22b3 100644 --- a/test-cli/test/tests/qnand.py +++ b/test-cli/test/tests/qnand.py @@ -5,6 +5,7 @@ import sh class Qnand(unittest.TestCase): params = None __device = "10M" + __resultlist = None # resultlist is a python list of python dictionaries # varlist: device def __init__(self, testname, testfunc, varlist): @@ -15,6 +16,7 @@ class Qnand(unittest.TestCase): else: raise Exception('device param inside Qnand must be defined') self._testMethodDoc = testname + self.__resultlist = [] def execute(self): try: @@ -22,17 +24,32 @@ class Qnand(unittest.TestCase): # save result with open('/tmp/nand-nandtest.txt', 'w') as outfile: n = outfile.write(p.stdout.decode('ascii')) + self.__resultlist.append( + { + "desc": "nandtest output", + "data": "/tmp/nand-nandtest.txt", + "type": "file" + } + ) except sh.ErrorReturnCode as e: + self.__resultlist.append( + { + "desc": "Test result", + "data": "FAILED: could not complete nandtest command", + "type": "string" + } + ) self.fail("failed: could not complete nandtest command") - def getresults(self): - # resultlist is a python list of python dictionaries - resultlist = [ + # Test successful + self.__resultlist.append( { - "desc": "nandtest output", - "data": "/tmp/nand-nandtest.txt", - "type": "file" + "desc": "Test result", + "data": "OK", + "type": "string" } - ] - return resultlist + ) + + def getresults(self): + return self.__resultlist diff --git a/test-cli/test/tests/qram.py b/test-cli/test/tests/qram.py index 561e980..a46424f 100644 --- a/test-cli/test/tests/qram.py +++ b/test-cli/test/tests/qram.py @@ -6,6 +6,7 @@ class Qram(unittest.TestCase): params = None __memsize = "10M" __loops = "1" + __resultlist = None # resultlist is a python list of python dictionaries # varlist: memsize, loops def __init__(self, testname, testfunc, varlist): @@ -20,15 +21,30 @@ class Qram(unittest.TestCase): else: raise Exception('loops param inside Qram must be defined') self._testMethodDoc = testname + self.__resultlist = [] def execute(self): try: p = sh.memtester(self.__memsize, "1", _out="/dev/null") except sh.ErrorReturnCode as e: + self.__resultlist.append( + { + "desc": "Test result", + "data": "FAILED: could not complete memtester command", + "type": "string" + } + ) self.fail("failed: could not complete memtester command") + # Test successful + self.__resultlist.append( + { + "desc": "Test result", + "data": "OK", + "type": "string" + } + ) + def getresults(self): - # resultlist is a python list of python dictionaries - resultlist = [] - return resultlist + return self.__resultlist diff --git a/test-cli/test/tests/qrtc.py b/test-cli/test/tests/qrtc.py index 715bcb7..6d4ecf6 100644 --- a/test-cli/test/tests/qrtc.py +++ b/test-cli/test/tests/qrtc.py @@ -7,6 +7,7 @@ import re class Qrtc(unittest.TestCase): params = None __rtc = None + __resultlist = None # resultlist is a python list of python dictionaries def __init__(self, testname, testfunc, varlist): self.params = varlist @@ -16,6 +17,7 @@ class Qrtc(unittest.TestCase): else: raise Exception('rtc param inside Qrtc must be defined') self._testMethodDoc = testname + self.__resultlist = [] def execute(self): # get time from RTC peripheral @@ -31,13 +33,41 @@ class Qrtc(unittest.TestCase): p.stdout.decode('ascii')) # check if the seconds of both times are different if time1 == time2: + self.__resultlist.append( + { + "desc": "Test result", + "data": "FAILED: RTC is not running", + "type": "string" + } + ) self.fail("failed: RTC is not running") else: - self.fail("failed: couldn't execute hwclock command 2nd time") + self.__resultlist.append( + { + "desc": "Test result", + "data": "FAILED: couldn't execute hwclock command for the second time", + "type": "string" + } + ) + self.fail("failed: couldn't execute hwclock command for the second time") else: + self.__resultlist.append( + { + "desc": "Test result", + "data": "FAILED: couldn't execute hwclock command", + "type": "string" + } + ) self.fail("failed: couldn't execute hwclock command") + # Test successful + self.__resultlist.append( + { + "desc": "Test result", + "data": "OK", + "type": "string" + } + ) + def getresults(self): - # resultlist is a python list of python dictionaries - resultlist = [] - return resultlist + return self.__resultlist diff --git a/test-cli/test/tests/qscreen.py b/test-cli/test/tests/qscreen.py deleted file mode 100644 index aaee628..0000000 --- a/test-cli/test/tests/qscreen.py +++ /dev/null @@ -1,27 +0,0 @@ -from test.helpers.syscmd import SysCommand -import unittest -from test.helpers.cv_display_test import pattern_detect - - -class Qscreen(unittest.TestCase): - params = None - - #varlist: display - def __init__(self, testname, testfunc, varlist): - self.params = varlist - super(Qscreen, self).__init__(testfunc) - if "display" in varlist: - self.__display = varlist["display"] - else: - raise Exception('display param inside Qscreen have been be defined') - self._testMethodDoc = testname - - def execute(self): - str_cmd = "fbi -T 1 --noverbose -d /dev/{} test/files/test_pattern.png".format(self.__display) - display_image = SysCommand("display_image", str_cmd) - if display_image.execute() == -1: - test_screen = pattern_detect(1) - if not test_screen=="0": - self.fail("failed: {}".format(test_screen)) - else: - self.fail("failed: could not display the image") diff --git a/test-cli/test/tests/qserial.py b/test-cli/test/tests/qserial.py index 0cb5563..faca505 100644 --- a/test-cli/test/tests/qserial.py +++ b/test-cli/test/tests/qserial.py @@ -8,6 +8,7 @@ class Qserial(unittest.TestCase): params = None __port = None __baudrate = None + __resultlist = None # resultlist is a python list of python dictionaries # varlist: port, baudrate def __init__(self, testname, testfunc, varlist): @@ -23,6 +24,7 @@ class Qserial(unittest.TestCase): else: raise Exception('baudrate param inside Qserial must be defined') self._testMethodDoc = testname + self.__resultlist = [] # open serial connection self.__serial = serial.Serial(self.__port, self.__baudrate, timeout=1) @@ -40,13 +42,34 @@ class Qserial(unittest.TestCase): self.__serial.write(test_uuid) time.sleep(0.05) # there might be a small delay if self.__serial.inWaiting() == 0: + self.__resultlist.append( + { + "desc": "Test result", + "data": "FAILED: port {} wait timeout exceded".format(self.__port), + "type": "string" + } + ) self.fail("failed: port {} wait timeout exceded".format(self.__port)) else: # check if what it was sent is equal to what has been received if self.__serial.readline() != test_uuid: + self.__resultlist.append( + { + "desc": "Test result", + "data": "FAILED: port {} write/read mismatch".format(self.__port), + "type": "string" + } + ) self.fail("failed: port {} write/read mismatch".format(self.__port)) + # Test successful + self.__resultlist.append( + { + "desc": "Test result", + "data": "OK", + "type": "string" + } + ) + def getresults(self): - # resultlist is a python list of python dictionaries - resultlist = [] - return resultlist + return self.__resultlist diff --git a/test-cli/test/tests/qtemplate.py b/test-cli/test/tests/qtemplate.py deleted file mode 100644 index 940cded..0000000 --- a/test-cli/test/tests/qtemplate.py +++ /dev/null @@ -1,51 +0,0 @@ -#IF COMMAND IS NEEDED -from test.helpers.syscmd import SysCommand -import unittest -#class name -class Qtemplate(unittest.TestCase): - # Initialize the variables - __variable1 = "Value-a" - __variable2 = "Value-b" - #.... - __variablen = "Value-n" - - def __init__(self, testname, testfunc, input1=None, inputn=None): - # Doing this we will initialize the class and later on perform a particular method inside this class - super(Qtemplate, self).__init__(testfunc) - self.__testname = testname - self.__input1 = input1 - self.__inputn = inputn - self._testMethodDoc = testname - - - - def execute(self): - str_cmd = "command" - t = SysCommand("command-name", str_cmd) - if t.execute() == 0: - self.__raw_out = t.getOutput() - if self.__raw_out == "": - return -1 - lines = t.getOutput().splitlines() - dat = lines[1] - dat = dat.decode('ascii') - dat_list = dat.split( ) - for d in dat_list: - a = dat_list.pop(0) - if a == "sec": - break - self.__MB_real = dat_list[0] - self.__BW_real = dat_list[2] - self.__dat_list = dat_list - print(self.__MB_real) - print(self.__BW_real) - self.failUnless(int(self.__BW_real)>int(self.__OKBW)*0.9,"FAIL:BECAUSE...") - else: - return -1 - return 0 - - def get_Total_MB(self): - return self.__MB_real; - - def get_Total_BW(self): - return self.__MB_real; diff --git a/test-cli/test/tests/qusb.py b/test-cli/test/tests/qusb.py index 316cef5..d952afc 100644 --- a/test-cli/test/tests/qusb.py +++ b/test-cli/test/tests/qusb.py @@ -7,11 +7,13 @@ from test.helpers.changedir import changedir class Qusb(unittest.TestCase): params = None + __resultlist = None # resultlist is a python list of python dictionaries def __init__(self, testname, testfunc, varlist): self.params = varlist super(Qusb, self).__init__(testfunc) self._testMethodDoc = testname + self.__resultlist = [] def execute(self): # Execute script usb.sh @@ -19,9 +21,19 @@ class Qusb(unittest.TestCase): test_abspath = os.path.join(test_abspath, "..", "..") p = sh.bash(os.path.join(test_abspath, 'test/scripts/usb.sh')) # Search in the stdout a pattern "/dev/sd + {letter} + {number} - q = re.search("/dev/sd\w\d", p.stdout.decode('ascii')) + match = re.search("/dev/sd\w\d", p.stdout.decode('ascii')) # get the first device which matches the pattern - device = q.group(0) + if match: + device = match.group(0) + else: + self.__resultlist.append( + { + "desc": "Test result", + "data": "FAILED: No pendrive found", + "type": "string" + } + ) + self.fail("failed: No pendrive found.") # create a new folder where the pendrive is going to be mounted sh.mkdir("-p", "/mnt/pendrive") # check if the device is mounted, and umount it @@ -50,15 +62,43 @@ class Qusb(unittest.TestCase): sh.umount("/mnt/pendrive") # check result if q is None: - self.fail("failed: wrong md5 result.") + self.__resultlist.append( + { + "desc": "Test result", + "data": "FAILED: Wrong md5 result", + "type": "string" + } + ) + self.fail("failed: Wrong md5 result.") else: # umount sh.umount("/mnt/pendrive") - self.fail("failed: unable to copy files.") + self.__resultlist.append( + { + "desc": "Test result", + "data": "FAILED: Unable to copy files to the USB memory device", + "type": "string" + } + ) + self.fail("failed: Unable to copy files to the USB memory device.") else: - self.fail("failed: unable to mount the device.") + self.__resultlist.append( + { + "desc": "Test result", + "data": "FAILED: Unable to mount the USB memory device", + "type": "string" + } + ) + self.fail("failed: Unable to mount the USB memory device.") + + # Test successful + self.__resultlist.append( + { + "desc": "Test result", + "data": "OK", + "type": "string" + } + ) def getresults(self): - # resultlist is a python list of python dictionaries - resultlist = [] - return resultlist + return self.__resultlist diff --git a/test-cli/test/tests/qwifi.py b/test-cli/test/tests/qwifi.py index a5b66e9..6f972d3 100644 --- a/test-cli/test/tests/qwifi.py +++ b/test-cli/test/tests/qwifi.py @@ -11,6 +11,7 @@ class Qwifi(unittest.TestCase): __port = None params = None __bwreal = None + __resultlist = None # resultlist is a python list of python dictionaries # varlist content: serverip, bwexpected, port def __init__(self, testname, testfunc, varlist): @@ -30,6 +31,7 @@ class Qwifi(unittest.TestCase): raise Exception('port param inside Qwifi must be defined') self.__numbytestx = "10M" self._testMethodDoc = testname + self.__resultlist = [] def execute(self): # check if the board is connected to the router by wifi @@ -63,28 +65,78 @@ class Qwifi(unittest.TestCase): # save result file with open('/tmp/wifi-iperf.json', 'w') as outfile: json.dump(data, outfile, indent=4) + self.__resultlist.append( + { + "desc": "iperf3 output", + "data": "/tmp/wifi-iperf.json", + "type": "file" + } + ) # check if BW is in the expected range - self.failUnless(self.__bwreal > float(self.__bwexpected) * 0.9, - "failed: speed is lower than spected. Speed(Mbits/s)" + str(self.__bwreal)) + if self.__bwreal < float(self.__bwexpected): + self.__resultlist.append( + { + "desc": "Test result", + "data": "FAILED: speed is lower than expected. Speed(Mbits/s): " + str(self.__bwreal), + "type": "string" + } + ) + self.fail("failed: speed is lower than expected. Speed(Mbits/s): " + str(self.__bwreal)) else: - self.fail("failed: could not complete iperf command") + self.__resultlist.append( + { + "desc": "Test result", + "data": "FAILED: could not complete iperf3 command", + "type": "string" + } + ) + self.fail("failed: could not complete iperf3 command") else: + self.__resultlist.append( + { + "desc": "Test result", + "data": "FAILED: wlan0 interface doesn't have any ip address", + "type": "string" + } + ) self.fail("failed: wlan0 interface doesn't have any ip address.") else: + self.__resultlist.append( + { + "desc": "Test result", + "data": "FAILED: could not complete ifconfig command", + "type": "string" + } + ) self.fail("failed: could not complete ifconfig command.") else: + self.__resultlist.append( + { + "desc": "Test result", + "data": "FAILED: wifi module is not connected to the router", + "type": "string" + } + ) self.fail("failed: wifi module is not connected to the router.") else: - self.fail("failed: couldn't execute iw command") + self.__resultlist.append( + { + "desc": "Test result", + "data": "FAILED: could not execute iw command", + "type": "string" + } + ) + self.fail("failed: could not execute iw command") - def getresults(self): - # resultlist is a python list of python dictionaries - resultlist = [ + # Test successful + self.__resultlist.append( { - "desc": "iperf3 output", - "data": "/tmp/wifi-iperf.json", - "type": "file" + "desc": "Test result", + "data": "OK", + "type": "string" } - ] - return resultlist + ) + + def getresults(self): + return self.__resultlist -- cgit v1.1 From 9ac8a326412b04e4873b883c2f2a056ca0b22480 Mon Sep 17 00:00:00 2001 From: Hector Fernandez Date: Thu, 25 Jun 2020 14:42:42 +0200 Subject: Modified USB test and the way it finds USB memory storages. --- test-cli/test/helpers/setup_xml.py | 48 +++++-- test-cli/test/helpers/syscmd.py | 88 ++++++++---- test-cli/test/helpers/usb.py | 270 +++++++++++++++++++++++++++++++++++++ test-cli/test/tests/qusb.py | 26 ++-- 4 files changed, 378 insertions(+), 54 deletions(-) create mode 100644 test-cli/test/helpers/usb.py (limited to 'test-cli/test') diff --git a/test-cli/test/helpers/setup_xml.py b/test-cli/test/helpers/setup_xml.py index eb8d73c..603a2ac 100644 --- a/test-cli/test/helpers/setup_xml.py +++ b/test-cli/test/helpers/setup_xml.py @@ -1,22 +1,23 @@ import xml.etree.ElementTree as XMLParser + class XMLSetup (object): - """aaaaa""" + """XML Setup Parser""" __tree = None # Parser __dbType = None # database connection required: PgSQLConnection __dbConnectionRaw = None # Connection string in raw __dbConnectionStr = None # Connection string to use in sql object connection def __init__(self, filename): - """aaaaa""" + """Parse the file in the constructor""" self.__tree = XMLParser.parse(filename) def __del__(self): - """aaaaa""" + """Destructor do nothing""" pass - def getdbConnectionStr (self): - """aaaaa""" + def getdbConnectionStr(self): + """XML to database connection string""" if self.__dbConnectionRaw is not None: return self.__dbConnectionRaw @@ -29,19 +30,44 @@ class XMLSetup (object): return None - def getPostgresConnectionStr (self): - """aaaaa""" + def getPostgresConnectionStr(self): + """Get Connection string """ str = self.__dbConnectionRaw del str['type'] return str - def getMysqlConnectionStr (self): - """aaaaa""" - pass + def getBoard(self, key, default): + for element in self.__tree.iter('board'): + if key in element.attrib: + return element.attrib[key] + return default + + def getTempPath(self, key, default): + for element in self.__tree.iter('tmpPath'): + if key in element.attrib: + return element.attrib[key] + return default + + def getKeyVal(self, tag, key, default): + for element in self.__tree.iter(tag): + if key in element.attrib: + return element.attrib[key] + return default def gettagKey (self, xmltag, xmlkey): """aaaaa""" for element in self.__tree.iter(xmltag): return element.attrib[xmlkey] - return None \ No newline at end of file + return None + + def getUSBlist(self): + list = {} + count = 0 + for elements in self.__tree.iter("usbdev"): + sublist = {} + for key,val in elements.items(): + sublist[key] = val + list[count] = sublist + count += 1 + return list \ No newline at end of file diff --git a/test-cli/test/helpers/syscmd.py b/test-cli/test/helpers/syscmd.py index 6114449..7223774 100644 --- a/test-cli/test/helpers/syscmd.py +++ b/test-cli/test/helpers/syscmd.py @@ -1,5 +1,6 @@ import unittest import subprocess +import threading class TestSysCommand(unittest.TestCase): @@ -9,24 +10,15 @@ class TestSysCommand(unittest.TestCase): __outdata = None __outtofile = False - #varlist: str_cmd, outtofile - def __init__(self, testname, testfunc, varlist): + def __init__(self, testname, testfunc, str_cmd, outtofile=False): """ init """ super(TestSysCommand, self).__init__(testfunc) - if "str_cmd" in varlist: - self.__str_cmd = varlist["str_cmd"] - else: - raise Exception('str_cmd param inside TestSysCommand have been be defined') + self.__str_cmd = str_cmd self.__testname = testname - if "outtofile" in varlist: - self.__outtofile = varlist["outtofile"] - if self.__outtofile is True: - self.__outfilename = '/tmp/{}.txt'.format(testname) - else: - self.__outtofile = None - self.__outfilename = None + self.__outtofile = outtofile self._testMethodDoc = testname - + if self.__outtofile is True: + self.__outfilename = '/tmp/{}.txt'.format(testname) def getName(self): return self.__testname @@ -50,7 +42,7 @@ class TestSysCommand(unittest.TestCase): else: res = -3 outdata = completed.stdout - self.longMessage=str(outdata).replace("'","") + self.longMessage = str(outdata).replace("'", "") self.assertTrue(True) except subprocess.CalledProcessError as err: self.assertTrue(False) @@ -62,11 +54,14 @@ class TestSysCommand(unittest.TestCase): 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 """ @@ -74,31 +69,37 @@ class SysCommand(object): self.__cmdname = cmdname def getName(self): - return self.__testname + 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): - res = -1 + # try: + self.__outdata = None + self.__errdata = None + self.__exception = None try: - self.__outdata = None - self.__errdata = None completed = subprocess.run( self.__str_cmd, - check=True, + check=False, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) + self.__returnCode = completed.returncode self.__outdata = completed.stdout - if completed.returncode is 0: - res = 0 - if completed.stderr.decode('ascii') != "": - res = -1 - self.__errdata = completed.stderr + self.__errdata = completed.stderr.decode('ascii') except subprocess.CalledProcessError as err: - res = -2 - except Exception as t: - res = -3 - return res + self.__exception = err + self.__returnCode = -1 + return self.__returnCode def getOutput(self): return self.__outdata @@ -106,6 +107,12 @@ class SysCommand(object): 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() @@ -114,3 +121,26 @@ class SysCommand(object): 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() diff --git a/test-cli/test/helpers/usb.py b/test-cli/test/helpers/usb.py new file mode 100644 index 0000000..8f8848d --- /dev/null +++ b/test-cli/test/helpers/usb.py @@ -0,0 +1,270 @@ +from test.helpers.syscmd import SysCommand +from test.helpers.amper import Amper +import scanf +import os +import json + + +class USBDevices(object): + __dev_list = {} + __serial_converter = {} + __usb_disk = {} + __usb_amper = {} + __dev_list_filtered = {} + __usb_mstorage = {} + __xml_config = None + + def __init__(self, xml): + self.__xml_config = xml + self.__getusblist() + self.__getSerialDevices() + self.__getAmper() + self.__getMassStorage() + + def print_usb(self): + print("------ usb list -------") + print(json.dumps(self.__dev_list)) + print("------ serial converter list -------") + print(self.__serial_converter) + print("------ usb disk list -------") + print(self.__usb_disk) + print("------ usb amper list -------") + print(self.__usb_amper) + print("------ usb mass storage list -------") + print(self.__usb_mstorage) + print("------ filtered list -------") + print(json.dumps(self.__dev_list_filtered)) + + def refresh(self): + self.__dev_list = {} + self.__serial_converter = {} + self.__usb_disk = {} + self.__usb_amper = {} + self.__usb_mstorage = {} + self.__dev_list_filtered = {} + self.__getusblist() + self.__getSerialDevices() + self.__getAmper() + self.__getMassStorage() + + def getMassStorage(self): + return self.__usb_mstorage + + def getAmper(self): + return self.__usb_amper + + def __getAmper(self): + for c, s_items in self.__serial_converter.items(): + for k,v in s_items.items(): + if k.find("USB") != -1 and v == "Prolific_Technology_Inc._USB-Serial_Controller": + testAmper = Amper(port=k) + testAmper.open() + res = testAmper.hello() + if res: + self.__usb_amper = {'port': k, 'ver': testAmper.getVersion()} + testAmper.close() + if res: + return + + def __getMassStorage(self): + for c, s_items in self.__usb_disk.items(): + for k,v in s_items.items(): + if k == "udev": + if v.get('ID_MODEL', None) == "File-Stor_Gadget" or v.get('ID_FS_LABEL', None) != "NODE_L031K6": + self.__usb_mstorage = {'disk': v.get('DEVNAME', ''), 'id': v.get('ID_FS_LABEL_ENC', '')} + + + def __check_ignore_usb_list(self, usb_list, dev_list): + count = 0 + ignore = "0" + for _, l in usb_list.items(): + for k, v in l.items(): + if k == "ignore": + ignore = v + else: + value = dev_list.get(k, None) + if v == value: + count += 1 + else: + count = 0 + break + if count >= len(l) -1: + break + + if count > 0: + if ignore == "1": + return True + return False + + + def __create_ignore_list(self, usb_list): + count = 1 + for _, dev in self.__dev_list.items(): + if not self.__check_ignore_usb_list(usb_list, dev): + self.__dev_list_filtered[count] = dev + count += 1 + + def __getusblist(self): + count = 0 + res = open('/sys/kernel/debug/usb/devices', 'rb').read().decode() + list = {} + for i in res.split('\n'): + if i.find('T:') != -1: + if len(list) > 0: + count += 1 + self.__dev_list[count] = list + list = self.__parse_T(i) + elif i.find('D:') != -1: + list = {**list, **self.__parse_D(i)} + elif i.find('P:') != -1: + list = {**list, **self.__parse_P(i)} + elif i.find('S:') != -1: + list = {**list, **self.__parse_S(i)} + else: + """ Ignore all rest""" + pass + + if count > 0: + count += 1 + self.__dev_list[count] = list + + self.__create_ignore_list(self.__xml_config.getUSBlist()) + + + def __parse_T(self, str): + data = {} + res = scanf.scanf("T: Bus=%2c Lev=%2c Prnt=%2c Port=%2c Cnt=%2c Dev#=%3c Spd=%s MxCh=%2c", str) + data["BUS"] = res[0] + data["LEV"] = res[1] + data["PRNT"] = res[2] + data["PORT"] = res[3] + data["CNT"] = res[4] + data["DEV"] = res[5].lstrip() + data["SPEED"] = res[6].rstrip() + data["MXCH"] = res[7].lstrip() + return data + + def __parse_D(self, str): + data = {} + str += ' ' + res = scanf.scanf("D: Ver=%5c Cls=%2c(%s ) %s ", str) + data["VER"] = res[0].lstrip() + data["CLASS"] = res[1] + return data + + def __parse_P(self, str): + data = {} + str += ' ' + res = scanf.scanf("P: Vendor=%4c ProdID=%4c %s", str) + data["VENDOR"] = res[0].lstrip() + data["PRODID"] = res[1] + return data + + def __parse_S(self, str): + data = {} + if str.find('Manufacturer') != -1: + pos = str.find('Manufacturer=') + data["MANUFACTURER"] = str[pos + len('Manufacturer='):].rstrip() + elif str.find('Product') != -1: + pos = str.find('Product=') + data["PRODUCT"] = str[pos + len('Product='):].rstrip() + elif str.find('SerialNumber') != -1: + pos = str.find('SerialNumber=') + data["SERIAL"] = str[pos + len('SerialNumber='):].rstrip() + else: + pass + return data + + def finddevicebytag(self, tag, str): + t = {} + count = 0 + for i, k in self.__dev_list.items(): + if tag in k: + if k[tag].find(str) != -1: + t[count] = k + count += 1 + return t + + def __getSerialDevices(self): + self.__serial_converter = {} + self.__usb_disk = {} + self.__usb_amper = {} + test_myPath = os.path.dirname(os.path.abspath(__file__)) + test_myPath = test_myPath + "/../" + s = SysCommand('usb', '{}/scripts/usb.sh'.format(test_myPath)) + s.execute() + data_list = s.getOutput().decode() + for i in data_list.split('\n'): + if len(i) > 0: + pos_div = i.find('-') + dev = i[0:pos_div - 1] + devName = i[pos_div + 2:] + # print("dev: {}".format(dev)) + # print("devName: {}".format(devName)) + res = scanf.scanf("/dev/sd%c", dev) + if res is not None: + dev_id = res[0][0] + # Now verify if is Disk or Partition + res = scanf.scanf("/dev/sd%c%c", dev) + if res is not None: + # this is a partition and we can ignore it + pass + else: + self.__usb_disk[dev_id] = {dev: devName, 'udev': self.__getudevquery(dev)} + else: + res = scanf.scanf("/dev/ttyUSB%c", dev) + if res is not None: + serial_id = res[0][0] + self.__serial_converter[serial_id] = {dev: devName, 'udev': self.__getudevquery(dev)} + + def __getudevquery(self, device): + list = {} + s = SysCommand('query-udev', 'udevadm info --query=all -n {}'.format(device)) + res = s.execute() + if res != 0: + return None + for i in s.getOutput().decode().split('\n'): + if i.find('P:') != -1: + list = self.__parse_udev_P(i) + elif i.find('S:') != -1: + list = {**list, **self.__parse_udev_S(i)} + elif i.find('N:') != -1: + list = {**list, **self.__parse_udev_N(i)} + elif i.find('S:') != -1: + list = {**list, **self.__parse_udev_S(i)} + elif i.find('E:') != -1: + list = {**list, **self.__parse_udev_E(i)} + return list + + def __parse_udev_P(self, str): + pos = str.find('P: ') + str = str[len('P: ') + pos:] + return {'PATH': str} + + def __parse_udev_S(self, str): + pos = str.find('P: ') + str = str[len('P: ') + pos:] + pos = str.find('disk/by-id/') + if pos != -1: + return {'DISK_BY_ID': str[len('disk/by-id/') + pos:]} + pos = str.find('disk/by-path/') + if pos != -1: + return {'DISK_BY_PATH': str[len('disk/by-path/') + pos:]} + pos = str.find('disk/by-uuid/') + if pos != -1: + return {'DISK_BY_UUID': str[len('disk/by-uuid/') + pos:]} + else: + return {} + + def __parse_udev_N(self, str): + pos = str.find('N: ') + str = str[len('N: ') + pos:] + return {'DEV_NAME': str} + + def __parse_udev_E(self, str): + pos = str.find('E: ') + str = str[len('E: ') + pos:] + pos = str.find('=') + str_key = str[:pos] + str_value = str[pos + 1:] + return {str_key: str_value} diff --git a/test-cli/test/tests/qusb.py b/test-cli/test/tests/qusb.py index d952afc..32d99ef 100644 --- a/test-cli/test/tests/qusb.py +++ b/test-cli/test/tests/qusb.py @@ -2,6 +2,7 @@ import sh import unittest import re import os +from test.helpers.usb import USBDevices from test.helpers.changedir import changedir @@ -16,24 +17,20 @@ class Qusb(unittest.TestCase): self.__resultlist = [] def execute(self): - # Execute script usb.sh - test_abspath = os.path.dirname(os.path.abspath(__file__)) - test_abspath = os.path.join(test_abspath, "..", "..") - p = sh.bash(os.path.join(test_abspath, 'test/scripts/usb.sh')) - # Search in the stdout a pattern "/dev/sd + {letter} + {number} - match = re.search("/dev/sd\w\d", p.stdout.decode('ascii')) - # get the first device which matches the pattern - if match: - device = match.group(0) + # get usb device + dev_obj = USBDevices(self.params["xml"]) + if dev_obj.getMassStorage(): + device = dev_obj.getMassStorage()['disk'] + "1" else: self.__resultlist.append( { "desc": "Test result", - "data": "FAILED: No pendrive found", + "data": "FAILED: No USB memory found", "type": "string" } ) - self.fail("failed: No pendrive found.") + self.fail("failed: No USB memory found.") + # create a new folder where the pendrive is going to be mounted sh.mkdir("-p", "/mnt/pendrive") # check if the device is mounted, and umount it @@ -48,11 +45,12 @@ class Qusb(unittest.TestCase): p = sh.mount(device, "/mnt/pendrive") if p.exit_code == 0: # copy files - p = sh.cp(os.path.join(test_abspath, "test/files/usbtest/usbdatatest.bin"), - os.path.join(test_abspath, "test/files/usbtest/usbdatatest.md5"), + test_abspath = os.path.dirname(os.path.abspath(__file__)) + "/../" + p = sh.cp(os.path.join(test_abspath, "files/usbtest/usbdatatest.bin"), + os.path.join(test_abspath, "files/usbtest/usbdatatest.md5"), "/mnt/pendrive") if p.exit_code == 0: - # check md5 + # check with changedir("/mnt/pendrive/"): p = sh.md5sum("-c", "usbdatatest.md5") q = re.search("OK", p.stdout.decode('ascii')) -- cgit v1.1 From 34df86b37d6838b115e65e5f3a332344afeb86b8 Mon Sep 17 00:00:00 2001 From: Hector Fernandez Date: Wed, 1 Jul 2020 10:45:34 +0200 Subject: Changes to adapt to new way to save results in DB. Created audio test. Added protections against unexpected status in DB. --- test-cli/test/files/dtmf-13579.wav | Bin 8045 -> 17722 bytes test-cli/test/files/test_pattern.png | Bin 4457 -> 0 bytes test-cli/test/helpers/DiskHelpers.py | 9 +++++ test-cli/test/helpers/int_registers.py | 2 +- test-cli/test/helpers/testsrv_db.py | 44 +++++++++------------- test-cli/test/runners/simple.py | 17 ++++----- test-cli/test/tasks/flasheeprom.py | 2 +- test-cli/test/tasks/generatedmesg.py | 17 --------- test-cli/test/tests/qamper.py | 61 ++++++++++-------------------- test-cli/test/tests/qaudio.py | 59 +++++++++++++++++++++++++++++ test-cli/test/tests/qdmesg.py | 38 +++++++++++++++++++ test-cli/test/tests/qduplex_ser.py | 40 ++------------------ test-cli/test/tests/qeeprom.py | 33 ++-------------- test-cli/test/tests/qethernet.py | 37 ++++-------------- test-cli/test/tests/qi2c.py | 67 --------------------------------- test-cli/test/tests/qmmcflash.py | 15 ++++++++ test-cli/test/tests/qnand.py | 29 ++++---------- test-cli/test/tests/qram.py | 20 ++-------- test-cli/test/tests/qrtc.py | 33 ++-------------- test-cli/test/tests/qserial.py | 26 ++----------- test-cli/test/tests/qusb.py | 40 ++------------------ test-cli/test/tests/qwifi.py | 63 ++++--------------------------- 22 files changed, 208 insertions(+), 444 deletions(-) delete mode 100644 test-cli/test/files/test_pattern.png create mode 100644 test-cli/test/helpers/DiskHelpers.py delete mode 100644 test-cli/test/tasks/generatedmesg.py create mode 100644 test-cli/test/tests/qaudio.py create mode 100644 test-cli/test/tests/qdmesg.py delete mode 100644 test-cli/test/tests/qi2c.py create mode 100644 test-cli/test/tests/qmmcflash.py (limited to 'test-cli/test') diff --git a/test-cli/test/files/dtmf-13579.wav b/test-cli/test/files/dtmf-13579.wav index 1ca5b93..c5b416a 100644 Binary files a/test-cli/test/files/dtmf-13579.wav and b/test-cli/test/files/dtmf-13579.wav differ diff --git a/test-cli/test/files/test_pattern.png b/test-cli/test/files/test_pattern.png deleted file mode 100644 index 353aab5..0000000 Binary files a/test-cli/test/files/test_pattern.png and /dev/null differ diff --git a/test-cli/test/helpers/DiskHelpers.py b/test-cli/test/helpers/DiskHelpers.py new file mode 100644 index 0000000..79b661e --- /dev/null +++ b/test-cli/test/helpers/DiskHelpers.py @@ -0,0 +1,9 @@ +import stat +import os + + +def disk_exists(path): + try: + return stat.S_ISBLK(os.stat(path).st_mode) + except: + return False diff --git a/test-cli/test/helpers/int_registers.py b/test-cli/test/helpers/int_registers.py index 0feb8da..9de503b 100644 --- a/test-cli/test/helpers/int_registers.py +++ b/test-cli/test/helpers/int_registers.py @@ -44,7 +44,7 @@ def get_die_id(modelid): return dieid -def get_mac(modelid): +def get_internal_mac(modelid): mac = None if modelid.find("IGEP0034") == 0 or modelid.find("SOPA0000") == 0: diff --git a/test-cli/test/helpers/testsrv_db.py b/test-cli/test/helpers/testsrv_db.py index 637d45c..7eeefb3 100644 --- a/test-cli/test/helpers/testsrv_db.py +++ b/test-cli/test/helpers/testsrv_db.py @@ -91,8 +91,8 @@ class TestSrv_Database(object): # print(r) return None - def finish_test(self, testid_ctl, testid, newstatus): - sql = "SELECT isee.f_finish_test({},{},'{}')".format(testid_ctl, testid, newstatus) + def finish_test(self, testid_ctl, testid, newstatus, textresult): + sql = "SELECT isee.f_finish_test({},{},'{}','{}')".format(testid_ctl, testid, newstatus, textresult) # print('>>>' + sql) try: self.__sqlObject.db_execute_query(sql) @@ -101,35 +101,13 @@ class TestSrv_Database(object): # print(r) return None - def upload_result_string(self, testid_ctl, testid, descrip, strdata): - sql = "SELECT isee.f_upload_result_string({},{},'{}','{}')".format(testid_ctl, testid, descrip, strdata) - # print('>>>' + sql) - try: - self.__sqlObject.db_execute_query(sql) - except Exception as err: - r = find_between(str(err), '#', '#') - # print(r) - return None - - def upload_result_file(self, testid_ctl, testid, descrip, filepath): + def upload_result_file(self, testid_ctl, testid, desc, filepath, mimetype): try: # generate a new oid fileoid = self.__sqlObject.db_upload_large_file(filepath) # insert into a table - sql = "SELECT isee.f_upload_result_file({},{},'{}','{}')".format(testid_ctl, testid, descrip, fileoid) - # print('>>>' + sql) - self.__sqlObject.db_execute_query(sql) - except Exception as err: - r = find_between(str(err), '#', '#') - # print(r) - return None - - def upload_dmesg(self, testid_ctl, filepath): - try: - # generate a new oid - fileoid = self.__sqlObject.db_upload_large_file(filepath) - # insert into a table - sql = "SELECT isee.f_upload_dmesg_file({},'{}')".format(testid_ctl, fileoid) + sql = "SELECT isee.f_upload_result_file({},{},'{}','{}','{}')".format(testid_ctl, testid, desc, fileoid, + mimetype) # print('>>>' + sql) self.__sqlObject.db_execute_query(sql) except Exception as err: @@ -224,3 +202,15 @@ class TestSrv_Database(object): r = find_between(str(err), '#', '#') # print(r) return None + + def get_setup_variable(self, skey): + sql = "SELECT * FROM admin.get_setupvar('{}')".format(skey) + # print('>>>' + sql) + try: + res = self.__sqlObject.db_execute_query(sql) + # print(res) + return res[0][0] + except Exception as err: + r = find_between(str(err), '#', '#') + # print(r) + return None diff --git a/test-cli/test/runners/simple.py b/test-cli/test/runners/simple.py index 22fe449..2eb61a4 100644 --- a/test-cli/test/runners/simple.py +++ b/test-cli/test/runners/simple.py @@ -59,8 +59,9 @@ class TextTestResult(unittest.TestResult): def addError(self, test, err): unittest.TestResult.addError(self, test, err) - test.longMessage = err[1] + # test.longMessage = err[1] self.result = self.ERROR + print(err[1]) def addFailure(self, test, err): unittest.TestResult.addFailure(self, test, err) @@ -73,17 +74,13 @@ class TextTestResult(unittest.TestResult): self.runner.writeUpdate(self.result) # save result data for result in test.getresults(): - if "desc" in result.keys() and result["desc"]: - if "type" in result.keys() and "data" in result.keys(): - if result["type"] == "string": - self.__pgObj.upload_result_string(test.params["testidctl"], test.params["testid"], - result["desc"], result["data"]) - elif result["type"] == "file": - self.__pgObj.upload_result_file(test.params["testidctl"], test.params["testid"], - result["desc"], result["data"]) + self.__pgObj.upload_result_file(test.params["testidctl"], test.params["testid"], + result["description"], result["filepath"], result["mimetype"]) # SEND TO DB THE RESULT OF THE TEST if self.result == self.PASS: status = "TEST_COMPLETE" + resulttext = test.gettextresult() else: status = "TEST_FAILED" - self.__pgObj.finish_test(test.params["testidctl"], test.params["testid"], status) + resulttext = test.longMessage + self.__pgObj.finish_test(test.params["testidctl"], test.params["testid"], status, resulttext) diff --git a/test-cli/test/tasks/flasheeprom.py b/test-cli/test/tasks/flasheeprom.py index 71c1bdd..feeb04c 100644 --- a/test-cli/test/tasks/flasheeprom.py +++ b/test-cli/test/tasks/flasheeprom.py @@ -21,7 +21,7 @@ def _generate_data_bytes(boarduuid, mac0, mac1): def _generate_output_data(data_rx): - boarduuid = data_rx[8:44].decode('ascii') # no 8:45 porque el \0 final hace que no funcione postgresql + boarduuid = data_rx[8:44].decode('ascii') # no 8:45 porque el \0 final hace que no funcione postgresql mac0 = binascii.hexlify(data_rx[45:51]).decode('ascii') mac1 = binascii.hexlify(data_rx[51:57]).decode('ascii') smac0 = ':'.join(mac0[i:i + 2] for i in range(0, len(mac0), 2)) diff --git a/test-cli/test/tasks/generatedmesg.py b/test-cli/test/tasks/generatedmesg.py deleted file mode 100644 index aa9d9ce..0000000 --- a/test-cli/test/tasks/generatedmesg.py +++ /dev/null @@ -1,17 +0,0 @@ -import sh - - -def generate_dmesg(tidctl, pgObj): - print("Start getting DMESG...") - p = sh.dmesg("--color=never") - if p.exit_code != 0: - print("DMESG: Unknown error.") - return 1 - else: - # save dmesg in a file - with open('/tmp/dmesg.txt', 'w') as outfile: - n = outfile.write(p.stdout.decode('ascii')) - # save dmesg result in DB - pgObj.upload_dmesg(tidctl, '/tmp/dmesg.txt') - print("DMESG: saved succesfully.") - return 0 diff --git a/test-cli/test/tests/qamper.py b/test-cli/test/tests/qamper.py index 7a31615..b4d57e3 100644 --- a/test-cli/test/tests/qamper.py +++ b/test-cli/test/tests/qamper.py @@ -26,60 +26,37 @@ class Qamper(unittest.TestCase): amp = Amper() # open serial connection if not amp.open(): - self.__resultlist.append( - { - "desc": "Test result", - "data": "FAILED: can not open a serial port", - "type": "string" - } - ) self.fail("Error: can not open a serial port") # check if the amperimeter is connected and working # 2 ATTEMTS if not amp.hello(): if not amp.hello(): - self.__resultlist.append( - { - "desc": "Test result", - "data": "FAILED: can not communicate with the amperimeter", - "type": "string" - } - ) self.fail("Error: can not communicate") # get current value (in Amperes) - current = amp.getCurrent() + self.current = amp.getCurrent() + # save result in a file + with open('/tmp/station/amper.txt', 'w') as outfile: + n = outfile.write("Current: {} A".format(self.current)) + outfile.close() + self.__resultlist.append( + { + "description": "Amperimeter values", + "filepath": "/tmp/station/amper.txt", + "mimetype": "text/plain" + } + ) # close serial connection amp.close() # Check current range - if float(current) > float(self._overcurrent): + if float(self.current) > float(self._overcurrent): # Overcurrent detected - self.__resultlist.append( - { - "desc": "Test result", - "data": "FAILED: Overcurrent detected ( {} A)".format(current), - "type": "string" - } - ) - self.fail("failed: Overcurrent detected ( {} )".format(current)) - elif float(current) < float(self._undercurrent): + self.fail("failed: Overcurrent detected ( {} )".format(self.current)) + elif float(self.current) < float(self._undercurrent): # Undercurrent detected - self.__resultlist.append( - { - "desc": "Test result", - "data": "FAILED: Undercurrent detected ( {} A)".format(current), - "type": "string" - } - ) - self.fail("failed: Undercurrent detected ( {} )".format(current)) - - # Test successful - self.__resultlist.append( - { - "desc": "Test result", - "data": "OK: Current {} A".format(current), - "type": "string" - } - ) + self.fail("failed: Undercurrent detected ( {} )".format(self.current)) def getresults(self): return self.__resultlist + + def gettextresult(self): + return "{} A".format(self.current) diff --git a/test-cli/test/tests/qaudio.py b/test-cli/test/tests/qaudio.py new file mode 100644 index 0000000..5baffe4 --- /dev/null +++ b/test-cli/test/tests/qaudio.py @@ -0,0 +1,59 @@ +import unittest +import sh +import wave +import contextlib + + +def calc_audio_duration(fname): + with contextlib.closing(wave.open(fname, 'r')) as f: + frames = f.getnframes() + rate = f.getframerate() + duration = frames / float(rate) + f.close() + return duration + + +class Qaudio(unittest.TestCase): + params = None + __resultlist = None # resultlist is a python list of python dictionaries + __dtmf_secuence = ["1", "3", "5", "7", "9"] + + def __init__(self, testname, testfunc, varlist): + self.params = varlist + super(Qaudio, self).__init__(testfunc) + self._testMethodDoc = testname + self.__resultlist = [] + + def execute(self): + # analize audio file + recordtime = calc_audio_duration("test/files/dtmf-13579.wav") + 0.15 + # play and record + p1 = sh.aplay("test/files/dtmf-13579.wav", _bg=True) + p2 = sh.arecord("-r", 8000, "-d", recordtime, "/tmp/station/recorded.wav", _bg=True) + p1.wait() + p2.wait() + if p1.exit_code == 0 and p2.exit_code == 0: + p = sh.multimon("-t", "wav", "-a", "DTMF", "/tmp/station/recorded.wav", "-q") + if p.exit_code == 0: + lines = p.stdout.decode('ascii').splitlines() + self.__dtmf_secuence_result = [] + for li in lines: + if li.split(" ")[0] == "DTMF:": + self.__dtmf_secuence_result.append(li.split(" ")[1]) + # compare original and processed dtmf sequence + if len(self.__dtmf_secuence) == len(self.__dtmf_secuence_result): + for i in range(len(self.__dtmf_secuence)): + if self.__dtmf_secuence[i] != self.__dtmf_secuence_result[i]: + self.fail("failed: sent and received DTMF sequence don't match.") + else: + self.fail("failed: received DTMF sequence is shorter than expected.") + else: + self.fail("failed: unable to use multimon command.") + else: + self.fail("failed: unable to play/record audio.") + + def getresults(self): + return self.__resultlist + + def gettextresult(self): + return "" diff --git a/test-cli/test/tests/qdmesg.py b/test-cli/test/tests/qdmesg.py new file mode 100644 index 0000000..45dd4eb --- /dev/null +++ b/test-cli/test/tests/qdmesg.py @@ -0,0 +1,38 @@ +import sh +import os.path +from os import path + +class Qdmesg: + params = None + __resultlist = None # resultlist is a python list of python dictionaries + + def __init__(self, testname, testfunc, varlist): + self.params = varlist + self._testMethodDoc = testname + self.__resultlist = [] + self.pgObj = varlist["db"] + + def execute(self): + print("running dmesg test") + self.pgObj.run_test(self.params["testidctl"], self.params["testid"]) + # delete previous file + if path.exists("/tmp/station/dmesg.txt"): + print("dmesg remove") + os.remove("/tmp/station/dmesg.txt") + # generate file + p = sh.dmesg("--color=never", _out="/tmp/station/dmesg.txt") + print("Exit code: {}".format(p.exit_code)) + if p.exit_code == 0: + # save result + # with open('/tmp/station/dmesg.txt', 'w') as outfile: + # n = outfile.write(p.stdout.decode('ascii')) + # outfile.close() + + # save dmesg result in DB + self.pgObj.upload_result_file(self.params["testidctl"], self.params["testid"], "dmesg output", + "/tmp/station/dmesg.txt", "text/plain") + self.pgObj.finish_test(self.params["testidctl"], self.params["testid"], "TEST_COMPLETE", "") + print("success dmesg test") + else: + self.pgObj.finish_test(self.params["testidctl"], self.params["testid"], "TEST_FAILED", "") + print("fail dmesg test") diff --git a/test-cli/test/tests/qduplex_ser.py b/test-cli/test/tests/qduplex_ser.py index 020844a..170039b 100644 --- a/test-cli/test/tests/qduplex_ser.py +++ b/test-cli/test/tests/qduplex_ser.py @@ -51,23 +51,9 @@ class Qduplex(unittest.TestCase): self.__serial1.write(test_uuid) time.sleep(0.05) # there might be a small delay if self.__serial2.inWaiting() == 0: - self.__resultlist.append( - { - "desc": "Test result", - "data": "FAILED: port {} wait timeout exceded".format(self.__port2), - "type": "string" - } - ) self.fail("failed: port {} wait timeout exceded".format(self.__port2)) else: if self.__serial2.readline() != test_uuid: - self.__resultlist.append( - { - "desc": "Test result", - "data": "FAILED: port {} write/read mismatch".format(self.__port2), - "type": "string" - } - ) self.fail("failed: port {} write/read mismatch".format(self.__port2)) time.sleep(0.05) # there might be a small delay @@ -81,33 +67,13 @@ class Qduplex(unittest.TestCase): self.__serial2.write(test_uuid) time.sleep(0.05) # there might be a small delay if self.__serial1.inWaiting() == 0: - self.__resultlist.append( - { - "desc": "Test result", - "data": "FAILED: port {} wait timeout exceded".format(self.__port1), - "type": "string" - } - ) self.fail("failed: port {} wait timeout exceded".format(self.__port1)) else: if self.__serial1.readline() != test_uuid: - self.__resultlist.append( - { - "desc": "Test result", - "data": "FAILED: port {} write/read mismatch".format(self.__port1), - "type": "string" - } - ) self.fail("failed: port {} write/read mismatch".format(self.__port1)) - # Test successful - self.__resultlist.append( - { - "desc": "Test OK", - "data": "OK", - "type": "string" - } - ) - def getresults(self): return self.__resultlist + + def gettextresult(self): + return "" diff --git a/test-cli/test/tests/qeeprom.py b/test-cli/test/tests/qeeprom.py index cafbc7f..7fc9fcd 100644 --- a/test-cli/test/tests/qeeprom.py +++ b/test-cli/test/tests/qeeprom.py @@ -36,41 +36,14 @@ class Qeeprom(unittest.TestCase): # compare both values if data_rx != data_tx: # Both data are different - self.__resultlist.append( - { - "desc": "Test result", - "data": "FAILED: mismatch between written and received values.", - "type": "string" - } - ) self.fail("failed: mismatch between written and received values.") else: - self.__resultlist.append( - { - "desc": "Test result", - "data": "FAILED: Unable to read from the EEPROM device.", - "type": "string" - } - ) self.fail("failed: Unable to read from the EEPROM device.") else: - self.__resultlist.append( - { - "desc": "Test result", - "data": "FAILED: Unable to write on the EEPROM device.", - "type": "string" - } - ) self.fail("failed: Unable to write on the EEPROM device.") - # Test successful - self.__resultlist.append( - { - "desc": "Test result", - "data": "OK", - "type": "string" - } - ) - def getresults(self): return self.__resultlist + + def gettextresult(self): + return "" diff --git a/test-cli/test/tests/qethernet.py b/test-cli/test/tests/qethernet.py index 878c0a0..3b2f197 100644 --- a/test-cli/test/tests/qethernet.py +++ b/test-cli/test/tests/qethernet.py @@ -1,6 +1,5 @@ import unittest import sh -import re import json @@ -53,45 +52,25 @@ class Qethernet(unittest.TestCase): data = json.loads(p.stdout.decode('ascii')) self.__bwreal = float(data['end']['sum_received']['bits_per_second'])/1024/1024 # save result file - with open('/tmp/ethernet-iperf.json', 'w') as outfile: + with open('/tmp/station/ethernet-iperf3.json', 'w') as outfile: json.dump(data, outfile, indent=4) + outfile.close() self.__resultlist.append( { - "desc": "iperf3 output", - "data": "/tmp/ethernet-iperf.json", - "type": "file" + "description": "iperf3 output", + "filepath": "/tmp/station/ethernet-iperf3.json", + "mimetype": "application/json" } ) # check if BW is in the expected range if self.__bwreal < float(self.__bwexpected): - self.__resultlist.append( - { - "desc": "Test result", - "data": "FAILED: speed is lower than spected. Speed(Mbits/s): " + str(self.__bwreal), - "type": "string" - } - ) self.fail("failed: speed is lower than spected. Speed(Mbits/s): " + str(self.__bwreal)) else: - self.__resultlist.append( - { - "desc": "Test result", - "data": "FAILED: could not complete iperf command.", - "type": "string" - } - ) self.fail("failed: could not complete iperf command.") - # Test successful - self.__resultlist.append( - { - "desc": "Test result", - "data": "OK", - "type": "string" - } - ) - def getresults(self): - return self.__resultlist + + def gettextresult(self): + return "" diff --git a/test-cli/test/tests/qi2c.py b/test-cli/test/tests/qi2c.py deleted file mode 100644 index 3afedfa..0000000 --- a/test-cli/test/tests/qi2c.py +++ /dev/null @@ -1,67 +0,0 @@ -from test.helpers.syscmd import SysCommand -import unittest - - -class Qi2c(unittest.TestCase): - params = None - __resultlist = None # resultlist is a python list of python dictionaries - - def __init__(self, testname, testfunc, varlist): - self.params = varlist - super(Qi2c, self).__init__(testfunc) - if "busnum" in varlist: - self.__busnum = varlist["busnum"] - else: - raise Exception('busnum param inside Qi2c must be defined') - if "register" in varlist: - self.__register = varlist["register"].split("/") - else: - raise Exception('register param inside Qi2c must be defined') - self.__devices = [] - self._testMethodDoc = testname - self.__resultlist = [] - - def execute(self): - str_cmd = "i2cdetect -a -y -r {}".format(self.__busnum) - i2c_command = SysCommand("i2cdetect", str_cmd) - if i2c_command.execute() == 0: - self.__raw_out = i2c_command.getOutput() - if self.__raw_out == "": - return -1 - lines = self.__raw_out.decode('ascii').splitlines() - for i in range(len(lines)): - if lines[i].count('UU'): - if lines[i].find("UU"): - self.__devices.append( - "0x{}{}".format((i - 1), hex(int((lines[i].find("UU") - 4) / 3)).split('x')[-1])) - for i in range(len(self.__register)): - if not (self.__register[i] in self.__devices): - self.__resultlist.append( - { - "desc": "Test result", - "data": "FAILED: device {} not found in bus i2c-{}".format(self.__register[i], self.__busnum), - "type": "string" - } - ) - self.fail("failed: device {} not found in bus i2c-{}".format(self.__register[i], self.__busnum)) - else: - self.__resultlist.append( - { - "desc": "Test result", - "data": "FAILED: could not complete i2cdedtect command", - "type": "string" - } - ) - self.fail("failed: could not complete i2cdedtect command.") - - # Test successful - self.__resultlist.append( - { - "desc": "Test result", - "data": "OK", - "type": "string" - } - ) - - def getresults(self): - return self.__resultlist diff --git a/test-cli/test/tests/qmmcflash.py b/test-cli/test/tests/qmmcflash.py new file mode 100644 index 0000000..f10757e --- /dev/null +++ b/test-cli/test/tests/qmmcflash.py @@ -0,0 +1,15 @@ +import unittest +import sh + +class Qmmcflash(unittest.TestCase): + params = None + + def __init__(self, testname, testfunc, varlist): + self.params = varlist + super(Qmmcflash, self).__init__(testfunc) + self._testMethodDoc = testname + # TODO + + + def execute(self): + # TODO \ No newline at end of file diff --git a/test-cli/test/tests/qnand.py b/test-cli/test/tests/qnand.py index d7c22b3..8c78e2b 100644 --- a/test-cli/test/tests/qnand.py +++ b/test-cli/test/tests/qnand.py @@ -22,34 +22,21 @@ class Qnand(unittest.TestCase): try: p = sh.nandtest("-m", self.__device) # save result - with open('/tmp/nand-nandtest.txt', 'w') as outfile: + with open('/tmp/station/nand-nandtest.txt', 'w') as outfile: n = outfile.write(p.stdout.decode('ascii')) + outfile.close() self.__resultlist.append( { - "desc": "nandtest output", - "data": "/tmp/nand-nandtest.txt", - "type": "file" + "description": "nandtest output", + "filepath": "/tmp/station/nand-nandtest.txt", + "mimetype": "text/plain" } ) - except sh.ErrorReturnCode as e: - self.__resultlist.append( - { - "desc": "Test result", - "data": "FAILED: could not complete nandtest command", - "type": "string" - } - ) self.fail("failed: could not complete nandtest command") - # Test successful - self.__resultlist.append( - { - "desc": "Test result", - "data": "OK", - "type": "string" - } - ) - def getresults(self): return self.__resultlist + + def gettextresult(self): + return "" diff --git a/test-cli/test/tests/qram.py b/test-cli/test/tests/qram.py index a46424f..21a01c8 100644 --- a/test-cli/test/tests/qram.py +++ b/test-cli/test/tests/qram.py @@ -26,25 +26,11 @@ class Qram(unittest.TestCase): def execute(self): try: p = sh.memtester(self.__memsize, "1", _out="/dev/null") - except sh.ErrorReturnCode as e: - self.__resultlist.append( - { - "desc": "Test result", - "data": "FAILED: could not complete memtester command", - "type": "string" - } - ) self.fail("failed: could not complete memtester command") - # Test successful - self.__resultlist.append( - { - "desc": "Test result", - "data": "OK", - "type": "string" - } - ) - def getresults(self): return self.__resultlist + + def gettextresult(self): + return "" diff --git a/test-cli/test/tests/qrtc.py b/test-cli/test/tests/qrtc.py index 6d4ecf6..df493d2 100644 --- a/test-cli/test/tests/qrtc.py +++ b/test-cli/test/tests/qrtc.py @@ -33,41 +33,14 @@ class Qrtc(unittest.TestCase): p.stdout.decode('ascii')) # check if the seconds of both times are different if time1 == time2: - self.__resultlist.append( - { - "desc": "Test result", - "data": "FAILED: RTC is not running", - "type": "string" - } - ) self.fail("failed: RTC is not running") else: - self.__resultlist.append( - { - "desc": "Test result", - "data": "FAILED: couldn't execute hwclock command for the second time", - "type": "string" - } - ) self.fail("failed: couldn't execute hwclock command for the second time") else: - self.__resultlist.append( - { - "desc": "Test result", - "data": "FAILED: couldn't execute hwclock command", - "type": "string" - } - ) self.fail("failed: couldn't execute hwclock command") - # Test successful - self.__resultlist.append( - { - "desc": "Test result", - "data": "OK", - "type": "string" - } - ) - def getresults(self): return self.__resultlist + + def gettextresult(self): + return "" diff --git a/test-cli/test/tests/qserial.py b/test-cli/test/tests/qserial.py index faca505..402e33f 100644 --- a/test-cli/test/tests/qserial.py +++ b/test-cli/test/tests/qserial.py @@ -42,34 +42,14 @@ class Qserial(unittest.TestCase): self.__serial.write(test_uuid) time.sleep(0.05) # there might be a small delay if self.__serial.inWaiting() == 0: - self.__resultlist.append( - { - "desc": "Test result", - "data": "FAILED: port {} wait timeout exceded".format(self.__port), - "type": "string" - } - ) self.fail("failed: port {} wait timeout exceded".format(self.__port)) else: # check if what it was sent is equal to what has been received if self.__serial.readline() != test_uuid: - self.__resultlist.append( - { - "desc": "Test result", - "data": "FAILED: port {} write/read mismatch".format(self.__port), - "type": "string" - } - ) self.fail("failed: port {} write/read mismatch".format(self.__port)) - # Test successful - self.__resultlist.append( - { - "desc": "Test result", - "data": "OK", - "type": "string" - } - ) - def getresults(self): return self.__resultlist + + def gettextresult(self): + return "" diff --git a/test-cli/test/tests/qusb.py b/test-cli/test/tests/qusb.py index 32d99ef..9b0cad3 100644 --- a/test-cli/test/tests/qusb.py +++ b/test-cli/test/tests/qusb.py @@ -22,13 +22,6 @@ class Qusb(unittest.TestCase): if dev_obj.getMassStorage(): device = dev_obj.getMassStorage()['disk'] + "1" else: - self.__resultlist.append( - { - "desc": "Test result", - "data": "FAILED: No USB memory found", - "type": "string" - } - ) self.fail("failed: No USB memory found.") # create a new folder where the pendrive is going to be mounted @@ -60,43 +53,16 @@ class Qusb(unittest.TestCase): sh.umount("/mnt/pendrive") # check result if q is None: - self.__resultlist.append( - { - "desc": "Test result", - "data": "FAILED: Wrong md5 result", - "type": "string" - } - ) self.fail("failed: Wrong md5 result.") else: # umount sh.umount("/mnt/pendrive") - self.__resultlist.append( - { - "desc": "Test result", - "data": "FAILED: Unable to copy files to the USB memory device", - "type": "string" - } - ) self.fail("failed: Unable to copy files to the USB memory device.") else: - self.__resultlist.append( - { - "desc": "Test result", - "data": "FAILED: Unable to mount the USB memory device", - "type": "string" - } - ) self.fail("failed: Unable to mount the USB memory device.") - # Test successful - self.__resultlist.append( - { - "desc": "Test result", - "data": "OK", - "type": "string" - } - ) - def getresults(self): return self.__resultlist + + def gettextresult(self): + return "" diff --git a/test-cli/test/tests/qwifi.py b/test-cli/test/tests/qwifi.py index 6f972d3..eb1f0bf 100644 --- a/test-cli/test/tests/qwifi.py +++ b/test-cli/test/tests/qwifi.py @@ -63,80 +63,33 @@ class Qwifi(unittest.TestCase): data = json.loads(p.stdout.decode('ascii')) self.__bwreal = float(data['end']['sum_received']['bits_per_second']) / 1024 / 1024 # save result file - with open('/tmp/wifi-iperf.json', 'w') as outfile: + with open('/tmp/station/wifi-iperf3.json', 'w') as outfile: json.dump(data, outfile, indent=4) + outfile.close() self.__resultlist.append( { - "desc": "iperf3 output", - "data": "/tmp/wifi-iperf.json", - "type": "file" + "description": "iperf3 output", + "filepath": "/tmp/station/wifi-iperf3.json", + "mimetype": "application/json" } ) # check if BW is in the expected range if self.__bwreal < float(self.__bwexpected): - self.__resultlist.append( - { - "desc": "Test result", - "data": "FAILED: speed is lower than expected. Speed(Mbits/s): " + str(self.__bwreal), - "type": "string" - } - ) self.fail("failed: speed is lower than expected. Speed(Mbits/s): " + str(self.__bwreal)) else: - self.__resultlist.append( - { - "desc": "Test result", - "data": "FAILED: could not complete iperf3 command", - "type": "string" - } - ) self.fail("failed: could not complete iperf3 command") else: - self.__resultlist.append( - { - "desc": "Test result", - "data": "FAILED: wlan0 interface doesn't have any ip address", - "type": "string" - } - ) self.fail("failed: wlan0 interface doesn't have any ip address.") else: - self.__resultlist.append( - { - "desc": "Test result", - "data": "FAILED: could not complete ifconfig command", - "type": "string" - } - ) self.fail("failed: could not complete ifconfig command.") else: - self.__resultlist.append( - { - "desc": "Test result", - "data": "FAILED: wifi module is not connected to the router", - "type": "string" - } - ) self.fail("failed: wifi module is not connected to the router.") else: - self.__resultlist.append( - { - "desc": "Test result", - "data": "FAILED: could not execute iw command", - "type": "string" - } - ) self.fail("failed: could not execute iw command") - # Test successful - self.__resultlist.append( - { - "desc": "Test result", - "data": "OK", - "type": "string" - } - ) - def getresults(self): return self.__resultlist + + def gettextresult(self): + return "" -- cgit v1.1 From b58a64c6993ab60f18a1a0ca8c90f167c7e6656b Mon Sep 17 00:00:00 2001 From: Hector Fernandez Date: Thu, 2 Jul 2020 14:45:48 +0200 Subject: Added support for IGEP0020 and IGEP0030. Fixed problem in Audio test. --- test-cli/test/helpers/int_registers.py | 2 +- test-cli/test/tests/qaudio.py | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) (limited to 'test-cli/test') diff --git a/test-cli/test/helpers/int_registers.py b/test-cli/test/helpers/int_registers.py index 9de503b..d081853 100644 --- a/test-cli/test/helpers/int_registers.py +++ b/test-cli/test/helpers/int_registers.py @@ -32,7 +32,7 @@ def get_die_id(modelid): elif modelid.find("IGEP0034") == 0 or modelid.find("SOPA0000") == 0: # registers: mac_id0_lo, mac_id0_hi, mac_id1_lo, mac_id1_hi registers = [0x44e10630, 0x44e10634, 0x44e10638, 0x44e1063C] - elif modelid.find("OMAP3") == 0: + elif modelid.find("OMAP3") == 0 or modelid.find("IGEP0020") == 0 or modelid.find("IGEP0030") == 0: registers = [0x4830A224, 0x4830A220, 0x4830A21C, 0x4830A218] elif modelid.find("OMAP5") == 0: registers = [0x4A002210, 0x4A00220C, 0x4A002208, 0x4A002200] diff --git a/test-cli/test/tests/qaudio.py b/test-cli/test/tests/qaudio.py index 5baffe4..ef0cf53 100644 --- a/test-cli/test/tests/qaudio.py +++ b/test-cli/test/tests/qaudio.py @@ -2,6 +2,7 @@ import unittest import sh import wave import contextlib +import os def calc_audio_duration(fname): @@ -25,10 +26,11 @@ class Qaudio(unittest.TestCase): self.__resultlist = [] def execute(self): + test_abspath = os.path.dirname(os.path.abspath(__file__)) + "/../" # analize audio file - recordtime = calc_audio_duration("test/files/dtmf-13579.wav") + 0.15 + recordtime = calc_audio_duration(os.path.join(test_abspath, "files/dtmf-13579.wav")) + 0.15 # play and record - p1 = sh.aplay("test/files/dtmf-13579.wav", _bg=True) + p1 = sh.aplay(os.path.join(test_abspath, "files/dtmf-13579.wav"), _bg=True) p2 = sh.arecord("-r", 8000, "-d", recordtime, "/tmp/station/recorded.wav", _bg=True) p1.wait() p2.wait() -- cgit v1.1 From 5dcd213c28451ac210703dc5bf9bf538671a0682 Mon Sep 17 00:00:00 2001 From: Hector Fernandez Date: Fri, 3 Jul 2020 13:55:45 +0200 Subject: Created new USB LOOP test. Moved all the test files to /var/lib/hwtest-files/ folder. --- test-cli/test/files/dtmf-13579.wav | Bin 17722 -> 0 bytes test-cli/test/files/usbtest/usbdatatest.bin | Bin 33554431 -> 0 bytes test-cli/test/files/usbtest/usbdatatest.md5 | 1 - test-cli/test/tests/qaudio.py | 6 +-- test-cli/test/tests/qusb.py | 64 +++++++++++++----------- test-cli/test/tests/qusbdual.py | 74 ++++++++++++++++++++++++++++ 6 files changed, 112 insertions(+), 33 deletions(-) delete mode 100644 test-cli/test/files/dtmf-13579.wav delete mode 100644 test-cli/test/files/usbtest/usbdatatest.bin delete mode 100644 test-cli/test/files/usbtest/usbdatatest.md5 create mode 100644 test-cli/test/tests/qusbdual.py (limited to 'test-cli/test') diff --git a/test-cli/test/files/dtmf-13579.wav b/test-cli/test/files/dtmf-13579.wav deleted file mode 100644 index c5b416a..0000000 Binary files a/test-cli/test/files/dtmf-13579.wav and /dev/null differ diff --git a/test-cli/test/files/usbtest/usbdatatest.bin b/test-cli/test/files/usbtest/usbdatatest.bin deleted file mode 100644 index 423eec3..0000000 Binary files a/test-cli/test/files/usbtest/usbdatatest.bin and /dev/null differ diff --git a/test-cli/test/files/usbtest/usbdatatest.md5 b/test-cli/test/files/usbtest/usbdatatest.md5 deleted file mode 100644 index 4358fb7..0000000 --- a/test-cli/test/files/usbtest/usbdatatest.md5 +++ /dev/null @@ -1 +0,0 @@ -6ef9717ac968b592803d0026f662a85e usbdatatest.bin diff --git a/test-cli/test/tests/qaudio.py b/test-cli/test/tests/qaudio.py index ef0cf53..acad4a9 100644 --- a/test-cli/test/tests/qaudio.py +++ b/test-cli/test/tests/qaudio.py @@ -2,7 +2,6 @@ import unittest import sh import wave import contextlib -import os def calc_audio_duration(fname): @@ -26,11 +25,10 @@ class Qaudio(unittest.TestCase): self.__resultlist = [] def execute(self): - test_abspath = os.path.dirname(os.path.abspath(__file__)) + "/../" # analize audio file - recordtime = calc_audio_duration(os.path.join(test_abspath, "files/dtmf-13579.wav")) + 0.15 + recordtime = calc_audio_duration("/var/lib/hwtest-files/dtmf-13579.wav") + 0.15 # play and record - p1 = sh.aplay(os.path.join(test_abspath, "files/dtmf-13579.wav"), _bg=True) + p1 = sh.aplay("/var/lib/hwtest-files/dtmf-13579.wav", _bg=True) p2 = sh.arecord("-r", 8000, "-d", recordtime, "/tmp/station/recorded.wav", _bg=True) p1.wait() p2.wait() diff --git a/test-cli/test/tests/qusb.py b/test-cli/test/tests/qusb.py index 9b0cad3..df1248d 100644 --- a/test-cli/test/tests/qusb.py +++ b/test-cli/test/tests/qusb.py @@ -1,9 +1,6 @@ import sh import unittest -import re -import os from test.helpers.usb import USBDevices -from test.helpers.changedir import changedir class Qusb(unittest.TestCase): @@ -14,6 +11,10 @@ class Qusb(unittest.TestCase): self.params = varlist super(Qusb, self).__init__(testfunc) self._testMethodDoc = testname + if "repetitions" in varlist: + self.__repetitions = varlist["repetitions"] + else: + raise Exception('repetitions param inside Qusb must be defined') self.__resultlist = [] def execute(self): @@ -23,43 +24,50 @@ class Qusb(unittest.TestCase): device = dev_obj.getMassStorage()['disk'] + "1" else: self.fail("failed: No USB memory found.") - - # create a new folder where the pendrive is going to be mounted - sh.mkdir("-p", "/mnt/pendrive") # check if the device is mounted, and umount it try: p = sh.findmnt("-n", device) if p.exit_code == 0: sh.umount(device) - except sh.ErrorReturnCode_1: + except sh.ErrorReturnCode as e: # error = 1 means "no found" pass # mount the device + sh.mkdir("-p", "/mnt/pendrive") p = sh.mount(device, "/mnt/pendrive") - if p.exit_code == 0: + if p.exit_code != 0: + self.fail("failed: Unable to mount the USB memory device.") + # execute test + for i in range(self.__repetitions): # copy files - test_abspath = os.path.dirname(os.path.abspath(__file__)) + "/../" - p = sh.cp(os.path.join(test_abspath, "files/usbtest/usbdatatest.bin"), - os.path.join(test_abspath, "files/usbtest/usbdatatest.md5"), - "/mnt/pendrive") - if p.exit_code == 0: - # check - with changedir("/mnt/pendrive/"): - p = sh.md5sum("-c", "usbdatatest.md5") - q = re.search("OK", p.stdout.decode('ascii')) - # delete files - sh.rm("-f", "/mnt/pendrive/usbdatatest.bin", "/mnt/pendrive/usbdatatest.md5") - # umount - sh.umount("/mnt/pendrive") - # check result - if q is None: - self.fail("failed: Wrong md5 result.") - else: - # umount + try: + p = sh.cp("/var/lib/hwtest-files/usbdatatest.bin", + "/var/lib/hwtest-files/usbdatatest.bin.md5", + "/mnt/pendrive") + except sh.ErrorReturnCode as e: sh.umount("/mnt/pendrive") + sh.rmdir("/mnt/pendrive") self.fail("failed: Unable to copy files to the USB memory device.") - else: - self.fail("failed: Unable to mount the USB memory device.") + # check MD5 + try: + p = sh.md5sum("/mnt/pendrive/usbdatatest.bin") + except sh.ErrorReturnCode as e: + sh.umount("/mnt/pendrive") + sh.rmdir("/mnt/pendrive") + self.fail("failed: Unable to calculate MD5 of the copied file.") + newmd5 = p.stdout.decode().split(" ")[0] + with open('/mnt/pendrive/usbdatatest.bin.md5', 'r') as outfile: + oldmd5 = outfile.read() + outfile.close() + if newmd5 != oldmd5: + sh.umount("/mnt/pendrive") + sh.rmdir("/mnt/pendrive") + self.fail("failed: MD5 check failed.") + # delete copied files + sh.rm("-f", "/mnt/pendrive/usbdatatest.bin", "/mnt/pendrive/usbdatatest.bin.md5") + # Finish + sh.umount("/mnt/pendrive") + sh.rmdir("/mnt/pendrive") def getresults(self): return self.__resultlist diff --git a/test-cli/test/tests/qusbdual.py b/test-cli/test/tests/qusbdual.py new file mode 100644 index 0000000..bb295b8 --- /dev/null +++ b/test-cli/test/tests/qusbdual.py @@ -0,0 +1,74 @@ +import sh +import unittest +import os.path + + +class Qusbdual(unittest.TestCase): + params = None + __resultlist = None # resultlist is a python list of python dictionaries + + def __init__(self, testname, testfunc, varlist): + self.params = varlist + super(Qusbdual, self).__init__(testfunc) + self._testMethodDoc = testname + if "repetitions" in varlist: + self.__repetitions = varlist["repetitions"] + else: + raise Exception('repetitions param inside Qusbdual must be defined') + self.__resultlist = [] + + def execute(self): + # check if file-as-filesystem exists + if not os.path.isfile('/var/lib/hwtest-files/mass-otg-test.img'): + self.fail("failed: Unable to find file-as-filesystem image.") + # generate mass storage gadget + p = sh.modprobe("g_mass_storage", "file=/var/lib/hwtest-files/mass-otg-test.img") + if p.exit_code != 0: + self.fail("failed: Unable to create a mass storage gadget.") + # find the mass storage device + try: + p = sh.grep(sh.lsblk("-So", "NAME,VENDOR"), "Linux") + except sh.ErrorReturnCode as e: + self.fail("failed: could not find any mass storage gadget") + device = p.stdout.decode().split(" ")[0] + # mount the mass storage gadget + sh.mkdir("-p", "/tmp/station/hdd_gadget") + p = sh.mount("-o", "ro", "/dev/" + device, "/tmp/station/hdd_gadget") + if p.exit_code != 0: + self.fail("failed: Unable to mount the mass storage gadget.") + # execute test + for i in range(self.__repetitions): + # copy files + try: + p = sh.cp("/tmp/station/hdd_gadget/usb-test.bin", "/tmp/station/hdd_gadget/usb-test.bin.md5", + "/tmp/stationnfs") + except sh.ErrorReturnCode as e: + sh.umount("/tmp/station/hdd_gadget") + sh.rmdir("/tmp/station/hdd_gadget") + self.fail("failed: Unable to copy files through USB.") + # Check md5 + try: + p = sh.md5sum("/tmp/stationnfs/usb-test.bin") + except sh.ErrorReturnCode as e: + sh.umount("/tmp/station/hdd_gadget") + sh.rmdir("/tmp/station/hdd_gadget") + self.fail("failed: Unable to calculate MD5 of the copied file.") + newmd5 = p.stdout.decode().split(" ")[0] + with open('/tmp/station/hdd_gadget/usb-test.bin.md5', 'r') as outfile: + oldmd5 = outfile.read() + outfile.close() + if newmd5 != oldmd5: + sh.umount("/tmp/station/hdd_gadget") + sh.rmdir("/tmp/station/hdd_gadget") + self.fail("failed: MD5 check failed.") + # delete copied files + sh.rm("-f", "/tmp/stationnfs/usb-test.bin", "/tmp/stationnfs/usb-test.bin.md5") + # Finish + sh.umount("/tmp/station/hdd_gadget") + sh.rmdir("/tmp/station/hdd_gadget") + + def getresults(self): + return self.__resultlist + + def gettextresult(self): + return "" -- cgit v1.1 From 0e8e3ecd4b9be71c41008b95950d089819622dff Mon Sep 17 00:00:00 2001 From: Hector Fernandez Date: Mon, 6 Jul 2020 14:08:27 +0200 Subject: Corrected some errors in USB and USBDUAL tests. --- test-cli/test/helpers/qrreader.py | 40 +++++++++++++++---------------- test-cli/test/tests/qdmesg.py | 3 +-- test-cli/test/tests/qusb.py | 50 ++++++++++++++++++++++++++------------- test-cli/test/tests/qusbdual.py | 7 +++++- 4 files changed, 60 insertions(+), 40 deletions(-) (limited to 'test-cli/test') diff --git a/test-cli/test/helpers/qrreader.py b/test-cli/test/helpers/qrreader.py index 908c9db..744db54 100644 --- a/test-cli/test/helpers/qrreader.py +++ b/test-cli/test/helpers/qrreader.py @@ -13,18 +13,17 @@ qrdevice_list = [ "SM SM-2D PRODUCT HID KBW" ] - -qrkey_list = { 'KEY_0':'0', - 'KEY_1':'1', - 'KEY_2':'2', - 'KEY_3':'3', - 'KEY_4':'4', - 'KEY_5':'5', - 'KEY_6':'6', - 'KEY_7':'7', - 'KEY_8':'8', - 'KEY_9':'9' - } +qrkey_list = {'KEY_0': '0', + 'KEY_1': '1', + 'KEY_2': '2', + 'KEY_3': '3', + 'KEY_4': '4', + 'KEY_5': '5', + 'KEY_6': '6', + 'KEY_7': '7', + 'KEY_8': '8', + 'KEY_9': '9' + } class QRReader: @@ -41,13 +40,13 @@ class QRReader: for device in devices: if device.name in qrdevice_list: self.__myReader['NAME'] = device.name - #print(self.__myReader['NAME']) + # print(self.__myReader['NAME']) self.__myReader['PATH'] = device.path - #print(self.__myReader['PATH']) + # print(self.__myReader['PATH']) self.__myReader['PHYS'] = device.phys - #print(self.__myReader['PHYS']) + # print(self.__myReader['PHYS']) - def IsQR (self): + def IsQR(self): return 'NAME' in self.__myReader def getQRNumber(self): @@ -84,7 +83,7 @@ class QRReader: return True return False - def wait_event (self, timeout): + def wait_event(self, timeout): selector.register(self.__dev, selectors.EVENT_READ) while True: events = selector.select(timeout); @@ -114,8 +113,7 @@ class QRReader: return r return False - -#qr = QRReader() -#if qr.openQR(): +# qr = QRReader() +# if qr.openQR(): # print(qr.readQRasync(2)) -#qr.closeQR() +# qr.closeQR() diff --git a/test-cli/test/tests/qdmesg.py b/test-cli/test/tests/qdmesg.py index 45dd4eb..8117deb 100644 --- a/test-cli/test/tests/qdmesg.py +++ b/test-cli/test/tests/qdmesg.py @@ -2,6 +2,7 @@ import sh import os.path from os import path + class Qdmesg: params = None __resultlist = None # resultlist is a python list of python dictionaries @@ -17,11 +18,9 @@ class Qdmesg: self.pgObj.run_test(self.params["testidctl"], self.params["testid"]) # delete previous file if path.exists("/tmp/station/dmesg.txt"): - print("dmesg remove") os.remove("/tmp/station/dmesg.txt") # generate file p = sh.dmesg("--color=never", _out="/tmp/station/dmesg.txt") - print("Exit code: {}".format(p.exit_code)) if p.exit_code == 0: # save result # with open('/tmp/station/dmesg.txt', 'w') as outfile: diff --git a/test-cli/test/tests/qusb.py b/test-cli/test/tests/qusb.py index df1248d..b5d152e 100644 --- a/test-cli/test/tests/qusb.py +++ b/test-cli/test/tests/qusb.py @@ -1,6 +1,7 @@ import sh import unittest from test.helpers.usb import USBDevices +import os.path class Qusb(unittest.TestCase): @@ -33,41 +34,58 @@ class Qusb(unittest.TestCase): # error = 1 means "no found" pass # mount the device - sh.mkdir("-p", "/mnt/pendrive") - p = sh.mount(device, "/mnt/pendrive") + sh.mkdir("-p", "/tmp/station/pendrive") + p = sh.mount(device, "/tmp/station/pendrive") if p.exit_code != 0: self.fail("failed: Unable to mount the USB memory device.") # execute test - for i in range(self.__repetitions): + for i in range(int(self.__repetitions)): # copy files try: p = sh.cp("/var/lib/hwtest-files/usbdatatest.bin", "/var/lib/hwtest-files/usbdatatest.bin.md5", - "/mnt/pendrive") + "/tmp/station/pendrive") except sh.ErrorReturnCode as e: - sh.umount("/mnt/pendrive") - sh.rmdir("/mnt/pendrive") + try: + sh.umount("/tmp/station/pendrive") + except sh.ErrorReturnCode: + pass + sh.rmdir("/tmp/station/pendrive") self.fail("failed: Unable to copy files to the USB memory device.") + # check if the device is still mounted + if not os.path.ismount("/tmp/station/pendrive"): + sh.rm("/tmp/station/pendrive/*") + sh.rmdir("/tmp/station/pendrive") + self.fail("failed: USB device unmounted during/after copying files.") # check MD5 try: - p = sh.md5sum("/mnt/pendrive/usbdatatest.bin") + p = sh.md5sum("/tmp/station/pendrive/usbdatatest.bin") except sh.ErrorReturnCode as e: - sh.umount("/mnt/pendrive") - sh.rmdir("/mnt/pendrive") + try: + sh.umount("/tmp/station/pendrive") + except sh.ErrorReturnCode: + pass + sh.rmdir("/tmp/station/pendrive") self.fail("failed: Unable to calculate MD5 of the copied file.") newmd5 = p.stdout.decode().split(" ")[0] - with open('/mnt/pendrive/usbdatatest.bin.md5', 'r') as outfile: - oldmd5 = outfile.read() + with open('/tmp/station/pendrive/usbdatatest.bin.md5', 'r') as outfile: + oldmd5 = outfile.read().rstrip("\n") outfile.close() if newmd5 != oldmd5: - sh.umount("/mnt/pendrive") - sh.rmdir("/mnt/pendrive") + try: + sh.umount("/tmp/station/pendrive") + except sh.ErrorReturnCode: + pass + sh.rmdir("/tmp/station/pendrive") self.fail("failed: MD5 check failed.") # delete copied files - sh.rm("-f", "/mnt/pendrive/usbdatatest.bin", "/mnt/pendrive/usbdatatest.bin.md5") + sh.rm("-f", "/tmp/station/pendrive/usbdatatest.bin", "/tmp/station/pendrive/usbdatatest.bin.md5") # Finish - sh.umount("/mnt/pendrive") - sh.rmdir("/mnt/pendrive") + try: + sh.umount("/tmp/station/pendrive") + except sh.ErrorReturnCode: + pass + sh.rmdir("/tmp/station/pendrive") def getresults(self): return self.__resultlist diff --git a/test-cli/test/tests/qusbdual.py b/test-cli/test/tests/qusbdual.py index bb295b8..ad95b84 100644 --- a/test-cli/test/tests/qusbdual.py +++ b/test-cli/test/tests/qusbdual.py @@ -37,7 +37,7 @@ class Qusbdual(unittest.TestCase): if p.exit_code != 0: self.fail("failed: Unable to mount the mass storage gadget.") # execute test - for i in range(self.__repetitions): + for i in range(int(self.__repetitions)): # copy files try: p = sh.cp("/tmp/station/hdd_gadget/usb-test.bin", "/tmp/station/hdd_gadget/usb-test.bin.md5", @@ -46,6 +46,11 @@ class Qusbdual(unittest.TestCase): sh.umount("/tmp/station/hdd_gadget") sh.rmdir("/tmp/station/hdd_gadget") self.fail("failed: Unable to copy files through USB.") + # check if the device is still mounted + if not os.path.ismount("/tmp/station/hdd_gadget"): + sh.rm("/tmp/station/hdd_gadget/*") + sh.rmdir("/tmp/station/hdd_gadget") + self.fail("failed: USB device unmounted during/after copying files.") # Check md5 try: p = sh.md5sum("/tmp/stationnfs/usb-test.bin") -- cgit v1.1 From cd3c8dd78e3bcdd442967583e3814db3701871c0 Mon Sep 17 00:00:00 2001 From: Hector Fernandez Date: Mon, 6 Jul 2020 16:01:08 +0200 Subject: Solved minor errors with audio and usbloop tests. --- test-cli/test/tests/qaudio.py | 7 +++++-- test-cli/test/tests/qusbdual.py | 2 +- 2 files changed, 6 insertions(+), 3 deletions(-) (limited to 'test-cli/test') diff --git a/test-cli/test/tests/qaudio.py b/test-cli/test/tests/qaudio.py index acad4a9..f7ae33c 100644 --- a/test-cli/test/tests/qaudio.py +++ b/test-cli/test/tests/qaudio.py @@ -2,6 +2,7 @@ import unittest import sh import wave import contextlib +import time def calc_audio_duration(fname): @@ -27,6 +28,8 @@ class Qaudio(unittest.TestCase): def execute(self): # analize audio file recordtime = calc_audio_duration("/var/lib/hwtest-files/dtmf-13579.wav") + 0.15 + # wait time before playing + time.sleep(1) # play and record p1 = sh.aplay("/var/lib/hwtest-files/dtmf-13579.wav", _bg=True) p2 = sh.arecord("-r", 8000, "-d", recordtime, "/tmp/station/recorded.wav", _bg=True) @@ -42,8 +45,8 @@ class Qaudio(unittest.TestCase): self.__dtmf_secuence_result.append(li.split(" ")[1]) # compare original and processed dtmf sequence if len(self.__dtmf_secuence) == len(self.__dtmf_secuence_result): - for i in range(len(self.__dtmf_secuence)): - if self.__dtmf_secuence[i] != self.__dtmf_secuence_result[i]: + for a, b in zip(self.__dtmf_secuence, self.__dtmf_secuence_result): + if a != b: self.fail("failed: sent and received DTMF sequence don't match.") else: self.fail("failed: received DTMF sequence is shorter than expected.") diff --git a/test-cli/test/tests/qusbdual.py b/test-cli/test/tests/qusbdual.py index ad95b84..842d514 100644 --- a/test-cli/test/tests/qusbdual.py +++ b/test-cli/test/tests/qusbdual.py @@ -60,7 +60,7 @@ class Qusbdual(unittest.TestCase): self.fail("failed: Unable to calculate MD5 of the copied file.") newmd5 = p.stdout.decode().split(" ")[0] with open('/tmp/station/hdd_gadget/usb-test.bin.md5', 'r') as outfile: - oldmd5 = outfile.read() + oldmd5 = outfile.read().rstrip("\n") outfile.close() if newmd5 != oldmd5: sh.umount("/tmp/station/hdd_gadget") -- cgit v1.1 From 1d51a80b57cc8c80c78d67c85290503997060e9e Mon Sep 17 00:00:00 2001 From: Hector Fernandez Date: Mon, 6 Jul 2020 17:22:17 +0200 Subject: Modified paths of ram and nfs temporary folders. --- test-cli/test/tests/qamper.py | 4 ++-- test-cli/test/tests/qaudio.py | 10 +++++----- test-cli/test/tests/qdmesg.py | 13 ++++--------- test-cli/test/tests/qethernet.py | 4 ++-- test-cli/test/tests/qnand.py | 4 ++-- test-cli/test/tests/qusb.py | 34 +++++++++++++++++----------------- test-cli/test/tests/qusbdual.py | 34 +++++++++++++++++----------------- test-cli/test/tests/qwifi.py | 6 +++--- 8 files changed, 52 insertions(+), 57 deletions(-) (limited to 'test-cli/test') diff --git a/test-cli/test/tests/qamper.py b/test-cli/test/tests/qamper.py index b4d57e3..58054c9 100644 --- a/test-cli/test/tests/qamper.py +++ b/test-cli/test/tests/qamper.py @@ -35,13 +35,13 @@ class Qamper(unittest.TestCase): # get current value (in Amperes) self.current = amp.getCurrent() # save result in a file - with open('/tmp/station/amper.txt', 'w') as outfile: + with open('/mnt/station_ramdisk/amper.txt', 'w') as outfile: n = outfile.write("Current: {} A".format(self.current)) outfile.close() self.__resultlist.append( { "description": "Amperimeter values", - "filepath": "/tmp/station/amper.txt", + "filepath": "/mnt/station_ramdisk/amper.txt", "mimetype": "text/plain" } ) diff --git a/test-cli/test/tests/qaudio.py b/test-cli/test/tests/qaudio.py index f7ae33c..bfbb051 100644 --- a/test-cli/test/tests/qaudio.py +++ b/test-cli/test/tests/qaudio.py @@ -2,7 +2,6 @@ import unittest import sh import wave import contextlib -import time def calc_audio_duration(fname): @@ -28,15 +27,15 @@ class Qaudio(unittest.TestCase): def execute(self): # analize audio file recordtime = calc_audio_duration("/var/lib/hwtest-files/dtmf-13579.wav") + 0.15 - # wait time before playing - time.sleep(1) + # previous play to estabilise audio lines + sh.aplay("/var/lib/hwtest-files/dtmf-13579.wav") # play and record p1 = sh.aplay("/var/lib/hwtest-files/dtmf-13579.wav", _bg=True) - p2 = sh.arecord("-r", 8000, "-d", recordtime, "/tmp/station/recorded.wav", _bg=True) + p2 = sh.arecord("-r", 8000, "-d", recordtime, "/mnt/station_ramdisk/recorded.wav", _bg=True) p1.wait() p2.wait() if p1.exit_code == 0 and p2.exit_code == 0: - p = sh.multimon("-t", "wav", "-a", "DTMF", "/tmp/station/recorded.wav", "-q") + p = sh.multimon("-t", "wav", "-a", "DTMF", "/mnt/station_ramdisk/recorded.wav", "-q") if p.exit_code == 0: lines = p.stdout.decode('ascii').splitlines() self.__dtmf_secuence_result = [] @@ -49,6 +48,7 @@ class Qaudio(unittest.TestCase): if a != b: self.fail("failed: sent and received DTMF sequence don't match.") else: + print(self.__dtmf_secuence_result) self.fail("failed: received DTMF sequence is shorter than expected.") else: self.fail("failed: unable to use multimon command.") diff --git a/test-cli/test/tests/qdmesg.py b/test-cli/test/tests/qdmesg.py index 8117deb..b35f1ff 100644 --- a/test-cli/test/tests/qdmesg.py +++ b/test-cli/test/tests/qdmesg.py @@ -17,19 +17,14 @@ class Qdmesg: print("running dmesg test") self.pgObj.run_test(self.params["testidctl"], self.params["testid"]) # delete previous file - if path.exists("/tmp/station/dmesg.txt"): - os.remove("/tmp/station/dmesg.txt") + if path.exists("/mnt/station_ramdisk/dmesg.txt"): + os.remove("/mnt/station_ramdisk/dmesg.txt") # generate file - p = sh.dmesg("--color=never", _out="/tmp/station/dmesg.txt") + p = sh.dmesg("--color=never", _out="/mnt/station_ramdisk/dmesg.txt") if p.exit_code == 0: - # save result - # with open('/tmp/station/dmesg.txt', 'w') as outfile: - # n = outfile.write(p.stdout.decode('ascii')) - # outfile.close() - # save dmesg result in DB self.pgObj.upload_result_file(self.params["testidctl"], self.params["testid"], "dmesg output", - "/tmp/station/dmesg.txt", "text/plain") + "/mnt/station_ramdisk/dmesg.txt", "text/plain") self.pgObj.finish_test(self.params["testidctl"], self.params["testid"], "TEST_COMPLETE", "") print("success dmesg test") else: diff --git a/test-cli/test/tests/qethernet.py b/test-cli/test/tests/qethernet.py index 3b2f197..d38de34 100644 --- a/test-cli/test/tests/qethernet.py +++ b/test-cli/test/tests/qethernet.py @@ -52,13 +52,13 @@ class Qethernet(unittest.TestCase): data = json.loads(p.stdout.decode('ascii')) self.__bwreal = float(data['end']['sum_received']['bits_per_second'])/1024/1024 # save result file - with open('/tmp/station/ethernet-iperf3.json', 'w') as outfile: + with open('/mnt/station_ramdisk/ethernet-iperf3.json', 'w') as outfile: json.dump(data, outfile, indent=4) outfile.close() self.__resultlist.append( { "description": "iperf3 output", - "filepath": "/tmp/station/ethernet-iperf3.json", + "filepath": "/mnt/station_ramdisk/ethernet-iperf3.json", "mimetype": "application/json" } ) diff --git a/test-cli/test/tests/qnand.py b/test-cli/test/tests/qnand.py index 8c78e2b..988ab60 100644 --- a/test-cli/test/tests/qnand.py +++ b/test-cli/test/tests/qnand.py @@ -22,13 +22,13 @@ class Qnand(unittest.TestCase): try: p = sh.nandtest("-m", self.__device) # save result - with open('/tmp/station/nand-nandtest.txt', 'w') as outfile: + with open('/mnt/station_ramdisk/nand-nandtest.txt', 'w') as outfile: n = outfile.write(p.stdout.decode('ascii')) outfile.close() self.__resultlist.append( { "description": "nandtest output", - "filepath": "/tmp/station/nand-nandtest.txt", + "filepath": "/mnt/station_ramdisk/nand-nandtest.txt", "mimetype": "text/plain" } ) diff --git a/test-cli/test/tests/qusb.py b/test-cli/test/tests/qusb.py index b5d152e..6302012 100644 --- a/test-cli/test/tests/qusb.py +++ b/test-cli/test/tests/qusb.py @@ -34,8 +34,8 @@ class Qusb(unittest.TestCase): # error = 1 means "no found" pass # mount the device - sh.mkdir("-p", "/tmp/station/pendrive") - p = sh.mount(device, "/tmp/station/pendrive") + sh.mkdir("-p", "/mnt/station_ramdisk/pendrive") + p = sh.mount(device, "/mnt/station_ramdisk/pendrive") if p.exit_code != 0: self.fail("failed: Unable to mount the USB memory device.") # execute test @@ -44,48 +44,48 @@ class Qusb(unittest.TestCase): try: p = sh.cp("/var/lib/hwtest-files/usbdatatest.bin", "/var/lib/hwtest-files/usbdatatest.bin.md5", - "/tmp/station/pendrive") + "/mnt/station_ramdisk/pendrive") except sh.ErrorReturnCode as e: try: - sh.umount("/tmp/station/pendrive") + sh.umount("/mnt/station_ramdisk/pendrive") except sh.ErrorReturnCode: pass - sh.rmdir("/tmp/station/pendrive") + sh.rmdir("/mnt/station_ramdisk/pendrive") self.fail("failed: Unable to copy files to the USB memory device.") # check if the device is still mounted - if not os.path.ismount("/tmp/station/pendrive"): - sh.rm("/tmp/station/pendrive/*") - sh.rmdir("/tmp/station/pendrive") + if not os.path.ismount("/mnt/station_ramdisk/pendrive"): + sh.rm("/mnt/station_ramdisk/pendrive/*") + sh.rmdir("/mnt/station_ramdisk/pendrive") self.fail("failed: USB device unmounted during/after copying files.") # check MD5 try: - p = sh.md5sum("/tmp/station/pendrive/usbdatatest.bin") + p = sh.md5sum("/mnt/station_ramdisk/pendrive/usbdatatest.bin") except sh.ErrorReturnCode as e: try: - sh.umount("/tmp/station/pendrive") + sh.umount("/mnt/station_ramdisk/pendrive") except sh.ErrorReturnCode: pass - sh.rmdir("/tmp/station/pendrive") + sh.rmdir("/mnt/station_ramdisk/pendrive") self.fail("failed: Unable to calculate MD5 of the copied file.") newmd5 = p.stdout.decode().split(" ")[0] - with open('/tmp/station/pendrive/usbdatatest.bin.md5', 'r') as outfile: + with open('/mnt/station_ramdisk/pendrive/usbdatatest.bin.md5', 'r') as outfile: oldmd5 = outfile.read().rstrip("\n") outfile.close() if newmd5 != oldmd5: try: - sh.umount("/tmp/station/pendrive") + sh.umount("/mnt/station_ramdisk/pendrive") except sh.ErrorReturnCode: pass - sh.rmdir("/tmp/station/pendrive") + sh.rmdir("/mnt/station_ramdisk/pendrive") self.fail("failed: MD5 check failed.") # delete copied files - sh.rm("-f", "/tmp/station/pendrive/usbdatatest.bin", "/tmp/station/pendrive/usbdatatest.bin.md5") + sh.rm("-f", "/mnt/station_ramdisk/pendrive/usbdatatest.bin", "/mnt/station_ramdisk/pendrive/usbdatatest.bin.md5") # Finish try: - sh.umount("/tmp/station/pendrive") + sh.umount("/mnt/station_ramdisk/pendrive") except sh.ErrorReturnCode: pass - sh.rmdir("/tmp/station/pendrive") + sh.rmdir("/mnt/station_ramdisk/pendrive") def getresults(self): return self.__resultlist diff --git a/test-cli/test/tests/qusbdual.py b/test-cli/test/tests/qusbdual.py index 842d514..054d7f4 100644 --- a/test-cli/test/tests/qusbdual.py +++ b/test-cli/test/tests/qusbdual.py @@ -32,45 +32,45 @@ class Qusbdual(unittest.TestCase): self.fail("failed: could not find any mass storage gadget") device = p.stdout.decode().split(" ")[0] # mount the mass storage gadget - sh.mkdir("-p", "/tmp/station/hdd_gadget") - p = sh.mount("-o", "ro", "/dev/" + device, "/tmp/station/hdd_gadget") + sh.mkdir("-p", "/mnt/station_ramdisk/hdd_gadget") + p = sh.mount("-o", "ro", "/dev/" + device, "/mnt/station_ramdisk/hdd_gadget") if p.exit_code != 0: self.fail("failed: Unable to mount the mass storage gadget.") # execute test for i in range(int(self.__repetitions)): # copy files try: - p = sh.cp("/tmp/station/hdd_gadget/usb-test.bin", "/tmp/station/hdd_gadget/usb-test.bin.md5", + p = sh.cp("/mnt/station_ramdisk/hdd_gadget/usb-test.bin", "/mnt/station_ramdisk/hdd_gadget/usb-test.bin.md5", "/tmp/stationnfs") except sh.ErrorReturnCode as e: - sh.umount("/tmp/station/hdd_gadget") - sh.rmdir("/tmp/station/hdd_gadget") + sh.umount("/mnt/station_ramdisk/hdd_gadget") + sh.rmdir("/mnt/station_ramdisk/hdd_gadget") self.fail("failed: Unable to copy files through USB.") # check if the device is still mounted - if not os.path.ismount("/tmp/station/hdd_gadget"): - sh.rm("/tmp/station/hdd_gadget/*") - sh.rmdir("/tmp/station/hdd_gadget") + if not os.path.ismount("/mnt/station_ramdisk/hdd_gadget"): + sh.rm("/mnt/station_ramdisk/hdd_gadget/*") + sh.rmdir("/mnt/station_ramdisk/hdd_gadget") self.fail("failed: USB device unmounted during/after copying files.") # Check md5 try: - p = sh.md5sum("/tmp/stationnfs/usb-test.bin") + p = sh.md5sum("/mnt/station_nfsdisk/usb-test.bin") except sh.ErrorReturnCode as e: - sh.umount("/tmp/station/hdd_gadget") - sh.rmdir("/tmp/station/hdd_gadget") + sh.umount("/mnt/station_ramdisk/hdd_gadget") + sh.rmdir("/mnt/station_ramdisk/hdd_gadget") self.fail("failed: Unable to calculate MD5 of the copied file.") newmd5 = p.stdout.decode().split(" ")[0] - with open('/tmp/station/hdd_gadget/usb-test.bin.md5', 'r') as outfile: + with open('/mnt/station_ramdisk/hdd_gadget/usb-test.bin.md5', 'r') as outfile: oldmd5 = outfile.read().rstrip("\n") outfile.close() if newmd5 != oldmd5: - sh.umount("/tmp/station/hdd_gadget") - sh.rmdir("/tmp/station/hdd_gadget") + sh.umount("/mnt/station_ramdisk/hdd_gadget") + sh.rmdir("/mnt/station_ramdisk/hdd_gadget") self.fail("failed: MD5 check failed.") # delete copied files - sh.rm("-f", "/tmp/stationnfs/usb-test.bin", "/tmp/stationnfs/usb-test.bin.md5") + sh.rm("-f", "/mnt/station_nfsdisk/usb-test.bin", "/mnt/station_nfsdisk/usb-test.bin.md5") # Finish - sh.umount("/tmp/station/hdd_gadget") - sh.rmdir("/tmp/station/hdd_gadget") + sh.umount("/mnt/station_ramdisk/hdd_gadget") + sh.rmdir("/mnt/station_ramdisk/hdd_gadget") def getresults(self): return self.__resultlist diff --git a/test-cli/test/tests/qwifi.py b/test-cli/test/tests/qwifi.py index eb1f0bf..4522057 100644 --- a/test-cli/test/tests/qwifi.py +++ b/test-cli/test/tests/qwifi.py @@ -51,7 +51,7 @@ class Qwifi(unittest.TestCase): # execute iperf command against the server try: p = sh.iperf3("-c", self.__serverip, "-n", self.__numbytestx, "-f", "m", "-p", self.__port, - "-J", _timeout=20) + "-J", _timeout=30) except sh.TimeoutException: self.fail("failed: iperf timeout reached") @@ -63,13 +63,13 @@ class Qwifi(unittest.TestCase): data = json.loads(p.stdout.decode('ascii')) self.__bwreal = float(data['end']['sum_received']['bits_per_second']) / 1024 / 1024 # save result file - with open('/tmp/station/wifi-iperf3.json', 'w') as outfile: + with open('/mnt/station_ramdisk/wifi-iperf3.json', 'w') as outfile: json.dump(data, outfile, indent=4) outfile.close() self.__resultlist.append( { "description": "iperf3 output", - "filepath": "/tmp/station/wifi-iperf3.json", + "filepath": "/mnt/station_ramdisk/wifi-iperf3.json", "mimetype": "application/json" } ) -- cgit v1.1 From 47827e40f71696e04ad805296dedc44a03451db3 Mon Sep 17 00:00:00 2001 From: Hector Fernandez Date: Mon, 6 Jul 2020 17:51:09 +0200 Subject: In case iperf3 server is busy, clients wait and retry. --- test-cli/test/tests/qaudio.py | 1 - test-cli/test/tests/qethernet.py | 19 +++++++++++++------ test-cli/test/tests/qwifi.py | 19 +++++++++++++------ 3 files changed, 26 insertions(+), 13 deletions(-) (limited to 'test-cli/test') diff --git a/test-cli/test/tests/qaudio.py b/test-cli/test/tests/qaudio.py index bfbb051..364d8b2 100644 --- a/test-cli/test/tests/qaudio.py +++ b/test-cli/test/tests/qaudio.py @@ -48,7 +48,6 @@ class Qaudio(unittest.TestCase): if a != b: self.fail("failed: sent and received DTMF sequence don't match.") else: - print(self.__dtmf_secuence_result) self.fail("failed: received DTMF sequence is shorter than expected.") else: self.fail("failed: unable to use multimon command.") diff --git a/test-cli/test/tests/qethernet.py b/test-cli/test/tests/qethernet.py index d38de34..81acef1 100644 --- a/test-cli/test/tests/qethernet.py +++ b/test-cli/test/tests/qethernet.py @@ -1,6 +1,7 @@ import unittest import sh import json +import time class Qethernet(unittest.TestCase): @@ -11,6 +12,7 @@ class Qethernet(unittest.TestCase): params = None __bwreal = None __resultlist = None # resultlist is a python list of python dictionaries + timebetweenattempts = 5 # varlist content: serverip, bwexpected, port def __init__(self, testname, testfunc, varlist): @@ -37,12 +39,17 @@ class Qethernet(unittest.TestCase): self.__resultlist = [] def execute(self): - # execute iperf command against the server - try: - p = sh.iperf3("-c", self.__serverip, "-n", self.__numbytestx, "-f", "m", "-p", self.__port, "-J", - _timeout=20) - except sh.TimeoutException: - self.fail("failed: iperf timeout reached") + # execute iperf command against the server, but it implements attempts in case the server is busy + iperfdone = False + while not iperfdone: + try: + p = sh.iperf3("-c", self.__serverip, "-n", self.__numbytestx, "-f", "m", "-p", self.__port, "-J", + _timeout=20) + iperfdone = True + except sh.TimeoutException: + self.fail("failed: iperf timeout reached") + except sh.ErrorReturnCode: + time.sleep(self.timebetweenattempts) # check if it was executed succesfully if p.exit_code == 0: diff --git a/test-cli/test/tests/qwifi.py b/test-cli/test/tests/qwifi.py index 4522057..3dd9e38 100644 --- a/test-cli/test/tests/qwifi.py +++ b/test-cli/test/tests/qwifi.py @@ -2,6 +2,7 @@ import unittest import sh import re import json +import time class Qwifi(unittest.TestCase): @@ -12,6 +13,7 @@ class Qwifi(unittest.TestCase): params = None __bwreal = None __resultlist = None # resultlist is a python list of python dictionaries + timebetweenattempts = 5 # varlist content: serverip, bwexpected, port def __init__(self, testname, testfunc, varlist): @@ -48,12 +50,17 @@ class Qwifi(unittest.TestCase): 'inet addr:(?!127\.0{1,3}\.0{1,3}\.0{0,2}1$)((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)', p.stdout.decode('ascii')) if result: - # execute iperf command against the server - try: - p = sh.iperf3("-c", self.__serverip, "-n", self.__numbytestx, "-f", "m", "-p", self.__port, - "-J", _timeout=30) - except sh.TimeoutException: - self.fail("failed: iperf timeout reached") + # execute iperf command against the server, but it implements attempts in case the server is busy + iperfdone = False + while not iperfdone: + try: + p = sh.iperf3("-c", self.__serverip, "-n", self.__numbytestx, "-f", "m", "-p", self.__port, + "-J", _timeout=20) + iperfdone = True + except sh.TimeoutException: + self.fail("failed: iperf timeout reached") + except sh.ErrorReturnCode: + time.sleep(self.timebetweenattempts) # check if it was executed succesfully if p.exit_code == 0: -- cgit v1.1 From 43f688b414ea182cd9baf06ee83df072c3f563f5 Mon Sep 17 00:00:00 2001 From: Hector Fernandez Date: Tue, 7 Jul 2020 09:57:58 +0200 Subject: Added full support for USBLOOP test. Reboot board always if autotest is enabled. --- test-cli/test/tests/qusbdual.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) (limited to 'test-cli/test') diff --git a/test-cli/test/tests/qusbdual.py b/test-cli/test/tests/qusbdual.py index 054d7f4..fcbb9aa 100644 --- a/test-cli/test/tests/qusbdual.py +++ b/test-cli/test/tests/qusbdual.py @@ -1,6 +1,7 @@ import sh import unittest import os.path +import time class Qusbdual(unittest.TestCase): @@ -25,10 +26,12 @@ class Qusbdual(unittest.TestCase): p = sh.modprobe("g_mass_storage", "file=/var/lib/hwtest-files/mass-otg-test.img") if p.exit_code != 0: self.fail("failed: Unable to create a mass storage gadget.") + # wait to detect the new device + time.sleep(3) # find the mass storage device try: p = sh.grep(sh.lsblk("-So", "NAME,VENDOR"), "Linux") - except sh.ErrorReturnCode as e: + except sh.ErrorReturnCode: self.fail("failed: could not find any mass storage gadget") device = p.stdout.decode().split(" ")[0] # mount the mass storage gadget @@ -40,8 +43,9 @@ class Qusbdual(unittest.TestCase): for i in range(int(self.__repetitions)): # copy files try: - p = sh.cp("/mnt/station_ramdisk/hdd_gadget/usb-test.bin", "/mnt/station_ramdisk/hdd_gadget/usb-test.bin.md5", - "/tmp/stationnfs") + p = sh.cp("/mnt/station_ramdisk/hdd_gadget/usb-test.bin", + "/mnt/station_ramdisk/hdd_gadget/usb-test.bin.md5", + "/mnt/station_nfsdisk/") except sh.ErrorReturnCode as e: sh.umount("/mnt/station_ramdisk/hdd_gadget") sh.rmdir("/mnt/station_ramdisk/hdd_gadget") -- cgit v1.1 From 9f89f02e7d6e2a3208b0b85d2567ebffd2515e09 Mon Sep 17 00:00:00 2001 From: Hector Fernandez Date: Tue, 7 Jul 2020 14:09:59 +0200 Subject: New way to check preivous state before changing to a new one. Solved some problems with audio test. --- test-cli/test/enums/StationStates.py | 1 + test-cli/test/helpers/testsrv_db.py | 4 +++- test-cli/test/tests/qaudio.py | 5 ++++- 3 files changed, 8 insertions(+), 2 deletions(-) (limited to 'test-cli/test') diff --git a/test-cli/test/enums/StationStates.py b/test-cli/test/enums/StationStates.py index 9de5e15..040e6bc 100644 --- a/test-cli/test/enums/StationStates.py +++ b/test-cli/test/enums/StationStates.py @@ -17,4 +17,5 @@ class StationStates(Enum): EXTRATASKS_RUNNING = 100 WAITING_FOR_SCANNER = 50 FINISHED = 60 + STATION_REBOOT = 2001 diff --git a/test-cli/test/helpers/testsrv_db.py b/test-cli/test/helpers/testsrv_db.py index 7eeefb3..9579e7e 100644 --- a/test-cli/test/helpers/testsrv_db.py +++ b/test-cli/test/helpers/testsrv_db.py @@ -197,7 +197,9 @@ class TestSrv_Database(object): sql = "SELECT station.setmystate('{}', '{}', NULL)".format(newstate, station) # print('>>>' + sql) try: - self.__sqlObject.db_execute_query(sql) + res = self.__sqlObject.db_execute_query(sql) + # print(res) + return res[0][0] except Exception as err: r = find_between(str(err), '#', '#') # print(r) diff --git a/test-cli/test/tests/qaudio.py b/test-cli/test/tests/qaudio.py index 364d8b2..3d2113a 100644 --- a/test-cli/test/tests/qaudio.py +++ b/test-cli/test/tests/qaudio.py @@ -28,7 +28,10 @@ class Qaudio(unittest.TestCase): # analize audio file recordtime = calc_audio_duration("/var/lib/hwtest-files/dtmf-13579.wav") + 0.15 # previous play to estabilise audio lines - sh.aplay("/var/lib/hwtest-files/dtmf-13579.wav") + p1 = sh.aplay("/var/lib/hwtest-files/dtmf-13579.wav", _bg=True) + p2 = sh.arecord("-r", 8000, "-d", recordtime, "/mnt/station_ramdisk/recorded.wav", _bg=True) + p1.wait() + p2.wait() # play and record p1 = sh.aplay("/var/lib/hwtest-files/dtmf-13579.wav", _bg=True) p2 = sh.arecord("-r", 8000, "-d", recordtime, "/mnt/station_ramdisk/recorded.wav", _bg=True) -- cgit v1.1 From 907b96801230e04d02575a3732a73e452089637b Mon Sep 17 00:00:00 2001 From: Hector Fernandez Date: Tue, 7 Jul 2020 17:27:33 +0200 Subject: After USBLOOP test, g_mass_storage must be stopped so the board can be rebooted correctly. --- test-cli/test/tests/qusbdual.py | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'test-cli/test') diff --git a/test-cli/test/tests/qusbdual.py b/test-cli/test/tests/qusbdual.py index fcbb9aa..05b22c3 100644 --- a/test-cli/test/tests/qusbdual.py +++ b/test-cli/test/tests/qusbdual.py @@ -32,12 +32,14 @@ class Qusbdual(unittest.TestCase): try: p = sh.grep(sh.lsblk("-So", "NAME,VENDOR"), "Linux") except sh.ErrorReturnCode: + sh.modprobe("-r", "g_mass_storage") self.fail("failed: could not find any mass storage gadget") device = p.stdout.decode().split(" ")[0] # mount the mass storage gadget sh.mkdir("-p", "/mnt/station_ramdisk/hdd_gadget") p = sh.mount("-o", "ro", "/dev/" + device, "/mnt/station_ramdisk/hdd_gadget") if p.exit_code != 0: + sh.modprobe("-r", "g_mass_storage") self.fail("failed: Unable to mount the mass storage gadget.") # execute test for i in range(int(self.__repetitions)): @@ -49,11 +51,13 @@ class Qusbdual(unittest.TestCase): except sh.ErrorReturnCode as e: sh.umount("/mnt/station_ramdisk/hdd_gadget") sh.rmdir("/mnt/station_ramdisk/hdd_gadget") + sh.modprobe("-r", "g_mass_storage") self.fail("failed: Unable to copy files through USB.") # check if the device is still mounted if not os.path.ismount("/mnt/station_ramdisk/hdd_gadget"): sh.rm("/mnt/station_ramdisk/hdd_gadget/*") sh.rmdir("/mnt/station_ramdisk/hdd_gadget") + sh.modprobe("-r", "g_mass_storage") self.fail("failed: USB device unmounted during/after copying files.") # Check md5 try: @@ -61,6 +65,7 @@ class Qusbdual(unittest.TestCase): except sh.ErrorReturnCode as e: sh.umount("/mnt/station_ramdisk/hdd_gadget") sh.rmdir("/mnt/station_ramdisk/hdd_gadget") + sh.modprobe("-r", "g_mass_storage") self.fail("failed: Unable to calculate MD5 of the copied file.") newmd5 = p.stdout.decode().split(" ")[0] with open('/mnt/station_ramdisk/hdd_gadget/usb-test.bin.md5', 'r') as outfile: @@ -69,12 +74,14 @@ class Qusbdual(unittest.TestCase): if newmd5 != oldmd5: sh.umount("/mnt/station_ramdisk/hdd_gadget") sh.rmdir("/mnt/station_ramdisk/hdd_gadget") + sh.modprobe("-r", "g_mass_storage") self.fail("failed: MD5 check failed.") # delete copied files sh.rm("-f", "/mnt/station_nfsdisk/usb-test.bin", "/mnt/station_nfsdisk/usb-test.bin.md5") # Finish sh.umount("/mnt/station_ramdisk/hdd_gadget") sh.rmdir("/mnt/station_ramdisk/hdd_gadget") + sh.modprobe("-r", "g_mass_storage") def getresults(self): return self.__resultlist -- cgit v1.1 From d46bce422fd03cd57d1ba336361da17d6efb48db Mon Sep 17 00:00:00 2001 From: Manel Caro Date: Fri, 31 Jul 2020 02:07:37 +0200 Subject: TEST restructure --- test-cli/test/enums/StationStates.py | 1 + test-cli/test/helpers/camara.py | 124 ++++++++++++++++++++++++++++ test-cli/test/helpers/cmdline.py | 2 +- test-cli/test/helpers/gpio.py | 55 +++++++++++++ test-cli/test/helpers/int_registers.py | 11 ++- test-cli/test/helpers/iseelogger.py | 25 +++++- test-cli/test/helpers/iw.py | 124 ++++++++++++++++++++++++++++ test-cli/test/helpers/md5.py | 8 ++ test-cli/test/helpers/plc.py | 57 +++++++++++++ test-cli/test/helpers/psqldb.py | 3 + test-cli/test/helpers/qrreader.py | 3 + test-cli/test/helpers/sdl.py | 126 +++++++++++++++++++++++++++++ test-cli/test/helpers/setup_xml.py | 1 - test-cli/test/helpers/testsrv_db.py | 25 +++++- test-cli/test/helpers/utils.py | 68 ++++++++++++++++ test-cli/test/runners/simple.py | 41 ++++++---- test-cli/test/tasks/flasheeprom.py | 121 ++++++++++++++++------------ test-cli/test/tasks/flashmemory.py | 50 +++++++++--- test-cli/test/tests/qamper.py | 32 +++++--- test-cli/test/tests/qaudio.py | 77 ++++++++++++------ test-cli/test/tests/qdmesg.py | 30 +++---- test-cli/test/tests/qeeprom.py | 77 +++++++++++------- test-cli/test/tests/qethernet.py | 77 +++++++++++++----- test-cli/test/tests/qmmcflash.py | 46 ++++++++++- test-cli/test/tests/qnand.py | 44 +++++----- test-cli/test/tests/qplc.py | 70 ++++++++++++++++ test-cli/test/tests/qram.py | 56 +++++++++---- test-cli/test/tests/qusb.py | 143 ++++++++++++++++----------------- test-cli/test/tests/qusbdual.py | 90 --------------------- test-cli/test/tests/qwifi.py | 143 ++++++++++++++++----------------- 30 files changed, 1278 insertions(+), 452 deletions(-) create mode 100644 test-cli/test/helpers/camara.py create mode 100644 test-cli/test/helpers/gpio.py create mode 100644 test-cli/test/helpers/iw.py create mode 100644 test-cli/test/helpers/md5.py create mode 100644 test-cli/test/helpers/plc.py create mode 100644 test-cli/test/helpers/sdl.py create mode 100644 test-cli/test/helpers/utils.py create mode 100644 test-cli/test/tests/qplc.py delete mode 100644 test-cli/test/tests/qusbdual.py (limited to 'test-cli/test') diff --git a/test-cli/test/enums/StationStates.py b/test-cli/test/enums/StationStates.py index 040e6bc..88dba1f 100644 --- a/test-cli/test/enums/StationStates.py +++ b/test-cli/test/enums/StationStates.py @@ -18,4 +18,5 @@ class StationStates(Enum): WAITING_FOR_SCANNER = 50 FINISHED = 60 STATION_REBOOT = 2001 + STATION_WAIT_SHUTDOWN = 2002 diff --git a/test-cli/test/helpers/camara.py b/test-cli/test/helpers/camara.py new file mode 100644 index 0000000..9b2829c --- /dev/null +++ b/test-cli/test/helpers/camara.py @@ -0,0 +1,124 @@ +import cv2 +from test.helpers.syscmd import SysCommand + +class Camara(object): + __parent = None + __device_name = None + __device = None + __w = 1280 + __h = 720 + __contrast = 0.0 + __brightness = 0.0 + __saturation = 55.0 + __hue = 0.0 + __exposure = 166 + + def __init__(self, parent, device="video0", width=1280, height=720): + self.__parent = parent + self.__device_name = device + self.__w = width + self.__h = height + + def Close(self): + if self.__device is not None: + del self.__device + self.__device = None + + def Open(self): + self.Close() + self.__device = cv2.VideoCapture("/dev/{}".format(self.__device_name)) + if self.__device.isOpened(): + self.__configure() + return True + return False + + def getSize(self): + return self.__w, self.__h + + def setSize(self, w, h): + if self.__device is not None and self.__device.isOpened(): + self.__w = self.__setCamVar(cv2.CAP_PROP_FRAME_WIDTH, w) + self.__h = self.__setCamVar(cv2.CAP_PROP_FRAME_HEIGHT, h) + else: + self.__w = w + self.__h = h + + def setContrast(self, newVal): + if self.__device.isOpened(): + self.__contrast = self.__setCamVar(cv2.CAP_PROP_CONTRAST, newVal) + else: + self.__contrast = newVal + + def getContrast(self): + return self.__contrast + + def setBrightness(self, newVal): + if self.__device.isOpened(): + self.__brightness = self.__setCamVar(cv2.CAP_PROP_BRIGHTNESS, newVal) + else: + self.__brightness = newVal + + def getBrightness(self): + return self.__brightness + + def __configure(self): + self.__w = self.__setCamVar(cv2.CAP_PROP_FRAME_WIDTH, self.__w) + self.__h = self.__setCamVar(cv2.CAP_PROP_FRAME_HEIGHT, self.__h) + cam_setup = SysCommand('v4lsetup', '{}/scripts/v4l-cam.sh'.format(self.__parent.getAppPath())) + cam_setup.execute() + + #self.__contrast = self.__setCamVar(cv2.CAP_PROP_CONTRAST, self.__contrast) + #self.__brightness = self.__setCamVar(cv2.CAP_PROP_BRIGHTNESS, self.__brightness) + #self.__saturation = self.__setCamVar(cv2.CAP_PROP_SATURATION, self.__saturation) + #self.__hue = self.__setCamVar(cv2.CAP_PROP_HUE, self.__hue) + #self.__exposure = self.__setCamVar(cv2.CAP_PROP_EXPOSURE, self.__exposure) + + + def __setCamVar(self, key, val): + valold = cv2.VideoCapture.get(self.__device, key) + if valold != val: + cv2.VideoCapture.set(self.__device, key, val) + t = cv2.VideoCapture.get(self.__device, key) + return t + return val + + def __getCamVar(self, key): + return cv2.VideoCapture.get(self.__device, key); + + def getFrameCount(self): + return cv2.VideoCapture.get(self.__device, cv2.CAP_PROP_BUFFERSIZE); + + def getFrame(self): + if self.__device.isOpened(): + retval, image = self.__device.read() + if retval: + return image + return None + else: + return None + + def getImageSize(self, image): + if hasattr(image, 'shape'): + return image.shape[1], image.shape[0] + else: + return (0, 0, 0) + + def showFrame(self, name, frame, w=False, maxTime=3000): + cv2.imshow(name, frame) + if w: + if maxTime == -1: + cv2.waitKey() + else: + cv2.waitKey(maxTime) + + def saveFrame(self, fileName, Frame): + cv2.imwrite(fileName, Frame) + + def readImage(self, filename): + return cv2.imread('{}'.format(filename), 0) + + def destroyWindow(self, name): + cv2.destroyWindow(name) + + def closeWindows(self): + cv2.destroyAllWindows() \ No newline at end of file diff --git a/test-cli/test/helpers/cmdline.py b/test-cli/test/helpers/cmdline.py index fad81ac..db94a1c 100644 --- a/test-cli/test/helpers/cmdline.py +++ b/test-cli/test/helpers/cmdline.py @@ -1,5 +1,5 @@ -class LinuxKernel: +class LinuxKernelCmd: __kernel_vars = {} diff --git a/test-cli/test/helpers/gpio.py b/test-cli/test/helpers/gpio.py new file mode 100644 index 0000000..f127f2b --- /dev/null +++ b/test-cli/test/helpers/gpio.py @@ -0,0 +1,55 @@ +import os + +class gpio (object): + gpioNum = None + + def __init__(self, gpioNum, dir, val): + self.gpioNum = gpioNum + self.__export(gpioNum) + self.__set_dir(gpioNum, dir) + if dir == 'out': + self.__set_value(gpioNum, val) + + def set_val(self, value): + self.__set_value( self.gpioNum, value) + + + def __export(self, gpio_number): + if not os.path.isfile("/sys/class/gpio/gpio{}/value".format(gpio_number)): + try: + f = open("/sys/class/gpio/export", "w", newline="\n") + f.write(str(gpio_number)) + f.close() + except IOError: + return False, '{}'.format(IOError.errno) + return True + + def __unexport(self, gpio_number): + if os.path.isfile("/sys/class/gpio/gpio{}/value".format(gpio_number)): + try: + f = open("/sys/class/gpio/unexport", "w", newline="\n") + f.write(str(gpio_number)) + f.close() + except IOError: + return False, '{}'.format(IOError.errno) + return True + + def __set_dir(self, gpio_number, dir): + try: + f = open("/sys/class/gpio/gpio{}/direction".format(gpio_number), "r+", newline="\n") + val = f.readline() + if val != dir: + f.write(dir) + f.close() + except IOError: + return False, '{}'.format(IOError.errno) + return True + + def __set_value(self, gpio_number, value): + try: + f = open("/sys/class/gpio/gpio{}/value".format(gpio_number), "w", newline="\n") + f.write(str(value)) + f.close() + except IOError: + return False, '{}'.format(IOError.errno) + return True \ No newline at end of file diff --git a/test-cli/test/helpers/int_registers.py b/test-cli/test/helpers/int_registers.py index d081853..133387c 100644 --- a/test-cli/test/helpers/int_registers.py +++ b/test-cli/test/helpers/int_registers.py @@ -22,6 +22,12 @@ def read(addr): os.close(fd) return "%08X" % retval[0] +def imx8m_readid(): + f = open("/sys/bus/soc/devices/soc0/soc_uid", "r", newline="\n") + val = f.readline() + f.close() + return val.rstrip() + def get_die_id(modelid): dieid = "" @@ -36,9 +42,10 @@ def get_die_id(modelid): registers = [0x4830A224, 0x4830A220, 0x4830A21C, 0x4830A218] elif modelid.find("OMAP5") == 0: registers = [0x4A002210, 0x4A00220C, 0x4A002208, 0x4A002200] + elif modelid.find("IGEP0048") == 0: + return imx8m_readid() else: - raise Exception('modelid not defined') - + raise Exception('modelid not defined: {}, modelid') for rg in registers: dieid = dieid + read(rg) return dieid diff --git a/test-cli/test/helpers/iseelogger.py b/test-cli/test/helpers/iseelogger.py index 785a78c..4b1087c 100644 --- a/test-cli/test/helpers/iseelogger.py +++ b/test-cli/test/helpers/iseelogger.py @@ -1,6 +1,6 @@ import logging import logging.handlers - +import datetime class ISEE_Logger(object): __logger = None @@ -37,3 +37,26 @@ class ISEE_Logger(object): def getlogger(self): return self.__logger +class MeasureTime: + __difference = None + __first_time = None + __later_time = None + + def __init__(self): + self.__first_time = datetime.datetime.now() + + def start(self): + self.first_time = datetime.datetime.now() + + def stop(self): + self.__later_time = datetime.datetime.now() + self.__difference = self.__later_time - self.__first_time + return self.__difference.total_seconds() + + def getTime(self): + return self.__difference.total_seconds() + + +global logObj +logObj = ISEE_Logger(logging.INFO) + diff --git a/test-cli/test/helpers/iw.py b/test-cli/test/helpers/iw.py new file mode 100644 index 0000000..8e29448 --- /dev/null +++ b/test-cli/test/helpers/iw.py @@ -0,0 +1,124 @@ +from sh import iw +from scanf import scanf + +class iw_scan: + __interface = None + __raw_unparsed = [] + __raw = None + + def __init__(self, interface='wlan0'): + self.__interface = interface + + def scan(self): + self.__raw_unparsed = [] + self.__raw = iw('{}'.format(self.__interface), 'scan') + if self.__raw.exit_code == 0: + self.__raw_unparsed = self.__raw.stdout.decode("utf-8").split('\n') + return True + return False + + def getRawData (self): + return self.__raw_unparsed + + def getInterface(self): + return self.__interface + + def getRawObject(self): + return self.__raw + + +class iwScan: + __iw_scan = None + __station_list = {} + + def __init__(self, interface='wlan0'): + self.__iw_scan = iw_scan(interface) + + def scan(self): + if self.__iw_scan.scan(): + self.__parse_scan(self.__iw_scan.getRawData()) + return True + return False + + def getLastError(self): + rObject = self.__iw_scan.getRawObject() + if rObject.exit_code != 0: + return rObject.stderr + return '' + + def __Parse_BBS(self, line): + data = {} + res = scanf("BSS %s(on %s) -- %s", line) + if res == None: + res = scanf("BSS %s(on %s)", line) + data["MAC"] = res[0] + data["DEV"] = res[1] + if len(res) == 3: + data["ASSOCIATED"] = 'YES' + else: + data["ASSOCIATED"] = 'NO' + return data + + def __Parse_T(self, id, OnNotFoundAttr ,line): + data = {} + res = scanf("{}: %s".format(id), line) + if res == None: + data[id.upper()] = OnNotFoundAttr + else: + data[id.upper()] = res[0] + return data + + def __Parse_X(self, line): + data = {} + res = scanf("DS Parameter set: channel %s", line) + if res == None: + data['CHANNEL'] = '-1' + else: + data['CHANNEL'] = res[0] + return data + + def __block_stationlist(self, rawdata): + list = {} + count = 0 + for line in rawdata: + idx = line.find('BSS') + if idx != -1 and idx == 0: + if len(list) > 0: + count += 1 + self.__station_list[count] = list + list = self.__Parse_BBS(line) + elif line.find('SSID:') != -1: + list = {**list, **self.__Parse_T('SSID', 'HIDDEN', line)} + elif line.find('freq:') != -1: + list = {**list, **self.__Parse_T('freq', '', line)} + elif line.find('signal:') != -1: + list = {**list, **self.__Parse_T('signal', '', line)} + elif line.find('DS Parameter set:') != -1: + list = {**list, **self.__Parse_X(line)} + if count > 0: + count += 1 + self.__station_list[count] = list + + def __parse_scan(self, rawData): + self.__station_list = {} + self.__block_stationlist(rawData) + #print('{}'.format(self.__station_list)) + #for i in self.__station_list: + # print(self.__station_list[i]) + + def findConnected (self): + for i in self.__station_list: + st = self.__station_list[i] + if st.get('ASSOCIATED', 'NO') == 'YES': + return True, self.__station_list[i] + return False, None + + def findBySSID(self, ssid): + for i in self.__station_list: + st = self.__station_list[i] + if st.get('SSID', '') == ssid: + return True, self.__station_list[i] + return False, None + + def getStations(self): + return self.__station_list \ No newline at end of file diff --git a/test-cli/test/helpers/md5.py b/test-cli/test/helpers/md5.py new file mode 100644 index 0000000..9bc9e23 --- /dev/null +++ b/test-cli/test/helpers/md5.py @@ -0,0 +1,8 @@ +import hashlib + +def md5_file(fname): + hash_md5 = hashlib.md5() + with open(fname, "rb") as f: + for chunk in iter(lambda: f.read(4096), b""): + hash_md5.update(chunk) + return hash_md5.hexdigest() \ No newline at end of file diff --git a/test-cli/test/helpers/plc.py b/test-cli/test/helpers/plc.py new file mode 100644 index 0000000..3b00934 --- /dev/null +++ b/test-cli/test/helpers/plc.py @@ -0,0 +1,57 @@ +import sh +from sh import flashcp +from sh import flash_erase +from sh import ErrorReturnCode +from sh import Command +from test.helpers.gpio import gpio + + +class dcpPLC(object): + __nReset = None + __Phy = None + __Plc = None + __mtd_device = None + __factool = None + __myConfigTool = None + + def __init__(self, plcfactool, mtd_device): + # default save firmware + self.__nRest = gpio('75', 'out', '0') + self.__nRest = gpio('69', 'out', '0') + self.__nRest = gpio('78', 'out', '1') + self.__factool = plcfactool + self.__mtd_device = mtd_device + self.__myConfigTool = Command(self.__factool) + + def setSaveFirmwareMode(self): + self.__nRest = gpio('75', 'out', '0') + self.__nRest = gpio('69', 'out', '0') + self.__nRest = gpio('78', 'out', '1') + + def setBootMode(self): + self.__nRest = gpio('78', 'out', '0') + self.__nRest = gpio('75', 'out', '1') + self.__nRest = gpio('69', 'out', '1') + + def SaveFirmware(self, firmare): + self.setSaveFirmwareMode() + try: + flash_erase(self.__mtd_device) + flashcp(firmare, self.__mtd_device) + except ErrorReturnCode as Error: + return False, "plc flash firmware failed {} ".format(Error.exit_code) + return True, '' + + def set_plc (self, var, value, password): + try: + self.__myConfigTool("-o", "SET", "-p", "{}".format(var), '{}'.format(value), "-w", "{}".format(password)) + except ErrorReturnCode as Error: + return False, "set var failed {} {}".format(var,Error.exit_code) + return True, '' + + def get_plc (self, var, value, password): + try: + self.__myConfigTool("-o", "GET", "-p", "{}".format(var), '{}'.format(value), "-w", "{}".format(password)) + except ErrorReturnCode as Error: + return False, "set var failed {} {}".format(var,Error.exit_code) + return True, '' diff --git a/test-cli/test/helpers/psqldb.py b/test-cli/test/helpers/psqldb.py index c98338a..e703c3a 100644 --- a/test-cli/test/helpers/psqldb.py +++ b/test-cli/test/helpers/psqldb.py @@ -31,6 +31,9 @@ class PgSQLConnection(object): print(error) return result + def getConfig(self): + return self.__db_config + def db_execute_query(self, query): cur = self.__conection_object.cursor() cur.execute(query) diff --git a/test-cli/test/helpers/qrreader.py b/test-cli/test/helpers/qrreader.py index 744db54..f663e99 100644 --- a/test-cli/test/helpers/qrreader.py +++ b/test-cli/test/helpers/qrreader.py @@ -4,6 +4,7 @@ import threading import time import selectors from selectors import DefaultSelector, EVENT_READ +from test.helpers.iseelogger import logObj selector = selectors.DefaultSelector() @@ -37,7 +38,9 @@ class QRReader: def getQRlist(self): devices = [evdev.InputDevice(path) for path in evdev.list_devices()] + logObj.getlogger().debug("{}".format(devices)) for device in devices: + logObj.getlogger().debug("{}".format(device.name)) if device.name in qrdevice_list: self.__myReader['NAME'] = device.name # print(self.__myReader['NAME']) diff --git a/test-cli/test/helpers/sdl.py b/test-cli/test/helpers/sdl.py new file mode 100644 index 0000000..8f55d9f --- /dev/null +++ b/test-cli/test/helpers/sdl.py @@ -0,0 +1,126 @@ +import sdl2.ext +from sdl2 import * +import os +import time + +Colors = { + 'red': sdl2.ext.Color(255, 0, 0, 255), + 'green': sdl2.ext.Color(0, 255, 0, 255), + 'blue': sdl2.ext.Color(0, 0, 255, 255), + 'white': sdl2.ext.Color(255, 255, 255, 255), + 'black': sdl2.ext.Color(0, 0, 0, 255), +} + + +class SDL2(object): + __resources = None + __w = 1024 + __h = 768 + __winName = "noname" + __window = None + __factory = None + __renderer = None + __srender = None + + def __init__(self, parent): + os.environ['SDL_VIDEODRIVER'] = "x11" + os.environ['DISPLAY'] = ":0" + self.__resources = sdl2.ext.Resources(parent.getAppPath(), 'files') + sdl2.ext.init() + self.__createWindow() + + def __createWindow(self): + self.__window = sdl2.ext.Window(title='{}'.format(self.__winName), size=(self.__w, self.__h), position=(0, 0), + flags=( + SDL_WINDOW_HIDDEN | SDL_WINDOW_FULLSCREEN | SDL_WINDOW_BORDERLESS | SDL_WINDOW_MAXIMIZED)) + self.__renderer = sdl2.ext.Renderer(self.__window) + self.__factory = sdl2.ext.SpriteFactory(sdl2.ext.TEXTURE, renderer=self.__renderer) + self.__srender = self.__factory.create_sprite_render_system(self.__window) + self.__window.show() + SDL_ShowCursor(SDL_DISABLE) + + def createFont(self, fontName, fontSize, fontColor): + return sdl2.ext.FontManager(font_path=self.__resources.get_path(fontName), size=fontSize, color=fontColor) + + def WriteText(self, text, x, y, fontManager): + imText = self.__factory.from_text(text, fontmanager=fontManager) + self.__renderer.copy(imText, dstrect=(x, y, imText.size[0], imText.size[1])) + + def show(self): + self.__window.show() + + def hide(self): + self.__window.hide() + + def setColor(self, red, green, blue, alpha): + self.__renderer.color = sdl2.ext.Color(red, green, blue, alpha) + + def fillColor(self, red, green, blue, alpha): + self.setColor(red, green, blue, alpha) + self.__renderer.clear() + + def fillbgColor(self, color, update=False): + if color in Colors: + self.__renderer.color = Colors[color] + self.__renderer.clear() + if update: + self.update() + + def update(self): + self.__renderer.present() + + def showImage(self, filename): + im = self.__factory.from_image(self.__resources.get_path(filename)) + self.__srender.render(im) + + +class SDL2_Test(object): + __sdl2 = None + + def __init__(self, parent): + self.__sdl2 = SDL2(parent) + + def Clear(self): + self.__sdl2.fillbgColor('black', True) + + def Paint(self, dcolor): + self.Clear() + self.__sdl2.fillbgColor(dcolor.lower(), True) + + +class SDL2_Message(object): + __sdl2 = None + __fontManager_w = None + __fontManager_b = None + + def __init__(self, parent): + self.__sdl2 = SDL2(parent) + self.__fontManager_w = self.__sdl2.createFont('OpenSans-Regular.ttf', 24, Colors['white']) + self.__fontManager_b = self.__sdl2.createFont('OpenSans-Regular.ttf', 24, Colors['black']) + + def Clear(self): + self.__sdl2.fillbgColor('black', True) + + def Paint(self, dcolor): + self.Clear() + self.__sdl2.fillbgColor(dcolor.lower(), True) + + def __write_w(self, x, y, text): + self.__sdl2.WriteText(text, x, y, self.__fontManager_w) + + def __write_b(self, x, y, text): + self.__sdl2.WriteText(text, x, y, self.__fontManager_b) + + def setTestOK(self, board_uuid, qrdata): + self.Paint('GREEN') + self.__write_b(100, 50, 'TEST OK') + self.__write_b(100, 100, 'uuid={}'.format(board_uuid)) + self.__write_b(100, 150, 'qr={}'.format(qrdata)) + self.__sdl2.update() + + def setTestERROR(self, error): + self.Paint('RED') + self.__write_w(100, 50, 'TEST FAILED') + self.__write_w(100, 100, '{}'.format(error)) + self.__sdl2.update() + diff --git a/test-cli/test/helpers/setup_xml.py b/test-cli/test/helpers/setup_xml.py index 603a2ac..d61d1fb 100644 --- a/test-cli/test/helpers/setup_xml.py +++ b/test-cli/test/helpers/setup_xml.py @@ -1,6 +1,5 @@ import xml.etree.ElementTree as XMLParser - class XMLSetup (object): """XML Setup Parser""" __tree = None # Parser diff --git a/test-cli/test/helpers/testsrv_db.py b/test-cli/test/helpers/testsrv_db.py index 9579e7e..c2b2276 100644 --- a/test-cli/test/helpers/testsrv_db.py +++ b/test-cli/test/helpers/testsrv_db.py @@ -24,6 +24,9 @@ class TestSrv_Database(object): self.__sqlObject = PgSQLConnection() return self.__sqlObject.db_connect(self.__xml_setup.getdbConnectionStr()) + def getConfig(self): + return self.__sqlObject.getConfig() + def create_board(self, processor_id, model_id, variant, station, bmac=None): '''create a new board''' if bmac is None: @@ -41,7 +44,8 @@ class TestSrv_Database(object): return res[0][0] except Exception as err: r = find_between(str(err), '#', '#') - # print(r) + print(r) + print(str(err)) return None def get_tests_list(self, board_uuid): @@ -95,10 +99,11 @@ class TestSrv_Database(object): sql = "SELECT isee.f_finish_test({},{},'{}','{}')".format(testid_ctl, testid, newstatus, textresult) # print('>>>' + sql) try: + print('finish_test => SQL {}'.format(sql)) self.__sqlObject.db_execute_query(sql) except Exception as err: r = find_between(str(err), '#', '#') - # print(r) + print('finish_test => {}'.format(err)) return None def upload_result_file(self, testid_ctl, testid, desc, filepath, mimetype): @@ -195,6 +200,18 @@ class TestSrv_Database(object): def change_station_state(self, station, newstate): sql = "SELECT station.setmystate('{}', '{}', NULL)".format(newstate, station) + print('>>>' + sql) + try: + res = self.__sqlObject.db_execute_query(sql) + print(res) + return res[0][0] + except Exception as err: + r = find_between(str(err), '#', '#') + print(r) + return None + + def get_setup_variable(self, skey): + sql = "SELECT * FROM admin.get_setupvar('{}')".format(skey) # print('>>>' + sql) try: res = self.__sqlObject.db_execute_query(sql) @@ -205,7 +222,7 @@ class TestSrv_Database(object): # print(r) return None - def get_setup_variable(self, skey): + def get_setup_variable(self, skey , default): sql = "SELECT * FROM admin.get_setupvar('{}')".format(skey) # print('>>>' + sql) try: @@ -215,4 +232,4 @@ class TestSrv_Database(object): except Exception as err: r = find_between(str(err), '#', '#') # print(r) - return None + return default diff --git a/test-cli/test/helpers/utils.py b/test-cli/test/helpers/utils.py new file mode 100644 index 0000000..8d2c27b --- /dev/null +++ b/test-cli/test/helpers/utils.py @@ -0,0 +1,68 @@ +import json +import socket +import os +import scanf + +def save_json_to_disk(filePath, description, mime, json_data, result): + with open(filePath, 'w') as outfile: + json.dump(json_data, outfile, indent=4) + outfile.close() + result.append( + { + "description": description, + "filepath": filePath, + "mimetype": mime + } + ) + +def save_file_to_disk(filePath, description, mime, data, result): + with open(filePath, 'w') as outfile: + outfile.write(data) + outfile.close() + result.append( + { + "description": description, + "filepath": filePath, + "mimetype": mime + } + ) + +def save_result (filePath, description, mime, result): + result.append( + { + "description": description, + "filepath": filePath, + "mimetype": mime + } + ) + + +def str2bool(v): + return v.lower() in ("yes", "true", "t", "1") + +def station2Port(base): + Name = socket.gethostname() + res = scanf.scanf("Station%d", Name) + if res[0]: + NmBase = int(base) + res = int(res[0]) + return str(NmBase + res) + return base + + +def sys_read(sysnode): + try: + f = open(sysnode, "r") + data = f.readline() + f.close() + except IOError as Error: + return False, '{}'.format(Error.errno) + return True, data + +def removefileIfExist(fname): + if os.path.exists(fname): + try: + os.remove(fname) + except OSError as error: + return False, str(error) + return True, '' diff --git a/test-cli/test/runners/simple.py b/test-cli/test/runners/simple.py index 2eb61a4..ece5a4e 100644 --- a/test-cli/test/runners/simple.py +++ b/test-cli/test/runners/simple.py @@ -5,6 +5,7 @@ Simple Test Runner for unittest module import sys import unittest +from test.helpers.iseelogger import logObj class SimpleTestRunner: @@ -59,28 +60,34 @@ class TextTestResult(unittest.TestResult): def addError(self, test, err): unittest.TestResult.addError(self, test, err) - # test.longMessage = err[1] + test.longMessage = err[1] self.result = self.ERROR - print(err[1]) + print(err) def addFailure(self, test, err): unittest.TestResult.addFailure(self, test, err) test.longMessage = err[1] self.result = self.FAIL + logObj.getlogger().info('{}:{}'.format(test, err)) def stopTest(self, test): - unittest.TestResult.stopTest(self, test) - # display: print test result - self.runner.writeUpdate(self.result) - # save result data - for result in test.getresults(): - self.__pgObj.upload_result_file(test.params["testidctl"], test.params["testid"], - result["description"], result["filepath"], result["mimetype"]) - # SEND TO DB THE RESULT OF THE TEST - if self.result == self.PASS: - status = "TEST_COMPLETE" - resulttext = test.gettextresult() - else: - status = "TEST_FAILED" - resulttext = test.longMessage - self.__pgObj.finish_test(test.params["testidctl"], test.params["testid"], status, resulttext) + try: + unittest.TestResult.stopTest(self, test) + # display: print test result + self.runner.writeUpdate(self.result) + # save result data + for result in test.getresults(): + self.__pgObj.upload_result_file(test.params["testidctl"], test.params["testid"], + result["description"], result["filepath"], result["mimetype"]) + # SEND TO DB THE RESULT OF THE TEST + if self.result == self.PASS: + status = "TEST_COMPLETE" + resulttext = test.gettextresult() + logObj.getlogger().info('{}:{}:{}:{}'.format(test.params["testidctl"], test.params["testid"], status, resulttext)) + else: + status = "TEST_FAILED" + resulttext = test.longMessage + logObj.getlogger().info('{}:{}:{}:{}'.format(test.params["testidctl"], test.params["testid"], status, resulttext)) + self.__pgObj.finish_test(test.params["testidctl"], test.params["testid"], status, resulttext) + except Exception as E: + logObj.getlogger().error('Exception: [{}]{}:{}:{}:{}'.format(E, test.params["testidctl"], test.params["testid"], status, resulttext)) \ No newline at end of file diff --git a/test-cli/test/tasks/flasheeprom.py b/test-cli/test/tasks/flasheeprom.py index feeb04c..775c556 100644 --- a/test-cli/test/tasks/flasheeprom.py +++ b/test-cli/test/tasks/flasheeprom.py @@ -2,55 +2,76 @@ import os import binascii from test.helpers.globalVariables import globalVar +class EEprom_Flasher: + __Name = None + __varlist = None + __xmlObj = None + __lastError = '' -def _generate_data_bytes(boarduuid, mac0, mac1): - data = bytearray() - data += (2029785358).to_bytes(4, 'big') # magicid --> 0x78FC110E - data += bytearray([0, 0, 0, 0]) # crc32 = 0 - data += bytearray(boarduuid + "\0", + def __init__(self, varlist): + self.__varlist = varlist + self.__xmlObj = varlist['xml'] + self.__Name = varlist.get('name_eeprom', self.__xmlObj.getKeyVal('EEProm_Flasher', 'name', 'EEProm_Flasher')) + # self.__igepflashPath = self.__xmlObj.getKeyVal('NAND_Flasher', 'igep_flash', '/usr/bin/igep-flash') + # self.__ImagePath = varlist.get('flashimagepath', '') + # self.__SkipNandtest = varlist.get('skipnandtest', self.__xmlObj.getKeyVal('NAND_Flasher', 'skipnandtest', '1')) + + def getTaskName(self): + return self.__Name + + def getError(self): + return self.__lastError + + def Execute(self): + return True, None + + def __generate_data_bytes(self, boarduuid, mac0, mac1): + data = bytearray() + data += (2029785358).to_bytes(4, 'big') # magicid --> 0x78FC110E + data += bytearray([0, 0, 0, 0]) # crc32 = 0 + data += bytearray(boarduuid + "\0", 'ascii') # uuid --> 'c0846c8a-5fa5-11ea-8576-f8b156ac62d7' and \0 at the end - data += binascii.unhexlify(mac0.replace(':', '')) # mac0 --> 'f8:b1:56:ac:62:d7' - if mac1 is not None: - data += binascii.unhexlify(mac1.replace(':', '')) # mac1 --> 'f8:b1:56:ac:62:d7' - else: - data += bytearray([0, 0, 0, 0, 0, 0]) # mac1 --> 0:0:0:0:0:0 - # calculate crc - crc = (binascii.crc32(data, 0)).to_bytes(4, 'big') - data[4:8] = crc - return data - - -def _generate_output_data(data_rx): - boarduuid = data_rx[8:44].decode('ascii') # no 8:45 porque el \0 final hace que no funcione postgresql - mac0 = binascii.hexlify(data_rx[45:51]).decode('ascii') - mac1 = binascii.hexlify(data_rx[51:57]).decode('ascii') - smac0 = ':'.join(mac0[i:i + 2] for i in range(0, len(mac0), 2)) - smac1 = ':'.join(mac1[i:i + 2] for i in range(0, len(mac1), 2)) - eepromdata = "UUID " + boarduuid + " , MAC0 " + smac0 + " , MAC1 " + smac1 - - return eepromdata - - -# returns exitcode and data saved into eeprom -def flash_eeprom(eeprompath, boarduuid, mac0, mac1=None): - print("Start programming Eeprom...") - # check if eeprompath is correct - if os.path.isfile(eeprompath): - # create u-boot data struct - data = _generate_data_bytes(boarduuid, mac0, mac1) - # write into eeprom and read back - f = open(eeprompath, "r+b") - f.write(data) - f.seek(0) - data_rx = f.read(57) - for i in range(57): - if data_rx[i] != data[i]: - print("Error while programming eeprom memory.") - return 1, None - print("Eeprom programmed succesfully.") - # generated eeprom read data - eepromdata = _generate_output_data(data_rx) - return 0, eepromdata - else: - print("Eeprom memory not found.") - return 1, None + data += binascii.unhexlify(mac0.replace(':', '')) # mac0 --> 'f8:b1:56:ac:62:d7' + if mac1 is not None: + data += binascii.unhexlify(mac1.replace(':', '')) # mac1 --> 'f8:b1:56:ac:62:d7' + else: + data += bytearray([0, 0, 0, 0, 0, 0]) # mac1 --> 0:0:0:0:0:0 + # calculate crc + crc = (binascii.crc32(data, 0)).to_bytes(4, 'big') + data[4:8] = crc + return data + + + def __generate_output_data(self, data_rx): + boarduuid = data_rx[8:44].decode('ascii') # no 8:45 porque el \0 final hace que no funcione postgresql + mac0 = binascii.hexlify(data_rx[45:51]).decode('ascii') + mac1 = binascii.hexlify(data_rx[51:57]).decode('ascii') + smac0 = ':'.join(mac0[i:i + 2] for i in range(0, len(mac0), 2)) + smac1 = ':'.join(mac1[i:i + 2] for i in range(0, len(mac1), 2)) + eepromdata = "UUID " + boarduuid + " , MAC0 " + smac0 + " , MAC1 " + smac1 + return eepromdata + + + # returns exitcode and data saved into eeprom + def flash_eeprom(self, eeprompath, boarduuid, mac0, mac1=None): + print("Start programming Eeprom...") + # check if eeprompath is correct + if os.path.isfile(eeprompath): + # create u-boot data struct + data = self.__generate_data_bytes(boarduuid, mac0, mac1) + # write into eeprom and read back + f = open(eeprompath, "r+b") + f.write(data) + f.seek(0) + data_rx = f.read(57) + for i in range(57): + if data_rx[i] != data[i]: + print("Error while programming eeprom memory.") + return 1, None + print("Eeprom programmed succesfully.") + # generated eeprom read data + eepromdata = self.__generate_output_data(data_rx) + return 0, eepromdata + else: + print("Eeprom memory not found.") + return 1, None diff --git a/test-cli/test/tasks/flashmemory.py b/test-cli/test/tasks/flashmemory.py index 3be56d7..ad9d92a 100644 --- a/test-cli/test/tasks/flashmemory.py +++ b/test-cli/test/tasks/flashmemory.py @@ -1,12 +1,44 @@ import sh +import os +class NAND_Flasher: + __Name = None + __varlist = None + __xmlObj = None + __igepflashPath = None + __lastError = '' + + def __init__(self, varlist): + self.__varlist = varlist + self.__xmlObj = varlist['xml'] + self.__Name = varlist.get('name_flashnand', self.__xmlObj.getKeyVal('NAND_Flasher', 'name', 'NAND_Flasher')) + self.__igepflashPath = self.__xmlObj.getKeyVal('NAND_Flasher', 'igep_flash', '/usr/bin/igep-flash') + self.__ImagePath = varlist.get('flashimagepath', '') + self.__SkipNandtest = varlist.get('skipnandtest', self.__xmlObj.getKeyVal('NAND_Flasher', 'skipnandtest', '1')) + + def getTaskName(self): + return self.__Name + + def getError(self): + return self.__lastError + + def Execute(self): + try: + self.__lastError = '' + if not os.path.isfile(self.__ImagePath): + self.__lastError('Not Image Found: {}'.format(self.__ImagePath)) + return False, None + if self.__SkipNandtest == '1': + p = sh.bash('{}'.format(self.__igepflashPath), "--skip-nandtest", "--image", self.__ImagePath) + else: + p = sh.bash('{}'.format(self.__igepflashPath), "--image", self.__ImagePath) + if p.exit_code != 0: + return False, None + except OSError as e: + self.__lastError('Exception: {}'.format(e.strerror)) + return False, None + except Exception as Error: + self.__lastError('Exception: {}'.format(Error)) + return False, None + return True, None -def flash_memory(imagepath): - print("Start programming Nand memory...") - p = sh.bash("/usr/bin/igep-flash", "--skip-nandtest", "--image", imagepath) - if p.exit_code != 0: - print("Flasher: Could not complete flashing task.") - return 1 - else: - print("Flasher: NAND memory flashed succesfully.") - return 0 diff --git a/test-cli/test/tests/qamper.py b/test-cli/test/tests/qamper.py index 58054c9..df340eb 100644 --- a/test-cli/test/tests/qamper.py +++ b/test-cli/test/tests/qamper.py @@ -5,6 +5,7 @@ from test.helpers.amper import Amper class Qamper(unittest.TestCase): params = None __resultlist = None # resultlist is a python list of python dictionaries + dummytest = False # varlist: undercurrent, overcurrent def __init__(self, testname, testfunc, varlist): @@ -21,8 +22,28 @@ class Qamper(unittest.TestCase): raise Exception('overcurrent param inside Qamp must be defined') self._testMethodDoc = testname self.__resultlist = [] + if "dummytest" in varlist: + self.dummytest = varlist["dummytest"] + + def saveresultinfile(self, currentvalue): + # save result in a file + with open('/mnt/station_ramdisk/amper.txt', 'w') as outfile: + n = outfile.write("Current: {} A".format(currentvalue)) + outfile.close() + self.__resultlist.append( + { + "description": "Amperimeter values", + "filepath": "/mnt/station_ramdisk/amper.txt", + "mimetype": "text/plain" + } + ) def execute(self): + if self.dummytest: + self.current = "0.0" + self.saveresultinfile(self.current) + return + amp = Amper() # open serial connection if not amp.open(): @@ -35,16 +56,7 @@ class Qamper(unittest.TestCase): # get current value (in Amperes) self.current = amp.getCurrent() # save result in a file - with open('/mnt/station_ramdisk/amper.txt', 'w') as outfile: - n = outfile.write("Current: {} A".format(self.current)) - outfile.close() - self.__resultlist.append( - { - "description": "Amperimeter values", - "filepath": "/mnt/station_ramdisk/amper.txt", - "mimetype": "text/plain" - } - ) + self.saveresultinfile(self.current) # close serial connection amp.close() # Check current range diff --git a/test-cli/test/tests/qaudio.py b/test-cli/test/tests/qaudio.py index 3d2113a..2c86809 100644 --- a/test-cli/test/tests/qaudio.py +++ b/test-cli/test/tests/qaudio.py @@ -2,56 +2,78 @@ import unittest import sh import wave import contextlib - - -def calc_audio_duration(fname): - with contextlib.closing(wave.open(fname, 'r')) as f: - frames = f.getnframes() - rate = f.getframerate() - duration = frames / float(rate) - f.close() - return duration - +import uuid +import time +from test.helpers.utils import save_result +from test.helpers.iseelogger import logObj class Qaudio(unittest.TestCase): params = None __resultlist = None # resultlist is a python list of python dictionaries __dtmf_secuence = ["1", "3", "5", "7", "9"] + __dtmf_file = None + __file_uuid = None + __QaudioName = None def __init__(self, testname, testfunc, varlist): self.params = varlist super(Qaudio, self).__init__(testfunc) self._testMethodDoc = testname self.__resultlist = [] + self.__xmlObj = varlist["xml"] + self.__QaudioName = varlist.get('name', 'qaudio') + self.__dtmf_file_play = varlist.get('play_dtmf_file', self.__xmlObj.getKeyVal(self.__QaudioName, "play_dtmf_file", "dtmf-13579.wav")) + self.__recordtime = varlist.get('recordtime', self.__xmlObj.getKeyVal(self.__QaudioName, "recordtime", "0.15")) + self.__dtmf_file_record = varlist.get('record_dtmf_file', self.__xmlObj.getKeyVal(self.__QaudioName, "record_dtmf_file", "record-{}.wav")) + self.__sampling_rate = varlist.get('rate', self.__xmlObj.getKeyVal(self.__QaudioName, "rate", "8000")) + self.__record_path = varlist.get('to', self.__xmlObj.getKeyVal(self.__QaudioName, "to", "/mnt/station_ramdisk")) + self.__run_delay = float(varlist.get('aplay_run_delay', self.__xmlObj.getKeyVal(self.__QaudioName, "aplay_run_delay", "0.0"))) + self.__file_uuid = uuid.uuid4() + self.__dtmf_file_record = self.__dtmf_file_record.format(self.__file_uuid) + + def restoreAlsaCtl(self): + try: + sh.alsactl('restore'); + except Exception as E: + logObj.getlogger().error("Failed to Execite alsactl restore"); def execute(self): - # analize audio file - recordtime = calc_audio_duration("/var/lib/hwtest-files/dtmf-13579.wav") + 0.15 + self.restoreAlsaCtl() + try: + # analize audio file + calcRecordTime = self.calc_audio_duration(self.__dtmf_file_play) + float(self.__recordtime) + float(0.1) + except TypeError as Error: + self.fail("failed: TypeError: {}.".Error) + # previous play to estabilise audio lines - p1 = sh.aplay("/var/lib/hwtest-files/dtmf-13579.wav", _bg=True) - p2 = sh.arecord("-r", 8000, "-d", recordtime, "/mnt/station_ramdisk/recorded.wav", _bg=True) - p1.wait() - p2.wait() - # play and record - p1 = sh.aplay("/var/lib/hwtest-files/dtmf-13579.wav", _bg=True) - p2 = sh.arecord("-r", 8000, "-d", recordtime, "/mnt/station_ramdisk/recorded.wav", _bg=True) - p1.wait() + p2 = sh.arecord("-r", self.__sampling_rate, "-d", calcRecordTime, "{}/{}".format(self.__record_path, self.__dtmf_file_record), _bg=True) + time.sleep(self.__run_delay) + p1 = sh.aplay(self.__dtmf_file_play) p2.wait() if p1.exit_code == 0 and p2.exit_code == 0: - p = sh.multimon("-t", "wav", "-a", "DTMF", "/mnt/station_ramdisk/recorded.wav", "-q") + p = sh.multimon("-t", "wav", "-a", "DTMF", "{}/{}".format(self.__record_path, self.__dtmf_file_record), "-q") if p.exit_code == 0: lines = p.stdout.decode('ascii').splitlines() self.__dtmf_secuence_result = [] for li in lines: if li.split(" ")[0] == "DTMF:": self.__dtmf_secuence_result.append(li.split(" ")[1]) + self.__dtmf_secuence_result = sorted(list(set(self.__dtmf_secuence_result))) # compare original and processed dtmf sequence if len(self.__dtmf_secuence) == len(self.__dtmf_secuence_result): for a, b in zip(self.__dtmf_secuence, self.__dtmf_secuence_result): if a != b: - self.fail("failed: sent and received DTMF sequence don't match.") + logObj.getlogger().debug( + "failed: sent and received DTMF sequence do not match.{} != {}".format( + self.__dtmf_secuence, self.__dtmf_secuence_result)) + self.fail("failed: sent and received DTMF sequence do not match.") + save_result(filePath='{}/{}'.format(self.__record_path, self.__dtmf_file_record), + description='sound record', + mime='audio/x-wav', + result=self.__resultlist) else: - self.fail("failed: received DTMF sequence is shorter than expected.") + logObj.getlogger().debug("received DTMF sequence is shorter than expected.{} {}".format(self.__dtmf_secuence,self.__dtmf_secuence_result)) + self.fail("received DTMF sequence is shorter than expected") else: self.fail("failed: unable to use multimon command.") else: @@ -62,3 +84,12 @@ class Qaudio(unittest.TestCase): def gettextresult(self): return "" + + def calc_audio_duration(self, fname): + duration = 0.0 + with contextlib.closing(wave.open(fname, 'r')) as f: + frames = f.getnframes() + rate = f.getframerate() + duration = frames / float(rate) + f.close() + return duration diff --git a/test-cli/test/tests/qdmesg.py b/test-cli/test/tests/qdmesg.py index b35f1ff..39a5047 100644 --- a/test-cli/test/tests/qdmesg.py +++ b/test-cli/test/tests/qdmesg.py @@ -1,4 +1,5 @@ import sh +import os import os.path from os import path @@ -9,24 +10,23 @@ class Qdmesg: def __init__(self, testname, testfunc, varlist): self.params = varlist - self._testMethodDoc = testname + self.__testMethodDoc = testname self.__resultlist = [] self.pgObj = varlist["db"] + self.__xmlObj = varlist["xml"] + self.__QdmesgName = varlist.get('name', 'qdmesg') + self.__syslog_dmesg_file = varlist.get('syslog_dmesg',self.__xmlObj.getKeyVal(self.__QdmesgName, "syslog_dmesg", + "/var/log/kern.log")) + + def getTestName(self): + return self.__testMethodDoc def execute(self): - print("running dmesg test") self.pgObj.run_test(self.params["testidctl"], self.params["testid"]) - # delete previous file - if path.exists("/mnt/station_ramdisk/dmesg.txt"): - os.remove("/mnt/station_ramdisk/dmesg.txt") - # generate file - p = sh.dmesg("--color=never", _out="/mnt/station_ramdisk/dmesg.txt") - if p.exit_code == 0: - # save dmesg result in DB - self.pgObj.upload_result_file(self.params["testidctl"], self.params["testid"], "dmesg output", - "/mnt/station_ramdisk/dmesg.txt", "text/plain") - self.pgObj.finish_test(self.params["testidctl"], self.params["testid"], "TEST_COMPLETE", "") - print("success dmesg test") - else: + if not os.path.isfile('{}'.format(self.__syslog_dmesg_file)): self.pgObj.finish_test(self.params["testidctl"], self.params["testid"], "TEST_FAILED", "") - print("fail dmesg test") + return False + self.pgObj.upload_result_file(self.params["testidctl"], self.params["testid"], "{}".format(self.__syslog_dmesg_file), + "{}".format(self.__syslog_dmesg_file), "text/plain") + self.pgObj.finish_test(self.params["testidctl"], self.params["testid"], "TEST_COMPLETE", "") + return True diff --git a/test-cli/test/tests/qeeprom.py b/test-cli/test/tests/qeeprom.py index 7fc9fcd..7900381 100644 --- a/test-cli/test/tests/qeeprom.py +++ b/test-cli/test/tests/qeeprom.py @@ -1,46 +1,65 @@ -import sh import unittest - +import os class Qeeprom(unittest.TestCase): params = None - __position = None - __eeprompath = None __resultlist = None # resultlist is a python list of python dictionaries + __QEepromName = None + __i2cBus = None + __device = None # varlist: position, eeprompath def __init__(self, testname, testfunc, varlist): self.params = varlist super(Qeeprom, self).__init__(testfunc) self._testMethodDoc = testname + self.__xmlObj = varlist["xml"] + self.__QEepromName = varlist.get('name', 'qeeprom') + self.__i2cAddress = varlist.get('i2c_address', self.__xmlObj.getKeyVal(self.__QEepromName, "i2c_address", "0050")) + self.__i2cBus = varlist.get('i2c_bus', self.__xmlObj.getKeyVal(self.__QEepromName, "i2c_bus", "0")) + self.__device = '/sys/bus/i2c/devices/{}-{}/eeprom'.format(self.__i2cBus, self.__i2cAddress) + self.__resultlist = [] - if "position" in varlist: - self.__position = varlist["position"] - else: - raise Exception('position param inside Qeeprom must be defined') - if "eeprompath" in varlist: - self.__eeprompath = varlist["eeprompath"] - else: - raise Exception('eeprompath param inside Qeeprom must be defined') + + def __check_device(self): + if os.path.isfile(self.__device): + return True + return False + + def __eeprom_write(self, data): + try: + f = open(self.__device, "wb") + f.write(data) + f.close() + except IOError as Error: + return False, '{}'.format(Error.errno) + return True, '' + + def __eeprom_read(self, size): + try: + f = open(self.__device, "rb") + data = f.read(size) + f.close() + except IOError as Error: + return False, '{}'.format(Error.errno) + return True, data + def execute(self): - # generate some data - data_tx = "isee_test" - # write data into the eeprom - p = sh.dd(sh.echo(data_tx), "of=" + self.__eeprompath, "bs=1", "seek=" + self.__position) - if p.exit_code == 0: - # read data from the eeprom - p = sh.dd("if=" + self.__eeprompath, "bs=1", "skip=" + self.__position, "count=" + str(len(data_tx))) - if p.exit_code == 0: - data_rx = p.stdout.decode('ascii') - # compare both values - if data_rx != data_tx: - # Both data are different - self.fail("failed: mismatch between written and received values.") - else: - self.fail("failed: Unable to read from the EEPROM device.") - else: - self.fail("failed: Unable to write on the EEPROM device.") + if not self.__check_device(): + self.fail("cannot open device {}".format(self.__device)) + + data = bytes('AbcDeFgHijK098521', 'utf-8') + + v, w = self.__eeprom_write(data) + if not v: + self.fail("eeprom: {} write test failed".format(w)) + v, r = self.__eeprom_read(len(data)) + if not v: + self.fail("eeprom: {} read test failed".format(r)) + if r != data: + self.fail("mismatch between write and read bytes") + def getresults(self): return self.__resultlist diff --git a/test-cli/test/tests/qethernet.py b/test-cli/test/tests/qethernet.py index 81acef1..7d081a1 100644 --- a/test-cli/test/tests/qethernet.py +++ b/test-cli/test/tests/qethernet.py @@ -2,7 +2,11 @@ import unittest import sh import json import time - +import uuid +import iperf3 +import netifaces +from test.helpers.utils import save_json_to_disk +from test.helpers.utils import station2Port class Qethernet(unittest.TestCase): __serverip = None @@ -16,29 +20,66 @@ class Qethernet(unittest.TestCase): # varlist content: serverip, bwexpected, port def __init__(self, testname, testfunc, varlist): - # save the parameters list self.params = varlist - # configure the function to be executed when the test runs. "testfunc" is a name of a method inside this - # class, that in this situation, it can only be "execute". super(Qethernet, self).__init__(testfunc) - # validate and get the parameters - if "serverip" in varlist: - self.__serverip = varlist["serverip"] - else: - raise Exception('sip param inside Qethernet have been be defined') - if "bwexpected" in varlist: - self.__bwexpected = varlist["bwexpected"] - else: - raise Exception('bwexpected param inside Qethernet must be defined') - if "port" in varlist: - self.__port = varlist["port"] - else: - raise Exception('port param inside Qethernet must be defined') - self.__numbytestx = "10M" self._testMethodDoc = testname + self.__xmlObj = varlist["xml"] + self.__QEthName = varlist.get('name', 'qeth') + self.__loops = varlist.get('loops', self.__xmlObj.getKeyVal(self.__QEthName, "loops", "1")) + self.__port = varlist.get('port', self.__xmlObj.getKeyVal(self.__QEthName, "port", "5000")) + self.__bw = varlist.get('bwexpected', self.__xmlObj.getKeyVal(self.__QEthName, "bwexpected", "40.0")) + self.__serverip = varlist.get('serverip', self.__xmlObj.getKeyVal(self.__QEthName, "serverip", "localhost")) + self.__duration = varlist.get('duration', self.__xmlObj.getKeyVal(self.__QEthName, "duration", "10")) + self.__interface = varlist.get('interface', self.__xmlObj.getKeyVal(self.__QEthName, "interface", "eth0")) + self.__toPath = varlist.get('to', self.__xmlObj.getKeyVal(self.__QEthName, "to", "/mnt/station_ramdisk")) + self.__retriesCount = varlist.get('retries', self.__xmlObj.getKeyVal(self.__QEthName, "retries", "5")) + self.__waitRetryTime = varlist.get('wait_retry', self.__xmlObj.getKeyVal(self.__QEthName, "wait_retry", "10")) + self.__wifi_res_file = varlist.get('eth_res_file', self.__xmlObj.getKeyVal(self.__QEthName, "eth_res_file", "eth_test_{}.json")) + self.__wifi_st_file = varlist.get('eth_st_file', self.__xmlObj.getKeyVal(self.__QEthName, "eth_st_file", "eth_st_{}.json")) + self.__file_uuid = uuid.uuid4() + self.__wifi_res_file = self.__wifi_res_file.format(self.__file_uuid) + self.__wifi_st_file = self.__wifi_st_file.format(self.__file_uuid) + self.__resultlist = [] + def checkInterface(self, reqInterface): + ifaces = netifaces.interfaces() + for t in ifaces: + if t == reqInterface: + return True + return False + def execute(self): + self.__resultlist = [] + # check interfaces + if not self.checkInterface(self.__interface): + self.fail('Interface not found: {}'.format(self.__interface)) + + # Start Iperf + client = iperf3.Client() + client.duration = int(self.__duration) + client.server_hostname = self.__serverip + client.port = station2Port(self.__port) + count = int(self.__retriesCount) + while count > 0: + result = client.run() + if result.error == None: + if result.received_Mbps >= float(self.__bw) and result.sent_Mbps >= float(self.__bw): + save_json_to_disk(filePath='{}/{}'.format(self.__toPath, self.__wifi_res_file), + description='eth {} iperf3'.format(self.__interface), + mime='application/json', + json_data=result.json, + result=self.__resultlist) + return + else: + self.fail('bw fail: rx:{} tx:{}'.format(result.received_Mbps, result.sent_Mbps)) + else: + count = count - 1 + time.sleep(int(self.__waitRetryTime)) + + self.fail('qEth (max tries) Execution error: {}'.format(result.error)) + + def execute2(self): # execute iperf command against the server, but it implements attempts in case the server is busy iperfdone = False while not iperfdone: diff --git a/test-cli/test/tests/qmmcflash.py b/test-cli/test/tests/qmmcflash.py index f10757e..0f5a0c1 100644 --- a/test-cli/test/tests/qmmcflash.py +++ b/test-cli/test/tests/qmmcflash.py @@ -1,5 +1,10 @@ import unittest -import sh +import scanf +from scanf import scanf +from sh import mmc +from sh import ErrorReturnCode +from test.helpers.utils import save_file_to_disk +from test.helpers.utils import sys_read class Qmmcflash(unittest.TestCase): params = None @@ -8,8 +13,43 @@ class Qmmcflash(unittest.TestCase): self.params = varlist super(Qmmcflash, self).__init__(testfunc) self._testMethodDoc = testname - # TODO + self.__xmlObj = varlist["xml"] + self.__QeMMCName = varlist.get('name', 'qemmc') + self.__emmcDevice = varlist.get('device', self.__xmlObj.getKeyVal(self.__QeMMCName, "device", "mmcblk0")) + self.__toPath = varlist.get('to', self.__xmlObj.getKeyVal(self.__QeMMCName, "to", "/mnt/station_ramdisk")) + self.__mmc_res_file = varlist.get('emmc_res_file', self.__xmlObj.getKeyVal(self.__QeMMCName, "emmc_res_file", "emmc_status.txt")) + self.__mmcPort = varlist.get('mmc_port', self.__xmlObj.getKeyVal(self.__QeMMCName, "mmc_port", "0")) + self.__mmcID = varlist.get('mmc_id', self.__xmlObj.getKeyVal(self.__QeMMCName, "mmc_id", "0001")) + + self.__resultlist = [] def execute(self): - # TODO \ No newline at end of file + try: + dataOut = mmc('extcsd', 'read', '/dev/{}'.format(self.__emmcDevice)) + save_file_to_disk(filePath='{}/{}'.format(self.__toPath, self.__mmc_res_file), + description='eMMC health test', + mime='text/plain', + data=dataOut.stdout.decode('utf-8'), + result=self.__resultlist) + sysDevice = "/sys/bus/mmc/drivers/mmcblk/mmc{}:{}".format(self.__mmcPort, self.__mmcID) + r, data = sys_read("{}/life_time".format(sysDevice)) + if not r: + self.fail("emmc: life_time not found") + res = scanf("0x%d 0x%d", data) + if res[0] > 3 or res[1] > 3: + self.fail("emmc: review {} life_time > 3".format(sysDevice)) + r, data = sys_read("{}/pre_eol_info".format(sysDevice)) + if not r: + self.fail("emmc: pre_eol_info not found") + res = scanf("0x%d", data) + if res[0] != 1: + self.fail("emmc: review {} pre_eol_info != 1".format(sysDevice)) + except ErrorReturnCode as Error: + self.fail("emmc: failed {} ".format(Error.exit_code)) + + def getresults(self): + return self.__resultlist + + def gettextresult(self): + return "" \ No newline at end of file diff --git a/test-cli/test/tests/qnand.py b/test-cli/test/tests/qnand.py index 988ab60..6de1eaf 100644 --- a/test-cli/test/tests/qnand.py +++ b/test-cli/test/tests/qnand.py @@ -1,6 +1,7 @@ import unittest import sh - +import uuid +from test.helpers.utils import save_file_to_disk class Qnand(unittest.TestCase): params = None @@ -11,29 +12,34 @@ class Qnand(unittest.TestCase): def __init__(self, testname, testfunc, varlist): self.params = varlist super(Qnand, self).__init__(testfunc) - if "device" in varlist: - self.__device = varlist["device"] - else: - raise Exception('device param inside Qnand must be defined') self._testMethodDoc = testname + self.__xmlObj = varlist["xml"] + self.__QNandName = varlist.get('name', 'qnand') + self.__device = varlist.get('device', self.__xmlObj.getKeyVal(self.__QNandName, "device", "/dev/mtd0")) + self.__nand_res_file = varlist.get('nand_res_file', self.__xmlObj.getKeyVal(self.__QNandName, "nand_res_file", "nand_test_{}.txt")) + self.__toPath = varlist.get('to', self.__xmlObj.getKeyVal(self.__QNandName, "to", "/mnt/station_ramdisk")) + self.__file_uuid = uuid.uuid4() + self.__nand_res_file = self.__nand_res_file.format(self.__file_uuid) + nandtestPath = self.__xmlObj.getKeyVal("qnand", "nandtestPath", '/root/hwtest-files/nandtest"') + + if nandtestPath == '': + self.myNandTest = sh.nandtest + else: + self.myNandTest = sh.Command(nandtestPath) self.__resultlist = [] def execute(self): try: - p = sh.nandtest("-m", self.__device) - # save result - with open('/mnt/station_ramdisk/nand-nandtest.txt', 'w') as outfile: - n = outfile.write(p.stdout.decode('ascii')) - outfile.close() - self.__resultlist.append( - { - "description": "nandtest output", - "filepath": "/mnt/station_ramdisk/nand-nandtest.txt", - "mimetype": "text/plain" - } - ) - except sh.ErrorReturnCode as e: - self.fail("failed: could not complete nandtest command") + res = self.myNandTest("-m", self.__device) + save_file_to_disk(filePath='{}/{}'.format(self.__toPath, self.__nand_res_file), + description='nand {} test'.format(self.__device), + mime='text/plain', + data=res.stdout.decode('utf-8'), + result=self.__resultlist) + + except sh.ErrorReturnCode_1 as e: + self.fail("nandtest failed: {}".format(e.ErrorReturnCode.stdout)) + def getresults(self): return self.__resultlist diff --git a/test-cli/test/tests/qplc.py b/test-cli/test/tests/qplc.py new file mode 100644 index 0000000..01258a9 --- /dev/null +++ b/test-cli/test/tests/qplc.py @@ -0,0 +1,70 @@ +import shutil +import unittest +import os.path +import os +import sh + +from test.helpers.md5 import md5_file +from test.helpers.plc import dcpPLC + +class Qplc(unittest.TestCase): + params = None + __resultlist = None # resultlist is a python list of python dictionaries + __QPLCName = None + __plc = None + + def __init__(self, testname, testfunc, varlist): + self.params = varlist + super(Qplc, self).__init__(testfunc) + self._testMethodDoc = testname + self.__xmlObj = varlist["xml"] + + self.__QPLCName = varlist.get('name', 'qplc') + self.__firmware = varlist.get('firmware', self.__xmlObj.getKeyVal(self.__QPLCName, "firmware", "")) + self.__firmware_md5 = varlist.get('firmware_md5', self.__xmlObj.getKeyVal(self.__QPLCName, "firmware_md5", "")) + self.__factoryTool = varlist.get('factory_tool', self.__xmlObj.getKeyVal(self.__QPLCName, "factory_tool", "")) + self.__gen_ip = varlist.get('gen_ip', self.__xmlObj.getKeyVal(self.__QPLCName, "gen_ip", "0")) + self.__gen_mac = varlist.get('gen_mac', self.__xmlObj.getKeyVal(self.__QPLCName, "gen_mac", "0")) + self.__mtd_device = varlist.get('mtd_device', self.__xmlObj.getKeyVal(self.__QPLCName, "mtd_device", "/dev/mtd0")) + self.__plc = dcpPLC(self.__factoryTool, self.__mtd_device) + + self.__resultlist = [] + + + def checkfiles(self): + if not os.path.isfile('{}/{}'.format(self.__filepath_from, self.__file_source)): + return False, 'File test binary Not found {}/{}'.format(self.__filepath_from, self.__file_source) + if not os.path.isfile('{}/{}'.format(self.__filepath_from, self.__file_md5)): + return False, 'File test binary md5 Not found {}/{}'.format(self.__filepath_from, self.__file_md5) + if self.__check_mounted != '': + if not os.path.ismount('{}'.format(self.__check_mounted)): + return False, 'Required mounted failed: {}'.format(self.__path_to) + r, s = self.removefileIfExist('{}/{}'.format(self.__path_to, self.__file_source)) + if not r: + return r, s + return True, '' + + def __flashMemory(self): + self.__plc.setSaveFirmwareMode() + r, v = self.__plc.SaveFirmware(self.__firmware) + if not r: + self.fail(v) + + def execute(self): + # Check files + v, m = self.checkfiles() + if not v: + self.fail(m) + # do flash & verify + self.__flashMemory() + # do Plc boot + self.__plc.setBootMode() + # Wait plc goes UP + + + + def getresults(self): + return self.__resultlist + + def gettextresult(self): + return "" diff --git a/test-cli/test/tests/qram.py b/test-cli/test/tests/qram.py index 21a01c8..49d4d54 100644 --- a/test-cli/test/tests/qram.py +++ b/test-cli/test/tests/qram.py @@ -1,33 +1,59 @@ import unittest import sh - +# from test.helpers.iseelogger import MeasureTime +# from test.helpers.iseelogger import logObj +from test.helpers.utils import save_file_to_disk class Qram(unittest.TestCase): params = None - __memsize = "10M" - __loops = "1" - __resultlist = None # resultlist is a python list of python dictionaries + __memsize = None + __loops = None + __resultlist = [] # resultlist is a python list of python dictionaries # varlist: memsize, loops def __init__(self, testname, testfunc, varlist): self.params = varlist super(Qram, self).__init__(testfunc) - if "memsize" in varlist: - self.__memsize = varlist["memsize"] - else: - raise Exception('memsize param inside Qram must be defined') - if "loops" in varlist: - self.__loops = varlist["loops"] - else: - raise Exception('loops param inside Qram must be defined') self._testMethodDoc = testname - self.__resultlist = [] + self.__xmlObj = varlist["xml"] + + self.__QramName = varlist.get('name', 'qram') + self.__loops = varlist.get('loops', self.__xmlObj.getKeyVal(self.__QramName, "loops", "1")) + self.__memsize = varlist.get('memsize', self.__xmlObj.getKeyVal(self.__QramName, "memsize", "50M")) + self.__toPath = varlist.get('to', self.__xmlObj.getKeyVal(self.__QramName, "to", "/mnt/station_ramdisk")) + self.__ram_res_file = varlist.get('ram_res_file', self.__xmlObj.getKeyVal(self.__QramName, "ram_res_file", "ram_res.txt")) + + self.__dummytest = varlist.get('dummytest', self.__xmlObj.getKeyVal(self.__QramName, "dummytest", "0")) + self.__dummyresult = varlist.get('dummytestresult', self.__xmlObj.getKeyVal(self.__QramName, "dummytest", "0")) + + memtesterPath = self.__xmlObj.getKeyVal(self.__QramName, "memtesterPath", '') + + if memtesterPath == '': + self.myMemtester = sh.memtester + else: + self.myMemtester = sh.Command(memtesterPath) def execute(self): + self.__resultlist = [] try: - p = sh.memtester(self.__memsize, "1", _out="/dev/null") + # mytime = MeasureTime() + res = self.myMemtester(self.__memsize, '{}'.format(self.__loops)) + save_file_to_disk(filePath='{}/{}'.format(self.__toPath, self.__ram_res_file), + description='Ram result test', + mime='text/plain', + data=res.stdout.decode('utf-8'), + result=self.__resultlist) + # mytime.stop() except sh.ErrorReturnCode as e: - self.fail("failed: could not complete memtester command") + save_file_to_disk(filePath='{}/{}'.format(self.__toPath, self.__ram_res_file), + description='Ram result test', + mime='text/plain', + data=e.stdout.decode('utf-8'), + result=self.__resultlist) + self.fail("failed: memtester {}::{}".format(str(e.exit_code), e.stdout.decode('utf-8'))) + + except Exception as details: + self.fail('Error: {}'.format(details)) def getresults(self): return self.__resultlist diff --git a/test-cli/test/tests/qusb.py b/test-cli/test/tests/qusb.py index 6302012..3182685 100644 --- a/test-cli/test/tests/qusb.py +++ b/test-cli/test/tests/qusb.py @@ -1,91 +1,90 @@ -import sh +import shutil import unittest -from test.helpers.usb import USBDevices import os.path +import os +import sh +from test.helpers.md5 import md5_file class Qusb(unittest.TestCase): params = None __resultlist = None # resultlist is a python list of python dictionaries + __QusbName = None def __init__(self, testname, testfunc, varlist): self.params = varlist super(Qusb, self).__init__(testfunc) self._testMethodDoc = testname - if "repetitions" in varlist: - self.__repetitions = varlist["repetitions"] - else: - raise Exception('repetitions param inside Qusb must be defined') + self.__xmlObj = varlist["xml"] + + self.__QusbName = varlist.get('name', 'qusb') + self.__loops = varlist.get('loops', self.__xmlObj.getKeyVal(self.__QusbName, "loops", "3")) + self.__filepath_from = varlist.get('path', self.__xmlObj.getKeyVal(self.__QusbName, "path", "/root/hwtest-files")) + self.__file_source = varlist.get('file', self.__xmlObj.getKeyVal(self.__QusbName, "file", "usb-test.bin")) + self.__file_md5 = varlist.get('file_md5', self.__xmlObj.getKeyVal(self.__QusbName, "file_md5", "usb-test.bin.md5")) + self.__path_to = varlist.get('pathto', self.__xmlObj.getKeyVal(self.__QusbName, "pathto", "/mnt/test/disk2")) + self.__check_mounted = varlist.get('check_mounted', self.__xmlObj.getKeyVal(self.__QusbName, "check_mounted", "")) + self.__resultlist = [] - def execute(self): - # get usb device - dev_obj = USBDevices(self.params["xml"]) - if dev_obj.getMassStorage(): - device = dev_obj.getMassStorage()['disk'] + "1" - else: - self.fail("failed: No USB memory found.") - # check if the device is mounted, and umount it - try: - p = sh.findmnt("-n", device) - if p.exit_code == 0: - sh.umount(device) - except sh.ErrorReturnCode as e: - # error = 1 means "no found" - pass - # mount the device - sh.mkdir("-p", "/mnt/station_ramdisk/pendrive") - p = sh.mount(device, "/mnt/station_ramdisk/pendrive") - if p.exit_code != 0: - self.fail("failed: Unable to mount the USB memory device.") - # execute test - for i in range(int(self.__repetitions)): - # copy files + def removefileIfExist(self, fname): + if os.path.exists(fname): try: - p = sh.cp("/var/lib/hwtest-files/usbdatatest.bin", - "/var/lib/hwtest-files/usbdatatest.bin.md5", - "/mnt/station_ramdisk/pendrive") - except sh.ErrorReturnCode as e: - try: - sh.umount("/mnt/station_ramdisk/pendrive") - except sh.ErrorReturnCode: - pass - sh.rmdir("/mnt/station_ramdisk/pendrive") - self.fail("failed: Unable to copy files to the USB memory device.") - # check if the device is still mounted - if not os.path.ismount("/mnt/station_ramdisk/pendrive"): - sh.rm("/mnt/station_ramdisk/pendrive/*") - sh.rmdir("/mnt/station_ramdisk/pendrive") - self.fail("failed: USB device unmounted during/after copying files.") - # check MD5 - try: - p = sh.md5sum("/mnt/station_ramdisk/pendrive/usbdatatest.bin") - except sh.ErrorReturnCode as e: - try: - sh.umount("/mnt/station_ramdisk/pendrive") - except sh.ErrorReturnCode: - pass - sh.rmdir("/mnt/station_ramdisk/pendrive") - self.fail("failed: Unable to calculate MD5 of the copied file.") - newmd5 = p.stdout.decode().split(" ")[0] - with open('/mnt/station_ramdisk/pendrive/usbdatatest.bin.md5', 'r') as outfile: - oldmd5 = outfile.read().rstrip("\n") - outfile.close() - if newmd5 != oldmd5: - try: - sh.umount("/mnt/station_ramdisk/pendrive") - except sh.ErrorReturnCode: - pass - sh.rmdir("/mnt/station_ramdisk/pendrive") - self.fail("failed: MD5 check failed.") - # delete copied files - sh.rm("-f", "/mnt/station_ramdisk/pendrive/usbdatatest.bin", "/mnt/station_ramdisk/pendrive/usbdatatest.bin.md5") - # Finish + os.remove(fname) + except OSError as error: + return False, str(error) + return True, '' + + def checkfiles(self): + if not os.path.isfile('{}/{}'.format(self.__filepath_from, self.__file_source)): + return False, 'File test binary Not found {}/{}'.format(self.__filepath_from, self.__file_source) + if not os.path.isfile('{}/{}'.format(self.__filepath_from, self.__file_md5)): + return False, 'File test binary md5 Not found {}/{}'.format(self.__filepath_from, self.__file_md5) + if self.__check_mounted != '': + if not os.path.ismount('{}'.format(self.__check_mounted)): + return False, 'Required mounted failed: {}'.format(self.__path_to) + r, s = self.removefileIfExist('{}/{}'.format(self.__path_to, self.__file_source)) + if not r: + return r, s + return True, '' + + def getTestFile_md5(self, fname): + t = '' + with open('{}'.format(fname), 'r') as outfile: + t = outfile.read().rstrip("\n") + outfile.close() + return t + + def ExecuteTranfer(self): try: - sh.umount("/mnt/station_ramdisk/pendrive") - except sh.ErrorReturnCode: - pass - sh.rmdir("/mnt/station_ramdisk/pendrive") + originalMD5 = self.getTestFile_md5('{}/{}'.format(self.__filepath_from, self.__file_md5)) + if originalMD5 == '': + self.fail('MD5 file {}/{} Not contain any md5'.format(self.__filepath_from, self.__file_md5)) + # shutil.copy2('{}/{}'.format(self.__filepath_from, self.__file_source), '{}'.format(self.__path_to)) + sh.cp('{}/{}'.format(self.__filepath_from, self.__file_source), '{}'.format(self.__path_to)) + sh.sync() + md5val = md5_file('{}/{}'.format(self.__path_to, self.__file_source)) + self.removefileIfExist('{}/{}'.format(self.__path_to, self.__file_source)) + if originalMD5 != md5val: + return False, 'md5 check failed {}<>{}'.format(originalMD5, md5val) + except OSError as why: + return False,'Error: {} tranfer failed'.format(why.errno) + except Exception as details: + return False, 'USB Exception: {} tranfer failed'.format(details) + return True, '' + + def execute(self): + v, m = self.checkfiles() + if not v: + self.fail(m) + countLoops = int(self.__loops) + while countLoops > 0: + res, msg = self.ExecuteTranfer() + if not res: + res, msg = self.ExecuteTranfer() + if not res: + self.fail(msg) + countLoops = countLoops - 1 def getresults(self): return self.__resultlist diff --git a/test-cli/test/tests/qusbdual.py b/test-cli/test/tests/qusbdual.py deleted file mode 100644 index 05b22c3..0000000 --- a/test-cli/test/tests/qusbdual.py +++ /dev/null @@ -1,90 +0,0 @@ -import sh -import unittest -import os.path -import time - - -class Qusbdual(unittest.TestCase): - params = None - __resultlist = None # resultlist is a python list of python dictionaries - - def __init__(self, testname, testfunc, varlist): - self.params = varlist - super(Qusbdual, self).__init__(testfunc) - self._testMethodDoc = testname - if "repetitions" in varlist: - self.__repetitions = varlist["repetitions"] - else: - raise Exception('repetitions param inside Qusbdual must be defined') - self.__resultlist = [] - - def execute(self): - # check if file-as-filesystem exists - if not os.path.isfile('/var/lib/hwtest-files/mass-otg-test.img'): - self.fail("failed: Unable to find file-as-filesystem image.") - # generate mass storage gadget - p = sh.modprobe("g_mass_storage", "file=/var/lib/hwtest-files/mass-otg-test.img") - if p.exit_code != 0: - self.fail("failed: Unable to create a mass storage gadget.") - # wait to detect the new device - time.sleep(3) - # find the mass storage device - try: - p = sh.grep(sh.lsblk("-So", "NAME,VENDOR"), "Linux") - except sh.ErrorReturnCode: - sh.modprobe("-r", "g_mass_storage") - self.fail("failed: could not find any mass storage gadget") - device = p.stdout.decode().split(" ")[0] - # mount the mass storage gadget - sh.mkdir("-p", "/mnt/station_ramdisk/hdd_gadget") - p = sh.mount("-o", "ro", "/dev/" + device, "/mnt/station_ramdisk/hdd_gadget") - if p.exit_code != 0: - sh.modprobe("-r", "g_mass_storage") - self.fail("failed: Unable to mount the mass storage gadget.") - # execute test - for i in range(int(self.__repetitions)): - # copy files - try: - p = sh.cp("/mnt/station_ramdisk/hdd_gadget/usb-test.bin", - "/mnt/station_ramdisk/hdd_gadget/usb-test.bin.md5", - "/mnt/station_nfsdisk/") - except sh.ErrorReturnCode as e: - sh.umount("/mnt/station_ramdisk/hdd_gadget") - sh.rmdir("/mnt/station_ramdisk/hdd_gadget") - sh.modprobe("-r", "g_mass_storage") - self.fail("failed: Unable to copy files through USB.") - # check if the device is still mounted - if not os.path.ismount("/mnt/station_ramdisk/hdd_gadget"): - sh.rm("/mnt/station_ramdisk/hdd_gadget/*") - sh.rmdir("/mnt/station_ramdisk/hdd_gadget") - sh.modprobe("-r", "g_mass_storage") - self.fail("failed: USB device unmounted during/after copying files.") - # Check md5 - try: - p = sh.md5sum("/mnt/station_nfsdisk/usb-test.bin") - except sh.ErrorReturnCode as e: - sh.umount("/mnt/station_ramdisk/hdd_gadget") - sh.rmdir("/mnt/station_ramdisk/hdd_gadget") - sh.modprobe("-r", "g_mass_storage") - self.fail("failed: Unable to calculate MD5 of the copied file.") - newmd5 = p.stdout.decode().split(" ")[0] - with open('/mnt/station_ramdisk/hdd_gadget/usb-test.bin.md5', 'r') as outfile: - oldmd5 = outfile.read().rstrip("\n") - outfile.close() - if newmd5 != oldmd5: - sh.umount("/mnt/station_ramdisk/hdd_gadget") - sh.rmdir("/mnt/station_ramdisk/hdd_gadget") - sh.modprobe("-r", "g_mass_storage") - self.fail("failed: MD5 check failed.") - # delete copied files - sh.rm("-f", "/mnt/station_nfsdisk/usb-test.bin", "/mnt/station_nfsdisk/usb-test.bin.md5") - # Finish - sh.umount("/mnt/station_ramdisk/hdd_gadget") - sh.rmdir("/mnt/station_ramdisk/hdd_gadget") - sh.modprobe("-r", "g_mass_storage") - - def getresults(self): - return self.__resultlist - - def gettextresult(self): - return "" diff --git a/test-cli/test/tests/qwifi.py b/test-cli/test/tests/qwifi.py index 3dd9e38..4695041 100644 --- a/test-cli/test/tests/qwifi.py +++ b/test-cli/test/tests/qwifi.py @@ -1,9 +1,11 @@ import unittest -import sh -import re -import json import time - +import uuid +import iperf3 +import netifaces +from test.helpers.iw import iwScan +from test.helpers.utils import save_json_to_disk +from test.helpers.utils import station2Port class Qwifi(unittest.TestCase): __serverip = None @@ -19,81 +21,76 @@ class Qwifi(unittest.TestCase): def __init__(self, testname, testfunc, varlist): self.params = varlist super(Qwifi, self).__init__(testfunc) - if "serverip" in varlist: - self.__serverip = varlist["serverip"] - else: - raise Exception('serverip param inside Qwifi have been be defined') - if "bwexpected" in varlist: - self.__bwexpected = varlist["bwexpected"] - else: - raise Exception('OKBW param inside Qwifi must be defined') - if "port" in varlist: - self.__port = varlist["port"] - else: - raise Exception('port param inside Qwifi must be defined') - self.__numbytestx = "10M" self._testMethodDoc = testname + self.__xmlObj = varlist["xml"] + self.__QwifiName = varlist.get('name', 'qwifi') + self.__loops = varlist.get('loops', self.__xmlObj.getKeyVal(self.__QwifiName, "loops", "1")) + self.__port = varlist.get('port', self.__xmlObj.getKeyVal(self.__QwifiName, "port", "5000")) + self.__bw = varlist.get('bwexpected', self.__xmlObj.getKeyVal(self.__QwifiName, "bwexpected", "5.0")) + self.__serverip = varlist.get('serverip', self.__xmlObj.getKeyVal(self.__QwifiName, "serverip", "localhost")) + self.__duration = varlist.get('duration', self.__xmlObj.getKeyVal(self.__QwifiName, "duration", "10")) + self.__interface = varlist.get('interface', self.__xmlObj.getKeyVal(self.__QwifiName, "interface", "wlan0")) + self.__toPath = varlist.get('to', self.__xmlObj.getKeyVal(self.__QwifiName, "to", "/mnt/station_ramdisk")) + self.__retriesCount = varlist.get('retries', self.__xmlObj.getKeyVal(self.__QwifiName, "retries", "5")) + self.__waitRetryTime = varlist.get('wait_retry', self.__xmlObj.getKeyVal(self.__QwifiName, "wait_retry", "10")) + self.__wifi_res_file = varlist.get('wifi_res_file', self.__xmlObj.getKeyVal(self.__QwifiName, "wifi_res_file", "wifi_test_{}.json")) + self.__wifi_st_file = varlist.get('wifi_st_file', self.__xmlObj.getKeyVal(self.__QwifiName, "wifi_st_file", "wifi_st_{}.json")) + self.__file_uuid = uuid.uuid4() + self.__wifi_res_file = self.__wifi_res_file.format(self.__file_uuid) + self.__wifi_st_file = self.__wifi_st_file.format(self.__file_uuid) self.__resultlist = [] - def execute(self): - # check if the board is connected to the router by wifi - p = sh.iw("wlan0", "link") - if p.exit_code == 0: - # get the first line of the output stream - out1 = p.stdout.decode('ascii').splitlines()[0] - if out1 != "Not connected.": - # check if the board has ip in the wlan0 interface - p = sh.ifconfig("wlan0") - if p.exit_code == 0: - # check if wlan0 has an IP - result = re.search( - 'inet addr:(?!127\.0{1,3}\.0{1,3}\.0{0,2}1$)((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)', - p.stdout.decode('ascii')) - if result: - # execute iperf command against the server, but it implements attempts in case the server is busy - iperfdone = False - while not iperfdone: - try: - p = sh.iperf3("-c", self.__serverip, "-n", self.__numbytestx, "-f", "m", "-p", self.__port, - "-J", _timeout=20) - iperfdone = True - except sh.TimeoutException: - self.fail("failed: iperf timeout reached") - except sh.ErrorReturnCode: - time.sleep(self.timebetweenattempts) - - # check if it was executed succesfully - if p.exit_code == 0: - if p.stdout == "": - self.fail("failed: error executing iperf command") - # analyze output string - data = json.loads(p.stdout.decode('ascii')) - self.__bwreal = float(data['end']['sum_received']['bits_per_second']) / 1024 / 1024 - # save result file - with open('/mnt/station_ramdisk/wifi-iperf3.json', 'w') as outfile: - json.dump(data, outfile, indent=4) - outfile.close() - self.__resultlist.append( - { - "description": "iperf3 output", - "filepath": "/mnt/station_ramdisk/wifi-iperf3.json", - "mimetype": "application/json" - } - ) + def checkInterface(self, reqInterface): + ifaces = netifaces.interfaces() + for t in ifaces: + if t == reqInterface: + return True + return False - # check if BW is in the expected range - if self.__bwreal < float(self.__bwexpected): - self.fail("failed: speed is lower than expected. Speed(Mbits/s): " + str(self.__bwreal)) - else: - self.fail("failed: could not complete iperf3 command") - else: - self.fail("failed: wlan0 interface doesn't have any ip address.") + def execute(self): + self.__resultlist = [] + stationList = {} + # check interfaces + if not self.checkInterface(self.__interface): + self.fail('Interface not found: {}'.format(self.__interface)) + # scan networks + scanner = iwScan(self.__interface) + if scanner.scan(): + stationList = scanner.getStations() + # check if we are connected + if not scanner.findConnected(): + self.fail('Not connected to test AP') + else: + strError = scanner.getLastError() + self.fail('qWifi scanner Execution error: {}'.format(strError)) + # Start Iperf + client = iperf3.Client() + client.duration = int(self.__duration) + client.server_hostname = self.__serverip + client.port = station2Port(self.__port) + count = int(self.__retriesCount) + while count > 0: + result = client.run() + if result.error == None: + if result.received_Mbps >= float(self.__bw) and result.sent_Mbps >= float(self.__bw): + save_json_to_disk(filePath='{}/{}'.format(self.__toPath, self.__wifi_st_file), + description='wifi scan', + mime='application/json', + json_data=stationList, + result=self.__resultlist) + save_json_to_disk(filePath='{}/{}'.format(self.__toPath, self.__wifi_res_file), + description='wifi {} iperf3'.format(self.__interface), + mime='application/json', + json_data=result.json, + result=self.__resultlist) + return else: - self.fail("failed: could not complete ifconfig command.") + self.fail('bw fail: rx:{} tx:{}'.format(result.received_Mbps, result.sent_Mbps)) else: - self.fail("failed: wifi module is not connected to the router.") - else: - self.fail("failed: could not execute iw command") + count = count - 1 + time.sleep(int(self.__waitRetryTime)) + + self.fail('qWifi (max tries) Execution error: {}'.format(result.error)) def getresults(self): return self.__resultlist -- cgit v1.1 From 227d9783fe8327b84ac3b0e032f012ba144816f8 Mon Sep 17 00:00:00 2001 From: Manel Caro Date: Fri, 31 Jul 2020 13:58:41 +0200 Subject: IGEP0048: added plc test --- test-cli/test/helpers/plc.py | 26 ++++++++++++++--- test-cli/test/helpers/testsrv_db.py | 13 +++++++++ test-cli/test/tests/qamper.py | 2 +- test-cli/test/tests/qplc.py | 58 +++++++++++++++++++++++++++---------- 4 files changed, 78 insertions(+), 21 deletions(-) (limited to 'test-cli/test') diff --git a/test-cli/test/helpers/plc.py b/test-cli/test/helpers/plc.py index 3b00934..b1ec382 100644 --- a/test-cli/test/helpers/plc.py +++ b/test-cli/test/helpers/plc.py @@ -1,10 +1,10 @@ import sh from sh import flashcp -from sh import flash_erase +from sh import flash_eraseall from sh import ErrorReturnCode from sh import Command from test.helpers.gpio import gpio - +import time class dcpPLC(object): __nReset = None @@ -33,10 +33,18 @@ class dcpPLC(object): self.__nRest = gpio('75', 'out', '1') self.__nRest = gpio('69', 'out', '1') + def setPLCReset(self): + self.__nRest = gpio('75', 'out', '0') + self.__nRest = gpio('69', 'out', '0') + time.sleep(0.25) + self.__nRest = gpio('69', 'out', '1') + self.__nRest = gpio('75', 'out', '1') + + def SaveFirmware(self, firmare): self.setSaveFirmwareMode() try: - flash_erase(self.__mtd_device) + flash_eraseall(self.__mtd_device) flashcp(firmare, self.__mtd_device) except ErrorReturnCode as Error: return False, "plc flash firmware failed {} ".format(Error.exit_code) @@ -44,11 +52,21 @@ class dcpPLC(object): def set_plc (self, var, value, password): try: - self.__myConfigTool("-o", "SET", "-p", "{}".format(var), '{}'.format(value), "-w", "{}".format(password)) + res = self.__myConfigTool("-o", "SET", "-p", "{}={}".format(var, value), "-w", "{}".format(password)) + print(res) except ErrorReturnCode as Error: return False, "set var failed {} {}".format(var,Error.exit_code) return True, '' + def set_plc2 (self, var1, value1,var2, value2, password): + try: + res = self.__myConfigTool("-o", "SET", "-p", "{}={}".format(var1, value1), "-p", "{}={}".format(var2, value2), "-w", "{}".format(password)) + print(res) + except ErrorReturnCode as Error: + return False, "set var failed {}".format(Error.exit_code) + return True, '' + + def get_plc (self, var, value, password): try: self.__myConfigTool("-o", "GET", "-p", "{}".format(var), '{}'.format(value), "-w", "{}".format(password)) diff --git a/test-cli/test/helpers/testsrv_db.py b/test-cli/test/helpers/testsrv_db.py index c2b2276..556c246 100644 --- a/test-cli/test/helpers/testsrv_db.py +++ b/test-cli/test/helpers/testsrv_db.py @@ -132,6 +132,19 @@ class TestSrv_Database(object): # print(r) return None + + def get_plc_macaddr(self, board_uuid): + sql = "SELECT * FROM isee.f_get_plcmac(\'{}\')".format(board_uuid) + # print('>>>' + sql) + try: + res = self.__sqlObject.db_execute_query(sql) + return res, '' + except Exception as err: + r = find_between(str(err), '#', '#') + print(r) + return None, r + + def get_board_macaddr(self, board_uuid): sql = "SELECT * FROM isee.f_get_board_macaddr('{}')".format(board_uuid) # print('>>>' + sql) diff --git a/test-cli/test/tests/qamper.py b/test-cli/test/tests/qamper.py index df340eb..96b673c 100644 --- a/test-cli/test/tests/qamper.py +++ b/test-cli/test/tests/qamper.py @@ -39,7 +39,7 @@ class Qamper(unittest.TestCase): ) def execute(self): - if self.dummytest: + if self.dummytest == '1': self.current = "0.0" self.saveresultinfile(self.current) return diff --git a/test-cli/test/tests/qplc.py b/test-cli/test/tests/qplc.py index 01258a9..a70ae3a 100644 --- a/test-cli/test/tests/qplc.py +++ b/test-cli/test/tests/qplc.py @@ -3,21 +3,26 @@ import unittest import os.path import os import sh +import stat from test.helpers.md5 import md5_file from test.helpers.plc import dcpPLC +from test.helpers.iseelogger import logObj class Qplc(unittest.TestCase): params = None __resultlist = None # resultlist is a python list of python dictionaries __QPLCName = None __plc = None + __board_uuid = None def __init__(self, testname, testfunc, varlist): self.params = varlist super(Qplc, self).__init__(testfunc) self._testMethodDoc = testname self.__xmlObj = varlist["xml"] + self.__psdbObj = varlist["db"] + self.__board_uuid = varlist["boarduuid"] self.__QPLCName = varlist.get('name', 'qplc') self.__firmware = varlist.get('firmware', self.__xmlObj.getKeyVal(self.__QPLCName, "firmware", "")) @@ -26,27 +31,32 @@ class Qplc(unittest.TestCase): self.__gen_ip = varlist.get('gen_ip', self.__xmlObj.getKeyVal(self.__QPLCName, "gen_ip", "0")) self.__gen_mac = varlist.get('gen_mac', self.__xmlObj.getKeyVal(self.__QPLCName, "gen_mac", "0")) self.__mtd_device = varlist.get('mtd_device', self.__xmlObj.getKeyVal(self.__QPLCName, "mtd_device", "/dev/mtd0")) + self.__firmware_Path = varlist.get('firmwarepath', self.__xmlObj.getKeyVal(self.__QPLCName, "firmwarepath", "/root/hwtest-files/firmware")) + self.__plc_test_ip = varlist.get('plc_test_ip', self.__xmlObj.getKeyVal(self.__QPLCName, "plc_test_ip", "192.168.60.91")) + self.__skipflash = varlist.get('skipflash', self.__xmlObj.getKeyVal(self.__QPLCName, "skipflash", "0")) self.__plc = dcpPLC(self.__factoryTool, self.__mtd_device) - + self.__factory_password = varlist.get('factory_password', self.__xmlObj.getKeyVal(self.__QPLCName, "factory_password", "0")) + self.__firmware_password = varlist.get('firmware_password', self.__xmlObj.getKeyVal(self.__QPLCName, "firmware_password", "0")) self.__resultlist = [] def checkfiles(self): - if not os.path.isfile('{}/{}'.format(self.__filepath_from, self.__file_source)): - return False, 'File test binary Not found {}/{}'.format(self.__filepath_from, self.__file_source) - if not os.path.isfile('{}/{}'.format(self.__filepath_from, self.__file_md5)): - return False, 'File test binary md5 Not found {}/{}'.format(self.__filepath_from, self.__file_md5) - if self.__check_mounted != '': - if not os.path.ismount('{}'.format(self.__check_mounted)): - return False, 'Required mounted failed: {}'.format(self.__path_to) - r, s = self.removefileIfExist('{}/{}'.format(self.__path_to, self.__file_source)) - if not r: - return r, s + if not os.path.isfile(self.__factoryTool): + return False, 'Factory tool Not found {}/{}'.format(self.__factoryTool) + if not os.path.isfile('{}/{}'.format(self.__firmware_Path, self.__firmware)): + return False, 'Firmware Not found {}/{}'.format(self.__firmware_Path, self.__firmware) + if not os.path.isfile('{}/{}'.format(self.__firmware_Path, self.__firmware_md5)): + return False, 'Firmware md5 Not found {}/{}'.format(self.__firmware_Path, self.__firmware_md5) + try: + mode = os.stat(self.__mtd_device).st_mode; + if not stat.S_ISCHR(mode): + return False, 'No device {} found'.format(self.__mtd_device) + except: + return False, 'No device {} found'.format(self.__mtd_device) return True, '' def __flashMemory(self): - self.__plc.setSaveFirmwareMode() - r, v = self.__plc.SaveFirmware(self.__firmware) + r, v = self.__plc.SaveFirmware('{}/{}'.format(self.__firmware_Path, self.__firmware)) if not r: self.fail(v) @@ -56,12 +66,28 @@ class Qplc(unittest.TestCase): if not v: self.fail(m) # do flash & verify - self.__flashMemory() + if self.__skipflash == '0': + self.__flashMemory() # do Plc boot self.__plc.setBootMode() # Wait plc goes UP - - + if self.__gen_mac: + res, v = self.__psdbObj.get_plc_macaddr(self.__board_uuid) + if res == None and v == 'MAC limit by uuid': + self.fail('MAC limit by uuid') + elif res == None: + self.fail('BUG: ?????') + logObj.getlogger().info("MAC {}".format(res[0])) + plcMAC = res[0][0] + self.__plc.set_plc2('SYSTEM.PRODUCTION.SECTOR0_UNLOCK_PASSWORD', + self.__factory_password, + 'SYSTEM.PRODUCTION.MAC_ADDR', + '{}'.format(plcMAC), + self.__firmware_password) + #self.__plc.set_plc('SYSTEM.PRODUCTION.SECTOR0_UNLOCK_PASSWORD', self.__factory_password, self.__firmware_password) + #plcMAC = res[0][0] + #self.__plc.set_plc('SYSTEM.PRODUCTION.MAC_ADDR', '{}'.format(plcMAC), self.__firmware_password) + self.__plc.setPLCReset() def getresults(self): return self.__resultlist -- cgit v1.1 From f5f3398291c40bcf0a8fdedb48d4821e8e331c3c Mon Sep 17 00:00:00 2001 From: Hector Fernandez Date: Thu, 20 Aug 2020 14:17:49 +0200 Subject: Added ping check in PLC test. --- test-cli/test/tests/qplc.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) (limited to 'test-cli/test') diff --git a/test-cli/test/tests/qplc.py b/test-cli/test/tests/qplc.py index a70ae3a..27bbbea 100644 --- a/test-cli/test/tests/qplc.py +++ b/test-cli/test/tests/qplc.py @@ -4,6 +4,8 @@ import os.path import os import sh import stat +import time +import ping3 from test.helpers.md5 import md5_file from test.helpers.plc import dcpPLC @@ -32,11 +34,12 @@ class Qplc(unittest.TestCase): self.__gen_mac = varlist.get('gen_mac', self.__xmlObj.getKeyVal(self.__QPLCName, "gen_mac", "0")) self.__mtd_device = varlist.get('mtd_device', self.__xmlObj.getKeyVal(self.__QPLCName, "mtd_device", "/dev/mtd0")) self.__firmware_Path = varlist.get('firmwarepath', self.__xmlObj.getKeyVal(self.__QPLCName, "firmwarepath", "/root/hwtest-files/firmware")) - self.__plc_test_ip = varlist.get('plc_test_ip', self.__xmlObj.getKeyVal(self.__QPLCName, "plc_test_ip", "192.168.60.91")) + self.__plc_test_ip = varlist.get('plc_test_ip', self.__xmlObj.getKeyVal(self.__QPLCName, "plc_test_ip", "10.10.1.254")) self.__skipflash = varlist.get('skipflash', self.__xmlObj.getKeyVal(self.__QPLCName, "skipflash", "0")) self.__plc = dcpPLC(self.__factoryTool, self.__mtd_device) self.__factory_password = varlist.get('factory_password', self.__xmlObj.getKeyVal(self.__QPLCName, "factory_password", "0")) self.__firmware_password = varlist.get('firmware_password', self.__xmlObj.getKeyVal(self.__QPLCName, "firmware_password", "0")) + self.__plc_reset_wait = varlist.get('plc_reset_wait', self.__xmlObj.getKeyVal(self.__QPLCName, "plc_reset_wait", "60")) self.__resultlist = [] @@ -88,6 +91,14 @@ class Qplc(unittest.TestCase): #plcMAC = res[0][0] #self.__plc.set_plc('SYSTEM.PRODUCTION.MAC_ADDR', '{}'.format(plcMAC), self.__firmware_password) self.__plc.setPLCReset() + time.sleep(int(self.__plc_reset_wait)) + # ping against the GPLC0000 board + ping3.EXCEPTIONS = True + try: + ping3.ping(self.__plc_test_ip, timeout=0.1) + except: + self.fail('PLC ping timeout') + def getresults(self): return self.__resultlist -- cgit v1.1 From 8765219910c95d0712ac0b2c27d33fd7a21fe3b8 Mon Sep 17 00:00:00 2001 From: Hector Fernandez Date: Mon, 14 Sep 2020 17:40:45 +0200 Subject: IGEP0048: Solved PLC test error. The PLC MAC address can be changed now. --- test-cli/test/helpers/plc.py | 4 ++-- test-cli/test/tests/qplc.py | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) (limited to 'test-cli/test') diff --git a/test-cli/test/helpers/plc.py b/test-cli/test/helpers/plc.py index b1ec382..c9ef774 100644 --- a/test-cli/test/helpers/plc.py +++ b/test-cli/test/helpers/plc.py @@ -36,7 +36,7 @@ class dcpPLC(object): def setPLCReset(self): self.__nRest = gpio('75', 'out', '0') self.__nRest = gpio('69', 'out', '0') - time.sleep(0.25) + time.sleep(1) self.__nRest = gpio('69', 'out', '1') self.__nRest = gpio('75', 'out', '1') @@ -58,7 +58,7 @@ class dcpPLC(object): return False, "set var failed {} {}".format(var,Error.exit_code) return True, '' - def set_plc2 (self, var1, value1,var2, value2, password): + def set_plc2 (self, var1, value1, var2, value2, password): try: res = self.__myConfigTool("-o", "SET", "-p", "{}={}".format(var1, value1), "-p", "{}={}".format(var2, value2), "-w", "{}".format(password)) print(res) diff --git a/test-cli/test/tests/qplc.py b/test-cli/test/tests/qplc.py index 27bbbea..48d600a 100644 --- a/test-cli/test/tests/qplc.py +++ b/test-cli/test/tests/qplc.py @@ -82,6 +82,7 @@ class Qplc(unittest.TestCase): self.fail('BUG: ?????') logObj.getlogger().info("MAC {}".format(res[0])) plcMAC = res[0][0] + time.sleep(12) self.__plc.set_plc2('SYSTEM.PRODUCTION.SECTOR0_UNLOCK_PASSWORD', self.__factory_password, 'SYSTEM.PRODUCTION.MAC_ADDR', -- cgit v1.1 From 6550286c1f6ce5b1dbfc718b5566af3012ab538a Mon Sep 17 00:00:00 2001 From: Hector Fernandez Date: Tue, 15 Sep 2020 16:29:14 +0200 Subject: IGEP0048: PLC test: Variable IP of the connected PLC. Use discover before changing MAC address. --- test-cli/test/helpers/plc.py | 23 +++++++++++++++-------- test-cli/test/tests/qplc.py | 27 ++++++++++++++++++++------- 2 files changed, 35 insertions(+), 15 deletions(-) (limited to 'test-cli/test') diff --git a/test-cli/test/helpers/plc.py b/test-cli/test/helpers/plc.py index c9ef774..069058d 100644 --- a/test-cli/test/helpers/plc.py +++ b/test-cli/test/helpers/plc.py @@ -6,6 +6,7 @@ from sh import Command from test.helpers.gpio import gpio import time + class dcpPLC(object): __nReset = None __Phy = None @@ -40,7 +41,6 @@ class dcpPLC(object): self.__nRest = gpio('69', 'out', '1') self.__nRest = gpio('75', 'out', '1') - def SaveFirmware(self, firmare): self.setSaveFirmwareMode() try: @@ -50,26 +50,33 @@ class dcpPLC(object): return False, "plc flash firmware failed {} ".format(Error.exit_code) return True, '' - def set_plc (self, var, value, password): + def set_plc(self, var, value, password): try: res = self.__myConfigTool("-o", "SET", "-p", "{}={}".format(var, value), "-w", "{}".format(password)) print(res) except ErrorReturnCode as Error: - return False, "set var failed {} {}".format(var,Error.exit_code) + return False, "set var failed {} {}".format(var, Error.exit_code) return True, '' - def set_plc2 (self, var1, value1, var2, value2, password): + def set_plc2(self, var1, value1, var2, value2, password): try: - res = self.__myConfigTool("-o", "SET", "-p", "{}={}".format(var1, value1), "-p", "{}={}".format(var2, value2), "-w", "{}".format(password)) + res = self.__myConfigTool("-o", "SET", "-p", "{}={}".format(var1, value1), "-p", + "{}={}".format(var2, value2), "-w", "{}".format(password)) print(res) except ErrorReturnCode as Error: return False, "set var failed {}".format(Error.exit_code) return True, '' - - def get_plc (self, var, value, password): + def get_plc(self, var, value, password): try: self.__myConfigTool("-o", "GET", "-p", "{}".format(var), '{}'.format(value), "-w", "{}".format(password)) except ErrorReturnCode as Error: - return False, "set var failed {} {}".format(var,Error.exit_code) + return False, "set var failed {} {}".format(var, Error.exit_code) return True, '' + + def discover(self): + try: + self.__myConfigTool("-o", "DISCOVER") + except ErrorReturnCode: + return False + return True diff --git a/test-cli/test/tests/qplc.py b/test-cli/test/tests/qplc.py index 48d600a..28310c6 100644 --- a/test-cli/test/tests/qplc.py +++ b/test-cli/test/tests/qplc.py @@ -6,6 +6,8 @@ import sh import stat import time import ping3 +from netifaces import AF_INET +import netifaces as ni from test.helpers.md5 import md5_file from test.helpers.plc import dcpPLC @@ -34,7 +36,6 @@ class Qplc(unittest.TestCase): self.__gen_mac = varlist.get('gen_mac', self.__xmlObj.getKeyVal(self.__QPLCName, "gen_mac", "0")) self.__mtd_device = varlist.get('mtd_device', self.__xmlObj.getKeyVal(self.__QPLCName, "mtd_device", "/dev/mtd0")) self.__firmware_Path = varlist.get('firmwarepath', self.__xmlObj.getKeyVal(self.__QPLCName, "firmwarepath", "/root/hwtest-files/firmware")) - self.__plc_test_ip = varlist.get('plc_test_ip', self.__xmlObj.getKeyVal(self.__QPLCName, "plc_test_ip", "10.10.1.254")) self.__skipflash = varlist.get('skipflash', self.__xmlObj.getKeyVal(self.__QPLCName, "skipflash", "0")) self.__plc = dcpPLC(self.__factoryTool, self.__mtd_device) self.__factory_password = varlist.get('factory_password', self.__xmlObj.getKeyVal(self.__QPLCName, "factory_password", "0")) @@ -82,25 +83,37 @@ class Qplc(unittest.TestCase): self.fail('BUG: ?????') logObj.getlogger().info("MAC {}".format(res[0])) plcMAC = res[0][0] - time.sleep(12) + # wait for PLC to be turned on + attemptcounter = 0 + plcfound = False + while attemptcounter < 5 and not plcfound: + if self.__plc.discover(): + plcfound = True + else: + attemptcounter += 1 + time.sleep(5) + # mandatory wait before configuring the PLC chip + time.sleep(2) self.__plc.set_plc2('SYSTEM.PRODUCTION.SECTOR0_UNLOCK_PASSWORD', self.__factory_password, 'SYSTEM.PRODUCTION.MAC_ADDR', '{}'.format(plcMAC), self.__firmware_password) - #self.__plc.set_plc('SYSTEM.PRODUCTION.SECTOR0_UNLOCK_PASSWORD', self.__factory_password, self.__firmware_password) - #plcMAC = res[0][0] - #self.__plc.set_plc('SYSTEM.PRODUCTION.MAC_ADDR', '{}'.format(plcMAC), self.__firmware_password) + # plc reset to save changes self.__plc.setPLCReset() time.sleep(int(self.__plc_reset_wait)) + # calculate the IP of the GPLC0000 board to ping + ip_eth01 = ni.ifaddresses('eth0:1')[AF_INET][0]['addr'] # plc_test_ip = 10.10.1.113 + ip_eth01_splited = ip_eth01.split('.') + ip_eth01_splited[3] = str(int(ip_eth01_splited[3]) + 100) + plc_test_ip = ".".join(ip_eth01_splited) # plc_test_ip = 10.10.1.213 # ping against the GPLC0000 board ping3.EXCEPTIONS = True try: - ping3.ping(self.__plc_test_ip, timeout=0.1) + ping3.ping(plc_test_ip, timeout=0.1) except: self.fail('PLC ping timeout') - def getresults(self): return self.__resultlist -- cgit v1.1 From d8d4684c24a7c34334bb0b1d74dead69282e8c46 Mon Sep 17 00:00:00 2001 From: Josep Maso Date: Wed, 30 Sep 2020 10:32:16 +0200 Subject: Modified audio test to work in IGEP0046. --- test-cli/test/tests/qaudio.py | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'test-cli/test') diff --git a/test-cli/test/tests/qaudio.py b/test-cli/test/tests/qaudio.py index 2c86809..a219a1a 100644 --- a/test-cli/test/tests/qaudio.py +++ b/test-cli/test/tests/qaudio.py @@ -50,6 +50,11 @@ class Qaudio(unittest.TestCase): time.sleep(self.__run_delay) p1 = sh.aplay(self.__dtmf_file_play) p2.wait() + + p2 = sh.arecord("-r", self.__sampling_rate, "-d", calcRecordTime, "{}/{}".format(self.__record_path, self.__dtmf_file_record), _bg=True) + time.sleep(self.__run_delay) + p1 = sh.aplay(self.__dtmf_file_play) + p2.wait() if p1.exit_code == 0 and p2.exit_code == 0: p = sh.multimon("-t", "wav", "-a", "DTMF", "{}/{}".format(self.__record_path, self.__dtmf_file_record), "-q") if p.exit_code == 0: -- cgit v1.1 From ca73fcc336edc23db5750e93b6e1014d32a54ea5 Mon Sep 17 00:00:00 2001 From: Hector Fernandez Date: Tue, 29 Sep 2020 13:27:32 +0200 Subject: Added new test to validate video output with a webcam. --- test-cli/test/files/OpenSans-Regular.ttf | Bin 0 -> 217360 bytes test-cli/test/helpers/camara.py | 18 +---- test-cli/test/helpers/detect.py | 61 +++++++++++++++ test-cli/test/helpers/sdl.py | 22 +++--- test-cli/test/scripts/v4l-cam.sh | 14 ++++ test-cli/test/tests/qvideo.py | 124 +++++++++++++++++++++++++++++++ 6 files changed, 214 insertions(+), 25 deletions(-) create mode 100644 test-cli/test/files/OpenSans-Regular.ttf create mode 100644 test-cli/test/helpers/detect.py create mode 100755 test-cli/test/scripts/v4l-cam.sh create mode 100644 test-cli/test/tests/qvideo.py (limited to 'test-cli/test') diff --git a/test-cli/test/files/OpenSans-Regular.ttf b/test-cli/test/files/OpenSans-Regular.ttf new file mode 100644 index 0000000..db43334 Binary files /dev/null and b/test-cli/test/files/OpenSans-Regular.ttf differ diff --git a/test-cli/test/helpers/camara.py b/test-cli/test/helpers/camara.py index 9b2829c..afe8112 100644 --- a/test-cli/test/helpers/camara.py +++ b/test-cli/test/helpers/camara.py @@ -1,8 +1,7 @@ import cv2 -from test.helpers.syscmd import SysCommand +import sh class Camara(object): - __parent = None __device_name = None __device = None __w = 1280 @@ -13,8 +12,7 @@ class Camara(object): __hue = 0.0 __exposure = 166 - def __init__(self, parent, device="video0", width=1280, height=720): - self.__parent = parent + def __init__(self, device="video0", width=1280, height=720): self.__device_name = device self.__w = width self.__h = height @@ -64,21 +62,13 @@ class Camara(object): def __configure(self): self.__w = self.__setCamVar(cv2.CAP_PROP_FRAME_WIDTH, self.__w) self.__h = self.__setCamVar(cv2.CAP_PROP_FRAME_HEIGHT, self.__h) - cam_setup = SysCommand('v4lsetup', '{}/scripts/v4l-cam.sh'.format(self.__parent.getAppPath())) - cam_setup.execute() - - #self.__contrast = self.__setCamVar(cv2.CAP_PROP_CONTRAST, self.__contrast) - #self.__brightness = self.__setCamVar(cv2.CAP_PROP_BRIGHTNESS, self.__brightness) - #self.__saturation = self.__setCamVar(cv2.CAP_PROP_SATURATION, self.__saturation) - #self.__hue = self.__setCamVar(cv2.CAP_PROP_HUE, self.__hue) - #self.__exposure = self.__setCamVar(cv2.CAP_PROP_EXPOSURE, self.__exposure) - + sh.bash("../scripts/v4l-cam.sh") def __setCamVar(self, key, val): valold = cv2.VideoCapture.get(self.__device, key) if valold != val: cv2.VideoCapture.set(self.__device, key, val) - t = cv2.VideoCapture.get(self.__device, key) + t = cv2.VideoCapture.get(self.__device, key) return t return val diff --git a/test-cli/test/helpers/detect.py b/test-cli/test/helpers/detect.py new file mode 100644 index 0000000..193dabf --- /dev/null +++ b/test-cli/test/helpers/detect.py @@ -0,0 +1,61 @@ +import cv2 +import numpy as np + + +class Detect_Color(object): + oFrame = None + img_hsv = None + __red_lower1 = [0, 50, 20] + __red_upper1 = [5, 255, 255] + __red_lower2 = [175, 50, 20] + __red_upper2 = [180, 255, 255] + __blue_lower = [110, 50, 50] + __blue_upper = [130, 255, 255] + __green_lower = [36, 25, 25] + __green_upper = [86, 255, 255] + + def __init__(self, frame): + self.oFrame = frame + self.__hist() + + def __hist(self): + self.img_hsv = cv2.cvtColor(self.oFrame, cv2.COLOR_BGR2HSV) + + def getRed(self): + return self.__detect_two_areas([0, 50, 20], [5, 255, 255], [175, 50, 20], [180, 255, 255]) + + def getBlue(self): + return self.__detect_one_area([110, 50, 50], [130, 255, 255]) + + def getGreen(self): + return self.__detect_one_area([36, 25, 25], [86, 255, 255]) + + def __detect_one_area(self, lower, upper): + a_lower = np.array(lower) + a_upper = np.array(upper) + c_mask = cv2.inRange(self.img_hsv, a_lower, a_upper) + croped = cv2.bitwise_and(self.oFrame, self.oFrame, mask=c_mask) + mean_v = cv2.mean(self.oFrame, mask=c_mask) + mean = {} + mean['R'] = mean_v[2] + mean['G'] = mean_v[1] + mean['B'] = mean_v[0] + count = cv2.countNonZero(c_mask) + return c_mask, croped, mean, count + + def __detect_two_areas(self, lower1, upper1, lower2, upper2): + a1_lower = np.array(lower1) + a1_upper = np.array(upper1) + a2_lower = np.array(lower2) + a2_upper = np.array(upper2) + c_mask1 = cv2.inRange(self.img_hsv, a1_lower, a1_upper) + c_mask2 = cv2.inRange(self.img_hsv, a2_lower, a2_upper) + c_mask = cv2.bitwise_or(c_mask1, c_mask2) + croped = cv2.bitwise_and(self.oFrame, self.oFrame, mask=c_mask) + mean_v = cv2.mean(self.oFrame, mask=c_mask) + mean = {} + mean['R'] = mean_v[2] + mean['G'] = mean_v[1] + mean['B'] = mean_v[0] + count = cv2.countNonZero(c_mask) + return c_mask, croped, mean, count diff --git a/test-cli/test/helpers/sdl.py b/test-cli/test/helpers/sdl.py index 8f55d9f..2abb6ee 100644 --- a/test-cli/test/helpers/sdl.py +++ b/test-cli/test/helpers/sdl.py @@ -22,10 +22,10 @@ class SDL2(object): __renderer = None __srender = None - def __init__(self, parent): + def __init__(self): os.environ['SDL_VIDEODRIVER'] = "x11" os.environ['DISPLAY'] = ":0" - self.__resources = sdl2.ext.Resources(parent.getAppPath(), 'files') + # self.__resources = sdl2.ext.Resources(parent.getAppPath(), 'files') sdl2.ext.init() self.__createWindow() @@ -39,8 +39,8 @@ class SDL2(object): self.__window.show() SDL_ShowCursor(SDL_DISABLE) - def createFont(self, fontName, fontSize, fontColor): - return sdl2.ext.FontManager(font_path=self.__resources.get_path(fontName), size=fontSize, color=fontColor) + # def createFont(self, fontName, fontSize, fontColor): + # return sdl2.ext.FontManager(font_path=self.__resources.get_path(fontName), size=fontSize, color=fontColor) def WriteText(self, text, x, y, fontManager): imText = self.__factory.from_text(text, fontmanager=fontManager) @@ -69,16 +69,16 @@ class SDL2(object): def update(self): self.__renderer.present() - def showImage(self, filename): - im = self.__factory.from_image(self.__resources.get_path(filename)) - self.__srender.render(im) + # def showImage(self, filename): + # im = self.__factory.from_image(self.__resources.get_path(filename)) + # self.__srender.render(im) class SDL2_Test(object): __sdl2 = None - def __init__(self, parent): - self.__sdl2 = SDL2(parent) + def __init__(self): + self.__sdl2 = SDL2() def Clear(self): self.__sdl2.fillbgColor('black', True) @@ -93,8 +93,8 @@ class SDL2_Message(object): __fontManager_w = None __fontManager_b = None - def __init__(self, parent): - self.__sdl2 = SDL2(parent) + def __init__(self): + self.__sdl2 = SDL2() self.__fontManager_w = self.__sdl2.createFont('OpenSans-Regular.ttf', 24, Colors['white']) self.__fontManager_b = self.__sdl2.createFont('OpenSans-Regular.ttf', 24, Colors['black']) diff --git a/test-cli/test/scripts/v4l-cam.sh b/test-cli/test/scripts/v4l-cam.sh new file mode 100755 index 0000000..18da1c0 --- /dev/null +++ b/test-cli/test/scripts/v4l-cam.sh @@ -0,0 +1,14 @@ +#!/bin/bash + +v4l2-ctl -d /dev/video0 -c exposure_auto=3 +v4l2-ctl -d /dev/video0 -c brightness=0 +v4l2-ctl -d /dev/video0 -c contrast=20 +v4l2-ctl -d /dev/video0 -c saturation=55 +v4l2-ctl -d /dev/video0 -c hue=0 +v4l2-ctl -d /dev/video0 -c white_balance_temperature_auto=0 +v4l2-ctl -d /dev/video0 -c gamma=100 +v4l2-ctl -d /dev/video0 -c power_line_frequency=1 +v4l2-ctl -d /dev/video0 -c white_balance_temperature=4500 +v4l2-ctl -d /dev/video0 -c sharpness=2 +v4l2-ctl -d /dev/video0 -c backlight_compensation=2 +# v4l2-ctl -d /dev/video0 -c exposure_absolute=166 \ No newline at end of file diff --git a/test-cli/test/tests/qvideo.py b/test-cli/test/tests/qvideo.py new file mode 100644 index 0000000..e2f413e --- /dev/null +++ b/test-cli/test/tests/qvideo.py @@ -0,0 +1,124 @@ +import unittest +import sh +import time +from test.helpers.camara import Camara +from test.helpers.detect import Detect_Color +from test.helpers.sdl import SDL2_Test + +class Qvideo(unittest.TestCase): + params = None + __resultlist = None # resultlist is a python list of python dictionaries + + def __init__(self, testname, testfunc, varlist): + self.params = varlist + super(Qvideo, self).__init__(testfunc) + self._testMethodDoc = testname + self.__xmlObj = varlist["xml"] + self.__QVideoName = varlist.get('name', 'qvideo') + self.__resultlist = [] + self.__Camara = Camara() + self.__SDL2_Test = SDL2_Test() + self.__SDL2_Test.Clear() + + def define_capture(self): + self.__Camara.setSize( + int(self.params.get('capture_size_w', self.__xmlObj.getKeyVal(self.__QVideoName, "capture_size_w", 1280))), + int(self.params.get('capture_size_h', self.__xmlObj.getKeyVal(self.__QVideoName, "capture_size_h", 720)))) + self.__discard_frames_Count = int(self.params.get('capture_discardframes', self.__xmlObj.getKeyVal(self.__QVideoName, "capture_discardframes", 3))) + self.__frame_mean = int(self.params.get('capture_framemean', self.__xmlObj.getKeyVal(self.__QVideoName, "capture_framemean", 3))) + self.__max_failed = int(self.params.get('capture_maxfailed', self.__xmlObj.getKeyVal(self.__QVideoName, "capture_maxfailed", 1))) + + def __drop_frames(self, frame_count): + count = frame_count + while count > 0: + _ = self.__Camara.getFrame() + count -= 1 + + def Verify_Color(self, color): + self.paintColor(color) + count = self.__frame_mean + res_ok = 0 + res_failed = 0 + r_count = 0 + c_mean = 0 + while count > 0: + res, t = self.Capture(color) + if res: + res_ok += 1 + else: + res_failed += 1 + if t == "count": + r_count += 1 + else: + c_mean +=1 + count -= 1 + self.unpaintColor(color) + if res_failed > self.__max_failed: + if r_count > 0: + return '{}_COLOR_FAILED'.format(color) + elif c_mean > 0: + return 'MEAN_{}_FAILED'.format(color) + return "ok" + + def paintColor(self, color): + self.__SDL2_Test.Paint(color) + time.sleep(3) + self.__drop_frames(self.__Camara.getFrameCount()) + + def unpaintColor(self, color): + self.__SDL2_Test.Clear() + time.sleep(1) + + def Capture(self, color): + image = self.__Camara.getFrame() + if image is None: + return None + dtObject = Detect_Color(image) + if color == 'RED': + _, _, mean, count = dtObject.getRed() + elif color == 'BLUE': + _, _, mean, count = dtObject.getBlue() + elif color == 'GREEN': + c_mask, croped, mean, count = dtObject.getGreen() + + return self.checkThreshold(color, mean, count) + + def checkThreshold(self, color, mean, count): + min_count = int( + self.params.get('{}_min_count'.format(color), + self.__xmlObj.getKeyVal(self.__QVideoName, '{}_min_count'.format(color), 50000))) + + str = "" + # first verify count + if count >= min_count: + return True, "" + else: + str = "count" + return False, str + + def execute(self): + self.__resultlist = [] + + # set image size + self.define_capture() + # Open camara + if not self.__Camara.Open(): + self.fail('Error: USB camera not found') + # discard initial frames + self.__drop_frames(self.__discard_frames_Count) + # Test + res = self.Verify_Color('RED') + if res != "ok": + self.fail("failed: RED verification failed") + res = self.Verify_Color('BLUE') + if res != "ok": + self.fail("failed: BLUE verification failed") + res = self.Verify_Color('GREEN') + if res != "ok": + self.fail("failed: GREEN verification failed") + + def getresults(self): + return self.__resultlist + + def gettextresult(self): + return "" -- cgit v1.1 From d4071b6579312b2fb265e379031f588354d35f3a Mon Sep 17 00:00:00 2001 From: Manel Caro Date: Fri, 2 Oct 2020 14:12:09 +0200 Subject: solve usb error bug with quotes message --- test-cli/test/tests/qusb.py | 2 ++ 1 file changed, 2 insertions(+) (limited to 'test-cli/test') diff --git a/test-cli/test/tests/qusb.py b/test-cli/test/tests/qusb.py index 3182685..4f76d0c 100644 --- a/test-cli/test/tests/qusb.py +++ b/test-cli/test/tests/qusb.py @@ -69,6 +69,8 @@ class Qusb(unittest.TestCase): return False, 'md5 check failed {}<>{}'.format(originalMD5, md5val) except OSError as why: return False,'Error: {} tranfer failed'.format(why.errno) + except sh.ErrorReturnCode as shError: + return False, 'USB Exception: tranfer failed' except Exception as details: return False, 'USB Exception: {} tranfer failed'.format(details) return True, '' -- cgit v1.1 From 5771dcc8acabd2f4f560768cf45615e929409f6e Mon Sep 17 00:00:00 2001 From: Manel Caro Date: Fri, 2 Oct 2020 15:33:12 +0200 Subject: fix execution camera setup script path not correct --- test-cli/test/helpers/camara.py | 7 +++++-- test-cli/test/tests/qvideo.py | 2 +- 2 files changed, 6 insertions(+), 3 deletions(-) (limited to 'test-cli/test') diff --git a/test-cli/test/helpers/camara.py b/test-cli/test/helpers/camara.py index afe8112..bcb1df7 100644 --- a/test-cli/test/helpers/camara.py +++ b/test-cli/test/helpers/camara.py @@ -4,6 +4,7 @@ import sh class Camara(object): __device_name = None __device = None + __setupScriptPath = '' __w = 1280 __h = 720 __contrast = 0.0 @@ -12,10 +13,11 @@ class Camara(object): __hue = 0.0 __exposure = 166 - def __init__(self, device="video0", width=1280, height=720): + def __init__(self, setup_script_path, device="video0", width=1280, height=720): self.__device_name = device self.__w = width self.__h = height + self.__setupScriptPath = setup_script_path; def Close(self): if self.__device is not None: @@ -62,7 +64,8 @@ class Camara(object): def __configure(self): self.__w = self.__setCamVar(cv2.CAP_PROP_FRAME_WIDTH, self.__w) self.__h = self.__setCamVar(cv2.CAP_PROP_FRAME_HEIGHT, self.__h) - sh.bash("../scripts/v4l-cam.sh") + sh.bash(self.__setupScriptPath + '/test/scripts/v4l-cam.sh') + # sh.bash("../scripts/v4l-cam.sh") def __setCamVar(self, key, val): valold = cv2.VideoCapture.get(self.__device, key) diff --git a/test-cli/test/tests/qvideo.py b/test-cli/test/tests/qvideo.py index e2f413e..b4133b6 100644 --- a/test-cli/test/tests/qvideo.py +++ b/test-cli/test/tests/qvideo.py @@ -16,7 +16,7 @@ class Qvideo(unittest.TestCase): self.__xmlObj = varlist["xml"] self.__QVideoName = varlist.get('name', 'qvideo') self.__resultlist = [] - self.__Camara = Camara() + self.__Camara = Camara(setup_script_path=varlist['testPath']) self.__SDL2_Test = SDL2_Test() self.__SDL2_Test.Clear() -- cgit v1.1 From e7631181c08c38c196558fc79b648d78ccaadcc8 Mon Sep 17 00:00:00 2001 From: Manel Caro Date: Mon, 5 Oct 2020 11:44:22 +0200 Subject: Add qvideo variables --- test-cli/test/helpers/camara.py | 5 ++--- test-cli/test/scripts/v4l-cam.sh | 14 -------------- test-cli/test/tests/qvideo.py | 25 +++++++++++++------------ 3 files changed, 15 insertions(+), 29 deletions(-) delete mode 100755 test-cli/test/scripts/v4l-cam.sh (limited to 'test-cli/test') diff --git a/test-cli/test/helpers/camara.py b/test-cli/test/helpers/camara.py index bcb1df7..b23df74 100644 --- a/test-cli/test/helpers/camara.py +++ b/test-cli/test/helpers/camara.py @@ -17,7 +17,7 @@ class Camara(object): self.__device_name = device self.__w = width self.__h = height - self.__setupScriptPath = setup_script_path; + self.__setupScriptPath = setup_script_path def Close(self): if self.__device is not None: @@ -64,8 +64,7 @@ class Camara(object): def __configure(self): self.__w = self.__setCamVar(cv2.CAP_PROP_FRAME_WIDTH, self.__w) self.__h = self.__setCamVar(cv2.CAP_PROP_FRAME_HEIGHT, self.__h) - sh.bash(self.__setupScriptPath + '/test/scripts/v4l-cam.sh') - # sh.bash("../scripts/v4l-cam.sh") + sh.bash(self.__setupScriptPath) def __setCamVar(self, key, val): valold = cv2.VideoCapture.get(self.__device, key) diff --git a/test-cli/test/scripts/v4l-cam.sh b/test-cli/test/scripts/v4l-cam.sh deleted file mode 100755 index 18da1c0..0000000 --- a/test-cli/test/scripts/v4l-cam.sh +++ /dev/null @@ -1,14 +0,0 @@ -#!/bin/bash - -v4l2-ctl -d /dev/video0 -c exposure_auto=3 -v4l2-ctl -d /dev/video0 -c brightness=0 -v4l2-ctl -d /dev/video0 -c contrast=20 -v4l2-ctl -d /dev/video0 -c saturation=55 -v4l2-ctl -d /dev/video0 -c hue=0 -v4l2-ctl -d /dev/video0 -c white_balance_temperature_auto=0 -v4l2-ctl -d /dev/video0 -c gamma=100 -v4l2-ctl -d /dev/video0 -c power_line_frequency=1 -v4l2-ctl -d /dev/video0 -c white_balance_temperature=4500 -v4l2-ctl -d /dev/video0 -c sharpness=2 -v4l2-ctl -d /dev/video0 -c backlight_compensation=2 -# v4l2-ctl -d /dev/video0 -c exposure_absolute=166 \ No newline at end of file diff --git a/test-cli/test/tests/qvideo.py b/test-cli/test/tests/qvideo.py index b4133b6..225940b 100644 --- a/test-cli/test/tests/qvideo.py +++ b/test-cli/test/tests/qvideo.py @@ -16,17 +16,20 @@ class Qvideo(unittest.TestCase): self.__xmlObj = varlist["xml"] self.__QVideoName = varlist.get('name', 'qvideo') self.__resultlist = [] - self.__Camara = Camara(setup_script_path=varlist['testPath']) - self.__SDL2_Test = SDL2_Test() - self.__SDL2_Test.Clear() + self.__w = int(varlist.get('capture_size_w', self.__xmlObj.getKeyVal(self.__QVideoName, "capture_size_w", 1280))) + self.__h = int(varlist.get('capture_size_h', self.__xmlObj.getKeyVal(self.__QVideoName, "capture_size_h", 720))) + self.__discard_frames_Count = int(varlist.get('capture_discardframes',self.__xmlObj.getKeyVal(self.__QVideoName, "capture_discardframes", 3))) + self.__frame_mean = int(varlist.get('capture_framemean', self.__xmlObj.getKeyVal(self.__QVideoName, "capture_framemean", 3))) + self.__max_failed = int(varlist.get('capture_maxfailed', self.__xmlObj.getKeyVal(self.__QVideoName, "capture_maxfailed", 1))) + self.__cam_setupscript = varlist.get('cam_setupfile', self.__xmlObj.getKeyVal(self.__QVideoName, "cam_setupfile", + "/root/hwtest-files/board/scripts/v4l-cam.sh")) + self.__sdl_display = varlist.get('sdl_display', self.__xmlObj.getKeyVal(self.__QVideoName, "sdl_display", ":0")) + self.__sdl_driver = varlist.get('sdl_driver', self.__xmlObj.getKeyVal(self.__QVideoName, "sdl_driver", "x11")) + self.__camdevice = varlist.get('camdevice', self.__xmlObj.getKeyVal(self.__QVideoName, "camdevice", "video0")) - def define_capture(self): - self.__Camara.setSize( - int(self.params.get('capture_size_w', self.__xmlObj.getKeyVal(self.__QVideoName, "capture_size_w", 1280))), - int(self.params.get('capture_size_h', self.__xmlObj.getKeyVal(self.__QVideoName, "capture_size_h", 720)))) - self.__discard_frames_Count = int(self.params.get('capture_discardframes', self.__xmlObj.getKeyVal(self.__QVideoName, "capture_discardframes", 3))) - self.__frame_mean = int(self.params.get('capture_framemean', self.__xmlObj.getKeyVal(self.__QVideoName, "capture_framemean", 3))) - self.__max_failed = int(self.params.get('capture_maxfailed', self.__xmlObj.getKeyVal(self.__QVideoName, "capture_maxfailed", 1))) + self.__Camara = Camara(setup_script_path=self.__cam_setupscript, device=self.__camdevice, width=self.__w, height=self.__h) + self.__SDL2_Test = SDL2_Test(driver=self.__sdl_driver, display=self.__sdl_display, w=self.__w, h=self.__h) + self.__SDL2_Test.Clear() def __drop_frames(self, frame_count): count = frame_count @@ -99,8 +102,6 @@ class Qvideo(unittest.TestCase): def execute(self): self.__resultlist = [] - # set image size - self.define_capture() # Open camara if not self.__Camara.Open(): self.fail('Error: USB camera not found') -- cgit v1.1 From 33fdf3f804a171b2d9c70ba39a7bad11658c5b64 Mon Sep 17 00:00:00 2001 From: Manel Caro Date: Mon, 5 Oct 2020 11:44:43 +0200 Subject: Add qvideo variables --- test-cli/test/helpers/sdl.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'test-cli/test') diff --git a/test-cli/test/helpers/sdl.py b/test-cli/test/helpers/sdl.py index 2abb6ee..8131a53 100644 --- a/test-cli/test/helpers/sdl.py +++ b/test-cli/test/helpers/sdl.py @@ -14,15 +14,15 @@ Colors = { class SDL2(object): __resources = None - __w = 1024 - __h = 768 + __w = 1280 + __h = 720 __winName = "noname" __window = None __factory = None __renderer = None __srender = None - def __init__(self): + def __init__(self, driver, display, w, h): os.environ['SDL_VIDEODRIVER'] = "x11" os.environ['DISPLAY'] = ":0" # self.__resources = sdl2.ext.Resources(parent.getAppPath(), 'files') @@ -77,8 +77,8 @@ class SDL2(object): class SDL2_Test(object): __sdl2 = None - def __init__(self): - self.__sdl2 = SDL2() + def __init__(self, driver, display, w, h): + self.__sdl2 = SDL2(driver, display, w, h) def Clear(self): self.__sdl2.fillbgColor('black', True) -- cgit v1.1 From 293f0682dd8258a068e4b152f9fecb292d732b78 Mon Sep 17 00:00:00 2001 From: Manel Caro Date: Mon, 5 Oct 2020 11:45:41 +0200 Subject: modify finish_test call, added execution without messsage if fails --- test-cli/test/helpers/testsrv_db.py | 14 +++++++++++++- test-cli/test/runners/simple.py | 3 ++- 2 files changed, 15 insertions(+), 2 deletions(-) (limited to 'test-cli/test') diff --git a/test-cli/test/helpers/testsrv_db.py b/test-cli/test/helpers/testsrv_db.py index 556c246..8e96e8c 100644 --- a/test-cli/test/helpers/testsrv_db.py +++ b/test-cli/test/helpers/testsrv_db.py @@ -101,10 +101,11 @@ class TestSrv_Database(object): try: print('finish_test => SQL {}'.format(sql)) self.__sqlObject.db_execute_query(sql) + return True except Exception as err: r = find_between(str(err), '#', '#') print('finish_test => {}'.format(err)) - return None + return False def upload_result_file(self, testid_ctl, testid, desc, filepath, mimetype): try: @@ -246,3 +247,14 @@ class TestSrv_Database(object): r = find_between(str(err), '#', '#') # print(r) return default + + def setDevelStationState(self, station, newState): + sql = "UPDATE station.station_state SET state = {} WHERE hostname={}".format(newState, station) + try: + res = self.__sqlObject.db_execute_query(sql) + # print(res) + return res[0][0] + except Exception as err: + r = find_between(str(err), '#', '#') + # print(r) + return None diff --git a/test-cli/test/runners/simple.py b/test-cli/test/runners/simple.py index ece5a4e..c110b1c 100644 --- a/test-cli/test/runners/simple.py +++ b/test-cli/test/runners/simple.py @@ -88,6 +88,7 @@ class TextTestResult(unittest.TestResult): status = "TEST_FAILED" resulttext = test.longMessage logObj.getlogger().info('{}:{}:{}:{}'.format(test.params["testidctl"], test.params["testid"], status, resulttext)) - self.__pgObj.finish_test(test.params["testidctl"], test.params["testid"], status, resulttext) + if not self.__pgObj.finish_test(test.params["testidctl"], test.params["testid"], status, resulttext): + self.__pgObj.finish_test(test.params["testidctl"], test.params["testid"], status, "") except Exception as E: logObj.getlogger().error('Exception: [{}]{}:{}:{}:{}'.format(E, test.params["testidctl"], test.params["testid"], status, resulttext)) \ No newline at end of file -- cgit v1.1 From de4defc5023097dbebbfe4aa5c2665631399630b Mon Sep 17 00:00:00 2001 From: Manel Caro Date: Tue, 3 Nov 2020 12:25:04 +0100 Subject: added support for Honeywell QR reader 1400g --- test-cli/test/helpers/qrreader.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'test-cli/test') diff --git a/test-cli/test/helpers/qrreader.py b/test-cli/test/helpers/qrreader.py index f663e99..51e5247 100644 --- a/test-cli/test/helpers/qrreader.py +++ b/test-cli/test/helpers/qrreader.py @@ -11,7 +11,8 @@ selector = selectors.DefaultSelector() qrdevice_list = [ "Honeywell Imaging & Mobility 1900", "Manufacturer Barcode Reader", - "SM SM-2D PRODUCT HID KBW" + "SM SM-2D PRODUCT HID KBW", + "Honeywell Imaging & Mobility 1400g" ] qrkey_list = {'KEY_0': '0', -- cgit v1.1 From d5b273a3b58a250742049df4ca0ef0ba54f53d33 Mon Sep 17 00:00:00 2001 From: Manel Caro Date: Sat, 6 Nov 2021 16:20:13 +0100 Subject: Change Comment about Postgres DB Object --- test-cli/test/helpers/psqldb.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'test-cli/test') diff --git a/test-cli/test/helpers/psqldb.py b/test-cli/test/helpers/psqldb.py index e703c3a..0141414 100644 --- a/test-cli/test/helpers/psqldb.py +++ b/test-cli/test/helpers/psqldb.py @@ -1,8 +1,9 @@ import psycopg2 +import psycopg2.extras class PgSQLConnection(object): - """aaaaaaa""" + """Postgres Connection Object""" __conection_object = None __db_config = {'dbname': 'testsrv', 'host': '192.168.2.171', -- cgit v1.1