Example #1
0
 def verify_element_exist(self,
                          locator
                          ):
     print("locator found is %s"%locator,is_console=False)
     #msg = "Element locator '" + locator + "' did not match any elements."
     msg = '"'+locator +'"'+" did not match any elements."
     msg=msg.replace('"','').replace("'","")
     msg1 = '"'+locator+ '"'+" is not a valid locator."
     msg1=msg1.replace('"','').replace("'","")
     print("Message is %s" %msg,is_console=False)
     print("Message 1 is %s" %msg1,is_console=False)
     try:
         self.click_element(locator)
         asserts.fail("Element present : %s"%locator)
     except Exception,Fault:
         F=str(Fault).replace('"','').replace("'","")
         print("exception found : %s"%str(Fault),is_console=False)
         #asserts.assert_equals((str(Fault),msg) or (str(Fault),msg1) ,"Unexpected exception found: %s"%Fault)
         #msg = "Unexpected Error found. [%s]" %(Fault)
         tflag=False
         if (msg in F) or (msg1 in F):
             tflag=True
         msg = "Unexpected exception found.[%s]" %(F)    
         if not tflag:
             asserts.fail(msg)
    def execute_command(self, cmd, skip='no', expected_rc=0):
        """Execute a command on a serial linux console and check return code.
        """
        expected_rc = int(expected_rc)

        ret = {}

        self._write_cmd(cmd)
        ret['output'] = self._read_until_prompt()
        if ret['output']:
            logger.info('Command output:\n{}'.format(ret['output']))
        else:
            logger.debug('No ouput')
        if skip == 'yes':
            return ret

        self._write_cmd('echo $?')
        ret['rc'] = int(self._read_until_prompt())

        if ret['rc'] != expected_rc:
            logger.debug(ret)
            asserts.fail(
                'Unexpected return code for command \'{}\' return code was {}'.
                format(cmd, ret['rc']))

        return ret
Example #3
0
 def serial_confirm_ter_restart(self, wait_time, baudrate=115200):
     '''
     功能:
     - 确认终端是否重启
     - 通过条件 : 接收到终端串口应答的时间
     
     参数:
     - wait_time : 超时时间
     '''
     wait_time = int(wait_time)
     send_data = '(\'IOT+L1+nw.e01.r01.ic=?\',\'IOT+L1+nw.e01.r01.ic\',{0},1)'.format(
         baudrate)
     s_time = 0
     flag = False
     for i in range(int(wait_time / 2)):
         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         sock.connect(IP_SERIAL_USB0)
         sock.send(send_data.encode())
         self.rsp_data = sock.recv(1024).decode()
         if self.rsp_data.find('IOT+L1+NW.E01.R01.IC=') != -1:
             flag = True
             break
         time.sleep(0.1)
         sock.close()
     if flag:
         print('terminal is working')
         print(self.rsp_data)
     else:
         asserts.fail('restart failed')
     sock.close()
     ret_time = self._get_ter_time()
     return ret_time
Example #4
0
    def server_actual_msg_get_num(self,
                                  start_time,
                                  interval_time,
                                  msg_num=None,
                                  platform='gb'):
        '''
        功能:
        - 验证这时间段内的实时数据量是否正常(验证盲区数据的时候使用)

        参数:
        - start_time : 开始时间
        - stop_time : 结束时间
        - msg_num : 应得数据数量
        '''
        start_time = str_to_timestamp(start_time)
        interval_time = int(interval_time)
        stop_time = start_time + interval_time
        if interval_time > 0:
            select_sql = SELECT_SQL_DICT['get_actual_msg_num'].format(
                platform, start_time, stop_time)
        else:
            select_sql = get_actual_msg_num['get_actual_msg_num'].format(
                platform, stop_time, start_time)
        select_res = self.mydatabase.select_all_data(select_sql)
        if select_res:
            actual_msg_num = len(select_res)
            if msg_num:
                msg_num = int(msg_num)
                if actual_msg_num != msg_num:
                    asserts.fail('actual msg num error:'.format(msg_num))
            else:
                return actual_msg_num
        else:
            asserts.fail('do not have actual msg')
Example #5
0
    def server_sleep_heartbeat_mon(self, start_time, stop_time, interval_time):
        '''
        功能:
        - 验证这时间段内心跳数据间隔是否正常

        参数:
        - start_time : 开始时间
        - stop_time : 结束时间
        - interval_time : 心跳数据间隔
        '''
        start_time = str_to_timestamp(start_time)
        stop_time = str_to_timestamp(stop_time)
        select_sql = SELECT_SQL_DICT['sleep_heartbeat'].format(
            start_time, stop_time)
        select_res = self.mydatabase.select_all_data(select_sql)
        if select_res:
            cur_time = 0
            for item in select_res:
                if cur_time == 0:
                    cur_time = item['time_pi']
                else:
                    myinterval = int(item['time_pi']) - int(cur_time)
                    if abs(myinterval - int(interval_time)) > 5:
                        print(item['time_pi'], cur_time)
                        print('interval time is ', myinterval)
                        asserts.fail('heartbeat error')
                    cur_time = item['time_pi']
        else:
            asserts.fail('don not had heartbeat data')
        print('heartbeat msg normal')
    def add_port(self, port_locator, open=True, make_current=False, **kwargs):
        """
        Adds new port with specified locator.

        port_locator may be in (traditional) port name or url format.
        If `open` has false value, the port is closed immediately.
        Parameters given in kwargs will override those library defaults
        initialized on import.
        If make_current has truth value, the opened port is set to current
        port. Note that if there's only one port in the library instance,
        it will always be current port, regardless of make_current's value.

        Fails if specified port_locator is already used in this library
        instance.

        Returns created port instance.
        """
        if port_locator in [None, '', '_']:
            asserts.fail('Invalid port locator.')
        elif port_locator in self._ports:
            asserts.fail('Port already exists.')
        serial_kw = dict(
            (k, type(v)(kwargs.get(k, v))) for k, v in self._defaults.items())
        # try url first, then port name
        try:
            port = serial_for_url(port_locator, **serial_kw)
        except (AttributeError, ValueError):
            port = Serial(port_locator, **serial_kw)
        asserts.assert_not_none(port, 'Port initialization failed.')
        self._ports[port_locator] = port
        if port.is_open and (is_truthy(open) is False):
            port.close()
        if self._current_port_locator is None or make_current:
            self._current_port_locator = port_locator
        return port
Example #7
0
 def server_actual_data_rf_analysis(slef,
                                    start_time,
                                    stop_time,
                                    platform='gbtele'):
     '''
     功能:
     - 判断实时数据变化趋势和结果是否正确
     
     参数:
     - start_time : 开始时间
     - stop_time : 结束时间
     '''
     start_time = str_to_timestamp(start_time)
     stop_time = str_to_timestamp(stop_time)
     select_sql = SELECT_SQL_DICT['rf_analysis_actual_data'].format(
         platform, start_time, stop_time)
     select_res = self.mydatabase.select_all_data(select_sql)
     start_id = 0
     num = 0
     for item in select_res:
         if hex_str_to_int(item['total_current_1']) < 1000:
             if start_id == 0:
                 start_id = i
             num = num + 1
         else:
             if num >= 10:
                 for item in select_res[start_id:start_id + num]:
                     if item['charge_state'] != '02':
                         asserts.fail('charg state error:' +
                                      str(item['time_ter']))
Example #8
0
 def get_login_cycle(self,
                     start_time=None,
                     stop_time=None,
                     platform='gbtele',
                     **kwargs):
     '''
     功能:
     - 获取登入周期
     
     参数:
     - start_time : 开始时间
     - stop_time : 结束时间
     - platform : 选择平台, 可填:gbtele,sirun,zdmon,zdgbt2,sharengo
     - 返回 : 得出的登入周期数组
     '''
     cycle_list = []
     start_time = str_to_timestamp(start_time)
     stop_time = str_to_timestamp(stop_time)
     select_sql = SELECT_SQL_DICT['get_login_cycle'].format(
         platform, start_time, stop_time)
     select_res = self.mydatabase.select_all_data(select_sql)
     try:
         login_times = len(select_res)
     except:
         asserts.fail('had not login')
     for i in range(login_times):
         if i < login_times - 1:
             cycle_list.append(
                 (select_res[i]['time_ter'], select_res[i + 1]['time_ter']))
         else:
             cycle_list.append((select_res[i]['time_ter'], stop_time))
     if cycle_list == []:
         cycle_list.append((start_time, stop_time))
     return cycle_list
Example #9
0
 def select_data_from_actual(self,
                             cycle_list,
                             ter_actual_report_interval,
                             is_alarm_data=None):
     '''
     功能:
     - 查询实时上报数据,同时判断报警数据是否正常(暂时只有国标)
     
     参数:
     - cycle_list : ``get_login_cycle``关键字返回值
     - ter_actual_report_interval : 实时上报间隔
     - is_alarm_data : 是否需要判断具体的报警数据, 默认不判断,填True就会判断
     - 返回值:报警时间,时间间隔为1的数据条数,时间间隔错误的数据时间
     '''
     ter_actual_report_interval = int(ter_actual_report_interval) / 1000
     try:
         for item in cycle_list:
             start_time = item[0]
             stop_time = item[1]
             select_sql = SELECT_SQL_DICT['select_data_from_actual'].format(
                 start_time, stop_time)
             last_time_data = self.mydatabase.select_all_data(select_sql)
             alarm_res = is_alarm(last_time_data, is_alarm_data)
             data_res = is_interval_time_normal(last_time_data,
                                                ter_actual_report_interval,
                                                alarm_res)
             if alarm_res == []:
                 asserts.fail('have not alarm data')
                 continue
             print('报警数据时间:', alarm_res)
             print('时间间隔为1的数据数:', data_res[0])
             print('时间间隔错误数据:', data_res[1])
             judge_alarm_data(data_res)
     except Exception as e:
         asserts.fail(e)
Example #10
0
def is_alarm(data, is_alarm_data):
    '''
    参数:数据库的实时上报数据
    功能:判断终端是否产生报警
    返回值:如果有报警数据,则返回包含产生报警的时间点的元组,如果没有报警数据就返回一个空的元组
    '''
    alarm_time = []
    item_time_ter = ''
    for item in data:
        len_alarm = len(alarm_time) - 1
        if item['max_alarm_level_7'][0] == '3':
            item_time_ter = item['time_ter']
            if alarm_time == []:
                alarm_time.append(item_time_ter)
                continue
            item_alarm_time = alarm_time[len_alarm]
            if item_alarm_time == item_time_ter:
                continue
            interval_time = item_time_ter - item_alarm_time
            if interval_time < 0:
                alarm_time[len_alarm] = item_time_ter
            if interval_time > 30:
                alarm_time.append(item_time_ter)
            if is_alarm_data:
                if item['com_alarm_sign_7'] != '00000200':
                    asserts.fail('do not have alarm data')
    return alarm_time
    def delete_port(self, port_locator=None):
        """
        Deletes specified port.

        Port is closed if it is opened.
        By default, current port is deleted and most recently added
        ports is selected as new current port. Deleting last port
        in the library instance makes current port set to None.
        Fails if specified port is not found or attempt to delete
        current port if it is set to None.
        """
        if port_locator is None:
            port_locator = self._current_port_locator
        # fails if invalid port locator.
        if port_locator not in self._ports:
            asserts.fail('Invalid port locator.')
        port = self._ports.pop(port_locator)
        if port.is_open:
            port.close()
        # if the deleted port is current port, most recent port
        # left in the instacne will be current port
        if port_locator == self._current_port_locator:
            self._current_port_locator = None
            if self._ports.keys():
                self._current_port_locator = self._ports.keys()[-1]
        del port
Example #12
0
 def CAN_send_and_rec_and_return(self, send_id, send_data, recv_id):
     '''
     功能:
     - 发送并接收CAN数据,并且返回CAN数据
     - 通过条件 : 接收到对应的can id的数据
     
     参数:
     - send_id : 发送的ID
     - send_data : 发送的数据
     - recv_id : 接收的ID
     (注意没有默认值的参数是必填的,有默认值的参数不填写,就会按照默认的参数执行)
     
     例子:
     | CAN_send_and_rec_and_return | 720 | 02 10 03 | 728 |
     '''
     send_id = self._convert_can_id(send_id)
     recv_id = self._convert_can_id(recv_id)
     send_data = self._convert_can_send_data(send_data)
     msg = can.Message(
         arbitration_id = send_id,
         data = send_data, 
         extended_id = False)
     self._can_send_and_wait_rsp(recv_id, msg)
     if SHOULD_RECV_CAN_OBJECT:
         for bus_recv_msg in SHOULD_RECV_CAN_OBJECT:
             return self._bytes_to_hex(bus_recv_msg.data)
     else:
         asserts.fail('未接收到CAN数据')
Example #13
0
 def CAN_send_and_rec_rsp(self, send_id, send_data, recv_id):
     '''
     功能:
     - 发送并接收CAN数据
     - 通过条件 : 收到期待的can id的数据
     
     参数:
     - send_id : 发送的ID
     - send_data : 发送的数据
     - recv_id : 接收的ID
     - timeout : 超时时间(ms)
     (注意没有默认值的参数是必填的,有默认值的参数不填写,就会按照默认的参数执行)
     
     例子:
     | CAN_send_and_rec_rsp | 720 | 02 10 03 | 728 |
     '''
     send_id = self._convert_can_id(send_id)
     recv_id = self._convert_can_id(recv_id)
     send_data = self._convert_can_send_data(send_data)
     msg = can.Message(
         arbitration_id = send_id,
         data = send_data, 
         extended_id = False)
     self._can_send_and_wait_rsp(recv_id, msg)
     if SHOULD_RECV_CAN_OBJECT:
         for bus_recv_msg in SHOULD_RECV_CAN_OBJECT:
             print('infact recv', hex(bus_recv_msg.arbitration_id),self._bytes_to_hex(bus_recv_msg.data))
             if bus_recv_msg.arbitration_id == recv_id:
                 logger.info('收到响应,测试成功')
                 break
     else:
         asserts.fail('没有收到响应,测试失败')
Example #14
0
 def CAN_send_and_rec_except(self, send_id, send_data, recv_id, recv_data):
     '''
     功能:
     - 发送并接收CAN数据
     - 通过条件 : 收到数据,并且收到的数据与指定的数据不同
     
     参数:
     - send_id : 发送的ID
     - send_data : 发送的数据
     - recv_id : 接收的ID
     - recv_data : 接收的数据
     - timeout : 超时时间(ms)
     (注意没有默认值的参数是必填的,有默认值的参数不填写,就会按照默认的参数执行)
     
     例子:
     | CAN_send_and_rec_except | 720 | 02 10 03 | 728 | 50 03 |
     '''
     send_id = self._convert_can_id(send_id)
     recv_id = self._convert_can_id(recv_id)
     send_data = self._convert_can_send_data(send_data)
     recv_data = self._convert_can_recv_data(recv_data)
     msg = can.Message(
         arbitration_id = send_id,
         data = send_data, 
         extended_id = False)
     self._can_send_and_wait_rsp(recv_id, msg)
     if SHOULD_RECV_CAN_OBJECT:
         for bus_recv_msg in SHOULD_RECV_CAN_OBJECT:
             print('except recv', hex(recv_id),self._bytes_to_hex(recv_data))
             print('infact recv', hex(bus_recv_msg.arbitration_id),self._bytes_to_hex(bus_recv_msg.data))
             if bus_recv_msg.arbitration_id == recv_id and bus_recv_msg.data == recv_data:
                 asserts.fail('收到了不想要的否定响应码')
                 break
     else:
         asserts.fail('没有收到CAN数据')
Example #15
0
 def isotpCAN_send_and_rec(self, send_data, recv_data, timeout=None):
     '''
     功能:
     - 发送并且接收isotp can数据
     - 收发的CAN ID 需要设置, 默认为0x720 0x728
     - 通过条件 : 接收到CAN数据, 并且与指定CAN数据相同
     
     参数:
     - send_data : 发送的CAN数据
     - recv_data : 接收的CAN数据
     - timeout : 超时时间设置单位(ms)(未生效)
     (注意没有默认值的参数是必填的,有默认值的参数不填写,就会按照默认的参数执行)
     
     例子(电咖VIN码设置与查询):
     | isotpCAN_send_and_rec | 10 01 | 50 01 00 32 01 F4 |
     | sleep | 10 | #等待10秒的原因是,开机10秒内无法进入安全访问等级 |
     | isotpCAN_send_and_rec | 10 03 | 50 03 00 32 01 F4 |
     | isotpCAN_send_and_rec | 27 01 | 67 01 2B 3A 7A 44 |
     | isotpCAN_send_and_rec | 27 02 BE 92 38 AE | 67 02 |
     | isotpCAN_send_and_rec | 2E F1 90 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 | 6E F1 90 |
     | isotpCAN_send_and_rec | 22 F1 90 | 62 F1 90 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 |
     '''
     self.shd_recv_data = recv_data
     self._isotp_nor_pro(send_data)
     if recv_data.lower() != self.rsp_data[:-1]:
         asserts.fail('接收错误数据')
     else:
         logger.info('数据校验成功')
Example #16
0
 def server_login_wait(self,
                       start_time,
                       wait_time,
                       platform1='gbtele',
                       platform2='',
                       vin=None,
                       init=0):
     '''
     功能:
     - 等待终端上线
     - 通过条件 : 终端在规定时间内上线
     
     参数:
     - start_time : 初始时间
     - wait_time : 等待时间
     - platform : 选择的平台, 可选的平台有:gb,sirun,zdmon,zdgbt2,sharengo
     '''
     self.wat_for_login_res = True
     try:
         res = _wait_for_login(start_time, wait_time, platform1, platform2,
                               vin, init)
     except Exception as e:
         asserts.fail(e)
     if not res:
         self.wat_for_login_res = False
         asserts.fail('car is not login platform')
    def delete_port(self, port_locator=None):
        """
        Deletes specified port.

        Port is closed if it is opened.
        By default, current port is deleted and most recently added
        ports is selected as new current port. Deleting last port
        in the library instance makes current port set to None.
        Fails if specified port is not found or attempt to delete
        current port if it is set to None.
        """
        if port_locator is None:
            port_locator = self._current_port_locator
        # fails if invalid port locator.
        if port_locator not in self._ports:
            asserts.fail('Invalid port locator.')
        port = self._ports.pop(port_locator)
        if port.is_open:
            port.close()
        # if the deleted port is current port, most recent port
        # left in the instacne will be current port
        if port_locator == self._current_port_locator:
            self._current_port_locator = None
            if self._ports.keys():
                self._current_port_locator = self._ports.keys()[-1]
        del port
Example #18
0
 def match_expected_notification(self,expected_notification=''):
     if not expected_notification:
         asserts.fail("Expected Message not provided.")
     
     act_msg = ""
     act_msg = self.get_text("LabelValueNotificationMsg")
     print("LabelValueNotificationMsg is %s" %act_msg)
     waittimer = Timer()
     waittime = waittimer.start(90,1)
     print("Expected message is {%s}, %s" % (expected_notification,type(expected_notification)), is_console=False)
     print("Actual message is {%s}, %s" %(act_msg,type(act_msg)), is_console=False)
     while ((act_msg.lower() != expected_notification.lower()) and waittimer.active()):
         #print("Waiting for Actual notification message.",is_console=False)
         act_msg = self.get_text("LabelValueNotificationMsg")
         if act_msg:
             print("Actual message is %s" %act_msg,is_console=False)
     
     print("Actual message retrieved is {%s}" %act_msg,is_console=False)
         
     try:
         self.click_element('close_notification')
         print("Notification message closed.", is_console=False)
     except:
         pass
     
     result = 0
     if act_msg.lower() == expected_notification.lower():
         result = 1
     
     if not result:
         match = self.match_string_to_regexp(expected_notification, act_msg)
         result = 1 if match == 1 else 0
     
     return result
Example #19
0
 def test_library_arguments_are_resolved(self):
     sugs = self.ns.get_suggestions_for(self._get_controller(TESTCASEFILE_WITH_EVERYTHING).keywords[0],
                                        'Get ')
     assert_true(len(sugs) > 0)
     for item in sugs:
         if item.name == 'Get Mandatory':
             return
     fail('Get mandatory not found')
Example #20
0
 def test_library_arguments_are_resolved(self):
     sugs = self.ns.get_suggestions_for(self._get_controller(TESTCASEFILE_WITH_EVERYTHING).keywords[0],
                                        'Get ')
     assert_true(len(sugs) > 0)
     for item in sugs:
         if item.name == 'Get Mandatory':
             return
     fail('Get mandatory not found')
Example #21
0
 def enter_take_over(self, class_take_over):
     try:
         take_over = self.browser.find_element_by_class_name(
             class_take_over)
         take_over.click()
     except NoSuchElementException:
         asserts.fail('****** Expected page element not found!\n'
                      '****** Unable to locate "{page_element}".\n'.format(
                          page_element=class_take_over))
    def switch_port(self, port_locator):
        """
        Make specified port as current port.

        Fails if specified port is not added in the library
        instance.
        """
        if port_locator not in self._ports:
            asserts.fail('No such port.')
        self._current_port_locator = port_locator
 def _attr_should_be(self, attr, value, port_locator):
     """
     Fails specified attribute does not have expected value.
     """
     value = 1 if is_truthy_on_off(value) else 0
     status = getattr(self._port(port_locator), attr)
     if value != status:
         msg = '%s should be %s but %s.' % (
             attr.upper(), to_on_off(value), to_on_off(status))
         asserts.fail(msg)
 def _attr_should_be(self, attr, value, port_locator):
     """
     Fails specified attribute does not have expected value.
     """
     value = 1 if is_truthy_on_off(value) else 0
     status = getattr(self._port(port_locator), attr)
     if value != status:
         msg = '%s should be %s but %s.' % (attr.upper(), to_on_off(value),
                                            to_on_off(status))
         asserts.fail(msg)
    def switch_port(self, port_locator):
        """
        Make specified port as current port.

        Fails if specified port is not added in the library
        instance.
        """
        if port_locator not in self._ports:
            asserts.fail('No such port.')
        self._current_port_locator = port_locator
 def ansible_result_host_message(self, result, host):
     """
     Get the message (if one exists, otherwise empty string) whether the 
     module executed successfully or not.
     @param result: result returned from Runner.run()
     @param host: host name
     """
     mergedResults = dict(result["contacted"].items() + result["dark"].items())
     if not mergedResults.has_key(host):
         asserts.fail("No entry in results for host %s" % host)
     return mergedResults[host].get("msg", "") # returns empty string by default
Example #27
0
    def play_music(self, url):
        data = PlayToJson(url).to_json()
        api = _API_BASEPATH + PlivoApi.PLAY_MUSIC % call_uuid
        headers = {'Content-Type': 'application/json'}

        response = requests.post(api, data=data, headers=headers, auth=(AuthId.auth_id, AuthId.auth_token))
        content = str(response.content, encoding='utf-8')
        assert_equal(response.status_code, 202, msg='Api response fails with message ' + content)
        try:
            res_msg = json.loads(content)
        except json.JSONDecodeError:
            fail("Play music api response is not JSON.")
        assert_equal(res_msg['message'], 'play started')
Example #28
0
 def fabric_run_command_and_return_value(self, cmd, _pty=None):
     if _pty is not None:
         with settings(warn_only=True):
             fabric_run_return = run(cmd, pty=_pty)
             return fabric_run_return
     else:
         with settings(warn_only=True):
             fabric_run_return = run(cmd)
             return fabric_run_return
     if fabric_run_return.return_code == 1:
         print "find run commnand received nonzero return code 1"
         asserts.fail(u"fabric 执行命令“%s”时候出错," % (cmd))
     return self
Example #29
0
    def get_live_call_details(self):
        params = {
            'status': 'live'
        }
        api = _API_BASEPATH + PlivoApi.CALL + call_uuid + "/"

        response = requests.get(api, params=params, auth=(AuthId.auth_id, AuthId.auth_token))
        content = str(response.content, encoding='utf-8')
        assert_equal(response.status_code, 200, msg='Api response fails with message ' + content)
        try:
            res_msg = json.loads(content)
        except json.JSONDecodeError:
            fail_message = "Live call details api response is not JSON" + content
            fail(fail_message)
    def async_get_request(self, urls=[]):
        """
        Performs async calls, then waits for all the responses.
        Returns a dictionary with the url as key containing the response object.

        urls must be a list variable.
        """
        errors = []
        try:
            response = asyncio.run(self.main(urls))
        except Exception as e:
            fail(str(e))
        data = asyncio.run(self._process_response_to_dict(response))
        return data
    def read_data_should_be(self, data, encoding=None, port_locator=None):
        """
        Fails if all read bytes from the port not equals to specifed data.

        This keyword compares values in byte space; data is encoded to bytes
        then compared to bytes read from the port.
        """
        bdata = self._encode(data, encoding)
        bread = self._port(port_locator).read_all()
        if bread != bdata:
            hex_bread = self._decode(bread, 'hexlify')
            hex_bdata = self._decode(bdata, 'hexlify')
            msg = "'%s'(read) != '%s'(data)" % (hex_bread, hex_bdata)
            asserts.fail(msg)
Example #32
0
 def make_conference_call(self, fromNo, toNo, answer_url):
     if ',' in toNo:
         for no in toNo.split(','):
             msg = CallToJson(fromNo, no, answer_url)
             print("JSON", msg.to_json())
             headers = {'Content-Type': 'application/json'}
             response = requests.post(_API_BASEPATH + PlivoApi.CALL, data=msg.to_json(),
                                      headers=headers, auth=(AuthId.auth_id, AuthId.auth_token))
             content = str(response.content, encoding='utf-8')
             try:
                 res_msg = json.loads(content)
             except json.JSONDecodeError:
                 fail("Conference api response is not JSON.")
             print("RESPONSE IS : ", response.status_code, "   ", response.content, "   ")
             assert_equal(response.status_code, 201, msg='Api response fails with message ' + content)
Example #33
0
    def make_a_call(self, fromNo, toNo, answer_url):
        msg = CallToJson(fromNo, toNo, answer_url)
        headers = {'Content-Type': 'application/json'}

        response = requests.post(_API_BASEPATH + PlivoApi.CALL, data=msg.to_json(),
                                 headers=headers, auth=(AuthId.auth_id, AuthId.auth_token))
        content = str(response.content, encoding='utf-8')
        assert_equal(response.status_code, 201, msg='Api response fails with message ' + content)
        try:
            res_msg = json.loads(content)
        except json.JSONDecodeError:
            fail("Make call api response is not JSON.")

        global call_uuid
        call_uuid = self.get_live_call_id()
    def _port(self, port_locator=None, fail=True):
        """
        Lookup port by name.

        If port_locator is None or string '_', current port
        is returned.
        If specified port is not found, exception is raised
        when fail is True, otherwise None is returned silently.
        """
        if port_locator in [None, '_']:
            port_locator = self._current_port_locator
        port = self._ports.get(port_locator, None)
        if port is None and is_truthy(fail) is True:
            asserts.fail('No such port.')
        return port
Example #35
0
 def fabric_run_command(self, cmd, _pty=None, _timeout=None):
     if _timeout is not None:
         timeout = _timeout
     else:
         timeout = 900
     if _pty is not None:
         with settings(warn_only=True):
             fabric_run_return = run(cmd, timeout, pty=_pty)
     else:
         with settings(warn_only=True):
             fabric_run_return = run(cmd, timeout)
     if fabric_run_return.return_code == 1:
         print "find run commnand received nonzero return code 1"
         asserts.fail(u"fabric 执行命令“%s”时候出错," % (cmd))
     return self
    def read_data_should_be(
            self, data, encoding=None, port_locator=None):
        """
        Fails if all read bytes from the port not equals to specifed data.

        This keyword compares values in byte space; data is encoded to bytes
        then compared to bytes read from the port.
        """
        bdata = self._encode(data, encoding)
        bread = self._port(port_locator).read_all()
        if bread != bdata:
            hex_bread = self._decode(bread, 'hexlify')
            hex_bdata = self._decode(bdata, 'hexlify')
            msg = "'%s'(read) != '%s'(data)" % (hex_bread, hex_bdata)
            asserts.fail(msg)
    def _port(self, port_locator=None, fail=True):
        """
        Lookup port by name.

        If port_locator is None or string '_', current port
        is returned.
        If specified port is not found, exception is raised
        when fail is True, otherwise None is returned silently.
        """
        if port_locator in [None, '_']:
            port_locator = self._current_port_locator
        port = self._ports.get(port_locator, None)
        if port is None and is_truthy(fail) is True:
            asserts.fail('No such port.')
        return port
    def get_port_parameter(self, param_name, port_locator=None):
        """
        Returns specified parameter of the port.

        By default, current port is inspected.
        Available parameters are those can be set at library import
        or Add Port keyword: baudrate, bytesize, parity, stopbits,
        timeout, xonxoff, rtscts, write_timeout, dsrdtr and
        inter_byte_timeout.

        Fails on wrong param_name or port_locator.
        """
        if param_name not in self._defaults:
            asserts.fail('Wrong parameter name.')
        port = self._port(port_locator)
        return getattr(port, param_name)
Example #39
0
 def isotpCAN_send_and_rec_rsp(self, send_data):
     '''
     功能:
     - 发送并接收CAN数据, 判断肯定响应
     - 通过条件 : 收到当前指定的CAN ID的CAN数据
     
     参数:
     - send_data : 发送的数据
     (注意没有默认值的参数是必填的,有默认值的参数不填写,就会按照默认的参数执行)
     
     例子:
     | isotpCAN_send_and_no_rsp | 10 01 |
     '''
     self._isotp_nor_pro(send_data)
     if not self.rsp_data:
         asserts.fail('没有收到任何当前指定的CAN ID的应答数据')
    def get_port_parameter(self, param_name, port_locator=None):
        """
        Returns specified parameter of the port.

        By default, current port is inspected.
        Available parameters are those can be set at library import
        or Add Port keyword: baudrate, bytesize, parity, stopbits,
        timeout, xonxoff, rtscts, write_timeout, dsrdtr and
        inter_byte_timeout.

        Fails on wrong param_name or port_locator.
        """
        if param_name not in self._defaults:
            asserts.fail('Wrong parameter name.')
        port = self._port(port_locator)
        return getattr(port, param_name)
Example #41
0
def judge_alarm_data(data):
    '''
    参数:数据,正确的报警次数
    功能:判断报警数据是否正确,如果报警数据错误间隔条数不为59,或者没有报警数据,或者时间间隔错误就报错
    元素0:报警时间,元素1:时间间隔错误数据,元素2:上报02数据的时间错误,与服务器时间差10s以上
    '''
    err_info = ''
    if int(data[0]) != 59 and int(data[0]) != 60:
        err_info = err_info + 'alarm info num error \n'
    if data[1] != []:
        err_info = err_info + 'interval time error {0}\n'.format(data[1])
    if data[2] != []:
        err_info = err_info + 'terminal time is not accurate {0}\n'.format(
            data[2])
    if err_info != '':
        asserts.fail(err_info)
Example #42
0
 def adj_colt_pow_freq(self, freq):
     '''
     功能:
     - 切换电流采集频率
     - 测试用例失败的时候记得把采集频率置回5s
     - 通过条件:参数填写无误
     
     参数:
     - freq: 采集频率ms
     '''
     if not freq.isdigit():
         asserts.fail('参数应该为数字')
         
     self._kill_all_process('python3.7 /home/pi/hlrfw/scripts/collect_current_data.py')
     time.sleep(1)
     os.system('python3.7 /home/pi/hlrfw/scripts/collect_current_data.py {}'.format(freq))
Example #43
0
    def get_call_details(self, api, params={}):
        response = requests.get(api, params=params, auth=(AuthId.auth_id, AuthId.auth_token))
        content = str(response.content, encoding='utf-8')
        assert_equal(response.status_code, 200)
        try:
            res_msg = json.loads(content)
        except json.JSONDecodeError:
            fail_message = "Calls get api response is not JSON" + content
            fail(fail_message)
        print("RES ", res_msg)
        try:
            uuid_call = res_msg['calls'][0]
        except IndexError:
            uuid_call = ''
        except KeyError:
            uuid_call = ''

        return uuid_call
    def set_port_parameter(self, param_name, value, port_locator=None):
        """
        Sets port parameter.

        By default, current port is affected.
        Available parameters are same as Get Port Parameter keyword.
        For most parameter, changing it on opened port will cause
        port reconfiguration.
        Fails on wrong param_name or port_locator.
        Returns previous value.
        """
        if param_name not in self._defaults:
            asserts.fail('Wrong parameter name.')
        port = self._port(port_locator, fail=True)
        prev_value = getattr(port, param_name)
        param_type = type(self._defaults.get(param_name))
        setattr(port, param_name, param_type(value))
        return prev_value
Example #45
0
    def create_endpoint(self, user, password, alias, application_id):
        msg = EndpointToJson(user, password, alias, application_id)
        headers = {'Content-Type': 'application/json'}

        response = requests.post(_API_BASEPATH + PlivoApi.ENDPOINT, data=msg.to_json(msg),
                                 headers=headers, auth=(AuthId.auth_id, AuthId.auth_token))
        content = str(response.content, encoding='utf-8')
        assert_equal(response.status_code, 201, msg='Api response fails with message ' + content)
        res_msg = {}
        try:
            res_msg = json.loads(content)
        except json.JSONDecodeError:
            fail("Endpoint api response is not JSON.")
        assert_equal(res_msg['message'], 'created')
        global end_id
        end_id = res_msg['endpoint_id']

        return end_id
    def read_all_and_log(self, loglevel='debug', encoding=None, port_locator=None):
        """
        Read all available data and write it to log.

        This is useful if you want to discard bytes in read queue, but just want
        to log it.
        Loglevel can be 'info', 'debug' or 'warn' (case insensitive).
        Any other level causes error.
        If `encoding` is not given, default encoding is used.
        """
        loglevel = loglevel.upper()
        logger_func = self.LOGGER_MAP.get(loglevel, None)
        if logger_func is None:
            raise asserts.fail('Invalid loglevel.')
        logger_func(self.read_all_data(encoding, port_locator))
    def add_port(self, port_locator, open=True, make_current=False, **kwargs):
        """
        Adds new port with specified locator.

        port_locator may be in (traditional) port name or url format.
        If `open` has false value, the port is closed immediately.
        Parameters given in kwargs will override those library defaults
        initialized on import.
        If make_current has truth value, the opened port is set to current
        port. Note that if there's only one port in the library instance,
        it will always be current port, regardless of make_current's value.

        Fails if specified port_locator is already used in this library
        instance.

        Returns created port instance.
        """
        if port_locator in [None, '', '_']:
            asserts.fail('Invalid port locator.')
        elif port_locator in self._ports:
            asserts.fail('Port already exists.')
        serial_kw = dict(
            (k, type(v)(kwargs.get(k, v)))
            for k, v in self._defaults.items())
        # try url first, then port name
        try:
            port = serial_for_url(port_locator, **serial_kw)
        except (AttributeError, ValueError):
            port = Serial(port_locator, **serial_kw)
        asserts.assert_not_none(port, 'Port initialization failed.')
        self._ports[port_locator] = port
        if port.is_open and (is_truthy(open) is False):
            port.close()
        if self._current_port_locator is None or make_current:
            self._current_port_locator = port_locator
        return port
Example #48
0
 def assert_in_keywords(self, keywords, *kw_names):
     for kw_name in kw_names:
         if not self._in_keywords(keywords, kw_name):
             fail(kw_name)
 def current_port_should_be(self, port_locator):
     """
     Fails if given port locator does not match current port locator.
     """
     if port_locator not in [self._current_port_locator, '_']:
         asserts.fail('Port does not match.')