Ejemplo n.º 1
0
 def log_list(self,list_,level='INFO'):
     """
     logs the length and contents of the 'list' using given 'level'.
     Valid levels aer TRACE,DEBUG,INFO(defalt), and WARN
     if you only want to the length,use keyword 'Get length' from the BuiltIn library.
     """
     logger.write('\n'.join(self._log_list(list_)),level)
Ejemplo n.º 2
0
 def report_invalid_syntax(self, message, level='ERROR', parent=None):
     parent = parent or getattr(self, 'parent', None)
     if parent:
         parent.report_invalid_syntax(message, level)
     else:
         from robot.api import logger
         logger.write(message, level)
 def write(self, msg, level, html=False):
     with self.lock:
         thread = threading.currentThread().getName()
         if thread in self.LOGGING_THREADS:
             logger.write(msg, level, html)
         else:
             message = BackgroundMessage(msg, level, html)
             self._messages.setdefault(thread, []).append(message)
    def log_response_status(self, log_level='INFO'):
        """
        Logs the response status line

        Specify `log_level` (default: "INFO") to set the log level.
        """

        logger.write("Response status line: %s" % self.response.status, log_level)
Ejemplo n.º 5
0
    def log_list(self, list_, level='INFO'):
        """Logs the length and contents of the ``list`` using given ``level``.

        Valid levels are TRACE, DEBUG, INFO (default), and WARN.

        If you only want to the length, use keyword `Get Length` from
        the BuiltIn library.
        """
        logger.write('\n'.join(self._log_list(list_)), level)
Ejemplo n.º 6
0
    def log_dictionary(self, dictionary, level='INFO'):
        """Logs the size and contents of the ``dictionary`` using given ``level``.

        Valid levels are TRACE, DEBUG, INFO (default), and WARN.

        If you only want to log the size, use keyword `Get Length` from
        the BuiltIn library.
        """
        logger.write('\n'.join(self._log_dictionary(dictionary)), level)
    def log_response_headers(self, log_level='INFO'):
        """
        Logs the response headers, line by line.

        Specify `log_level` (default: "INFO") to set the log level.
        """
        logger.write("Response headers:", log_level)
        for name, value in self.response.headers.items():
            logger.write("%s: %s" % (name, value), log_level)
 def timer_log(self, timer_name="Global", log_level="INFO", result_format="number", exclude_millis="True"):
     current_time = get_current_time_for_timers()
     if timer_name not in self.TIMERS_DICTIONARY:
         message = "Time '%s' is not started." % timer_name
         raise AssertionError(message)
     else:
         delta = Time(current_time - self.TIMERS_DICTIONARY[timer_name]).convert(result_format, millis=is_falsy(exclude_millis))
         msg = "Timer \"%s\" current results is %s" % (
             timer_name, Time(current_time - self.TIMERS_DICTIONARY[timer_name]).convert("verbose", millis=is_falsy(exclude_millis)))
         logger.write(msg, log_level)
         return delta
    def log_response_body(self, log_level='INFO'):
        """
        Logs the response body.

        Specify `log_level` (default: "INFO") to set the log level.
        """
        if self.response.body:
            logger.write("Response body:", log_level)
            logger.write(self.response.body, log_level)
        else:
            logger.debug("No response body received", log_level)
Ejemplo n.º 10
0
    def log_element(self, source, level="INFO", xpath="."):
        """Logs the string representation of the specified element.

        The element specified with `source` and `xpath` is first converted into
        a string using `Element To String` keyword internally. The resulting
        string is then logged using the given `level`.

        The logged string is also returned.
        """
        string = self.element_to_string(source, xpath)
        logger.write(string, level)
        return string
    def Compare_Files(self, p_szWorkFile, p_szReferenceFile):
        """ 比较两个文件是否一致  """
        """
        输入参数:
             p_szWorkFile:        需要比对的当前结果文件
             p_szReferenceFile:  需要比对的结果参考文件

        返回值:
            True           比对完成成功
            False          比对中发现了差异

        例外:
            在Compare_Break_With_Difference为True后,若比对发现差异,则抛出例外
        """
        if self.__Reference_LogDirLists is None:
            if "T_LOG" in os.environ:
                T_LOG = os.environ["T_LOG"]
                m_T_LOG_environs = shlex.shlex(T_LOG)
                m_T_LOG_environs.whitespace = ','
                m_T_LOG_environs.quotes = "'"
                m_T_LOG_environs.whitespace_split = True
                self.__Reference_LogDirLists = list(m_T_LOG_environs)

        # 检查work文件是否存在,如果存在,则文件是全路径
        if os.path.exists(p_szWorkFile):
            # 传递的是全路径
            (m_WorkFilePath, m_TempFileName) = os.path.split(p_szWorkFile)
            (m_ShortWorkFileName,
             m_WorkFileExtension) = os.path.splitext(m_TempFileName)
            # 如果定义了T_WORK,则dif文件生成在T_WORK下, 否则生成在当前目录下
            if "T_WORK" in os.environ:
                m_DifFilePath = os.environ["T_WORK"]
                m_DifFileName = m_ShortWorkFileName + '.dif'
                m_SucFilePath = os.environ["T_WORK"]
                m_SucFileName = m_ShortWorkFileName + '.suc'
            else:
                m_DifFilePath = os.getcwd()
                m_DifFileName = m_ShortWorkFileName + '.dif'
                m_SucFilePath = os.getcwd()
                m_SucFileName = m_ShortWorkFileName + '.suc'
            m_DifFullFileName = os.path.join(m_DifFilePath, m_DifFileName)
            m_SucFullFileName = os.path.join(m_SucFilePath, m_SucFileName)
            m_szWorkFile = p_szWorkFile
        else:
            if "T_WORK" not in os.environ:
                logger.info('===============   work log [' + p_szWorkFile +
                            '] does not exist. ' +
                            ' T_WORK env does not exist too ============')
                if self.__BreakWithDifference:
                    raise ExecutionFailed(message=(
                        '===============   work log [' + p_szWorkFile +
                        '] does not exist. ' +
                        ' T_WORK env does not exist too ============'),
                                          continue_on_failure=True)
                return False

            # 传递的不是绝对路径,是相对路径
            (m_ShortWorkFileName,
             m_WorkFileExtension) = os.path.splitext(p_szWorkFile)
            # 如果定义了T_WORK,则dif文件生成在T_WORK下, 否则生成在当前目录下
            m_DifFilePath = os.environ["T_WORK"]
            m_DifFileName = m_ShortWorkFileName + '.dif'
            m_SucFilePath = os.environ["T_WORK"]
            m_SucFileName = m_ShortWorkFileName + '.suc'
            m_DifFullFileName = os.path.join(m_DifFilePath, m_DifFileName)
            m_SucFullFileName = os.path.join(m_SucFilePath, m_SucFileName)
            m_szWorkFile = os.path.join(os.environ['T_WORK'], p_szWorkFile)

        # remove old file first
        if os.path.exists(m_DifFullFileName):
            os.remove(m_DifFullFileName)
        if os.path.exists(m_SucFullFileName):
            os.remove(m_SucFullFileName)

        # check if work file exist
        if not os.path.isfile(m_szWorkFile):
            m_CompareResultFile = open(m_DifFullFileName, 'w')
            m_CompareResultFile.write('===============   work log [' +
                                      p_szWorkFile +
                                      '] does not exist ============')
            m_CompareResultFile.close()
            if self.__BreakWithDifference:
                raise ExecutionFailed(
                    message=('===============   work log [' + p_szWorkFile +
                             '] does not exist ============'),
                    continue_on_failure=True)
            return False

        # search reference log
        m_ReferenceLog = None
        if self.__Reference_LogDirLists is not None:
            for m_Reference_LogDir in self.__Reference_LogDirLists:
                m_TempReferenceLog = os.path.join(m_Reference_LogDir,
                                                  p_szReferenceFile)
                if os.path.isfile(m_TempReferenceLog):
                    m_ReferenceLog = m_TempReferenceLog
                    break
        if m_ReferenceLog is None:
            m_ReferenceLog = p_szReferenceFile
        if not os.path.isfile(m_ReferenceLog):
            logger.info('===============   reference log [' + m_ReferenceLog +
                        '] does not exist ============')
            m_CompareResultFile = open(m_DifFullFileName, 'w')
            m_CompareResultFile.write('===============   reference log [' +
                                      m_ReferenceLog +
                                      '] does not exist ============')
            m_CompareResultFile.close()
            if self.__BreakWithDifference:
                raise ExecutionFailed(
                    message=('===============   reference log [' +
                             m_ReferenceLog + '] does not exist ============'),
                    continue_on_failure=True)
            return False

        # compare file
        m_Comparer = POSIXCompare()
        try:
            # 这里的CompareResultList是一个被翻转了的列表,在输出的时候,需要翻转回来
            (m_CompareResult,
             m_CompareResultList) = m_Comparer.compare_text_files(
                 m_szWorkFile, m_ReferenceLog, self.__SkipLines,
                 self.__IgnoreEmptyLine, self.__CompareWithMask,
                 self.__CompareIgnoreCase, self.__CompareIgnoreTailOrHeadBlank)
        except DiffException as de:
            logger.info('Fatal Diff Exception:: ' + de.message)
            if self.__BreakWithDifference:
                raise ExecutionFailed(message=('Fatal Diff Exception:: ' +
                                               de.message),
                                      continue_on_failure=True)
            return False

        if m_CompareResult:
            m_CompareResultFile = open(m_SucFullFileName, 'w')
            m_CompareResultFile.close()
            logger.write("======= Succ file       [" + m_SucFullFileName +
                         "] >>>>> ")
            logger.write("  ===== Work file       [" +
                         os.path.abspath(m_szWorkFile) + "]")
            logger.write("  ===== Ref  file       [" +
                         os.path.abspath(m_ReferenceLog) + "]")
            logger.write("  ===== Mask flag       [" +
                         str(self.__CompareWithMask) + "]")
            logger.write("  ===== BlankSpace flag [" +
                         str(self.__CompareIgnoreTailOrHeadBlank) + "]")
            logger.write("  ===== Case flag       [" +
                         str(self.__CompareIgnoreCase) + "]")
            logger.write("  ===== Empty line flag [" +
                         str(self.__IgnoreEmptyLine) + "]")
            for row in self.__SkipLines:
                logger.write("  ===== Skip line       [" + str(row) + "]")
            return True
        else:
            logger.write("======= Diff file       [" + m_DifFullFileName +
                         "] >>>>> ")
            logger.write("  ===== Work file       [" +
                         os.path.abspath(m_szWorkFile) + "]")
            logger.write("  ===== Ref  file       [" +
                         os.path.abspath(m_ReferenceLog) + "]")
            logger.write("  ===== Mask flag       [" +
                         str(self.__CompareWithMask) + "]")
            logger.write("  ===== BlankSpace flag [" +
                         str(self.__CompareIgnoreTailOrHeadBlank) + "]")
            logger.write("  ===== Case flag       [" +
                         str(self.__CompareIgnoreCase) + "]")
            logger.write("  ===== Empty line flag [" +
                         str(self.__IgnoreEmptyLine) + "]")
            for row in self.__SkipLines:
                logger.write("  ===== Skip line       [" + str(row) + "]")

            m_CompareResultFile = open(m_DifFullFileName,
                                       'w',
                                       encoding="utf-8")
            for line in m_CompareResultList:
                print(line, file=m_CompareResultFile)
                if self.__EnableConsoleOutPut:
                    if line.startswith('-'):
                        logger.write(
                            '<font style="color:Black;background-color:#E0E0E0">'
                            + line[0:7] + '</font>' +
                            '<font style="color:white;background-color:Red">' +
                            line[7:] + '</font>',
                            html=True)
                    elif line.startswith('+'):
                        logger.write(
                            '<font style="color:Black;background-color:#E0E0E0">'
                            + line[0:7] + '</font>' +
                            '<font style="color:white;background-color:Green">'
                            + line[7:] + '</font>',
                            html=True)
                    elif line.startswith('S'):
                        logger.write(
                            '<font style="color:Black;background-color:#E0E0E0">'
                            + line + '</font>',
                            html=True)
                    else:
                        logger.write(
                            '<font style="color:Black;background-color:#E0E0E0">'
                            + line[0:7] + '</font>' +
                            '<font style="color:Black;background-color:white">'
                            + line[7:] + '</font>',
                            html=True)
            m_CompareResultFile.close()
            logger.write("======= Diff file [" + m_DifFullFileName +
                         "] <<<<< ")
            if self.__BreakWithDifference:
                raise ExecutionFailed(
                    message=('Got Difference. Please check [' +
                             m_DifFullFileName + '] for more information.'),
                    continue_on_failure=self.__BreakWithDifference)
            return False
 def log(self, msg, level='INFO', html=False):
     if not is_noney(level):
         logger.write(msg, level.upper(), html)
Ejemplo n.º 13
0
 def test_logged_to_python(self):
     logger.info("Foo")
     logger.debug("Boo")
     logger.trace("Goo")
     logger.write("Doo", 'INFO')
     self.assertEquals(self.handler.messages, ['Foo', 'Boo', 'Goo', 'Doo'])
 def _embed_screenshot(path, level="INFO", width="1200px"):
     link = urljoin('file:', urllib.pathname2url(os.path.normpath(path)))
     logger.write('</td></tr><tr><td colspan="3"><a href="%s"><img src="%s" width="%s"></a>' % (link, link, width), level, html=True)
Ejemplo n.º 15
0
 def log_dictionary(self,dictionary,level='INFO'):
     logger.write('\n'.join(self.log_dictionary(dictionary)),level)
def log_with_all_levels():
    for level in 'trace debug info warn error'.split():
        msg = '%s msg' % level
        logger.write(msg+' 1', level)
        getattr(logger, level)(msg+' 2', html=False)
Ejemplo n.º 17
0
 def find_and_replace_keyword_from_multiple_CSV_file(
         self, textfilefolder, searchKeyword, replaceKeyword):
     self.__add_keyword(searchKeyword, replaceKeyword)
     logger.write("Find and Replacing Multiple Text file started at: " +
                  datetime.datetime.fromtimestamp(time.time()).strftime(
                      '%Y-%m-%d %H:%M:%S'))
     start_time = time.time()
     for fle in os.listdir(textfilefolder):
         if fle.endswith('.csv'):
             logger.write("Working With: " + fle)
             txtfile = open(os.path.join(textfilefolder, fle), 'r')
             txtcontent = txtfile.read()
             txtfile.close()
             newtxtcontent = self.__replace_keywords(txtcontent)
             txtfile = open(os.path.join(textfilefolder, fle), 'w')
             txtfile.write(newtxtcontent)
             txtfile.close()
             logger.write("Finished Working With: " + fle)
         else:
             logger.write("No Text files found in folder")
     logger.write("Find and Replacing Multiple Text file stoped at: " +
                  datetime.datetime.fromtimestamp(time.time()).strftime(
                      '%Y-%m-%d %H:%M:%S'))
     logger.write("Multiple Text File's Replace Operation took: " +
                  str(time.time() - start_time) + " seconds")
Ejemplo n.º 18
0
def log_with_all_levels():
    for level in 'trace debug info warn'.split():
        msg = '%s msg' % level
        logger.write(msg+' 1', level)
        getattr(logger, level)(msg+' 2', html=False)
    logger.write('whatever', level='invalid')
 def log_json(self, json_string, log_level='INFO'):
     """
     Logs a pretty printed version of the JSON document `json_string`.
     """
     for line in json.dumps(json_string, indent=2, ensure_ascii=False).split('\n'):
         logger.write(line, log_level)
 def log(self, msg, level='INFO', html=False):
     if not is_noney(level):
         logger.write(msg, level.upper(), html)
Ejemplo n.º 21
0
def log_html():
    logger.write('<b>debug</b>', level='DEBUG', html=True)
    logger.info('<b>info</b>', html=True)
    logger.warn('<b>warn</b>', html=True)
 def log(self, msg: str, level: str = "INFO", html: bool = False):
     if not is_noney(level):
         logger.write(msg, level.upper(), html)
Ejemplo n.º 23
0
 def fapi_log(self, message, repr=False):
     """ Log `message` to test report """
     logger.write(message)
 def write(self, msg, level, html=False):
     logger.write(msg, level, html)
Ejemplo n.º 25
0
 def test_logger_to_python_with_html(self):
     logger.info("Foo", html=True)
     logger.write("Doo", 'INFO', html=True)
     logger.write("Joo", 'HTML')
     self.assertEquals(self.handler.messages, ['Foo', 'Doo', 'Joo'])
Ejemplo n.º 26
0
 def _log(self, msg):
     logger.write(msg, self._logLevel, html=False)
 def log(self, msg, level='INFO', html=False):
     if level.upper() in LOG_LEVELS:
         logger.write(msg, level, html)
 def log_json(self, json_string, log_level='INFO'):
     """
     Logs a pretty printed version of the JSON document `json_string`.
     """
     for line in json.dumps(json_string, indent=2, ensure_ascii=False).split('\n'):
         logger.write(line, log_level)
def write(message, level):
    logger.write(message, level)
Ejemplo n.º 30
0
def log_with_all_levels():
    for level in 'trace debug info warn error'.split():
        msg = '%s msg' % level
        logger.write(msg + ' 1', level)
        getattr(logger, level)(msg + ' 2', html=False)
Ejemplo n.º 31
0
 def msg(self, msg, *args):
     # Forward telnetlib's debug messages to log
     if self._telnetlib_log_level != 'NONE':
         logger.write(msg % args, self._telnetlib_log_level)
Ejemplo n.º 32
0
 def _log(self, msg, level=None):
     msg = msg.strip()
     if msg:
         logger.write(msg, level or self._default_log_level)
Ejemplo n.º 33
0
 def _log(self, msg, level=None):
     msg = msg.strip()
     if msg:
         logger.write(msg, level or self._default_log_level)
Ejemplo n.º 34
0
    def connect_to(self,
                   host='localhost',
                   transport='https',
                   port='443',
                   username='******',
                   password='******',
                   alias=None,
                   enablepwd=None,
                   autorefresh=True):
        """This is the cornerstone of all testing. The Connect To
        keyword accepts the necessary parameters to setup an API connection to
        your node.

        Example:
        | Connect To | host=192.0.2.50 | transport=http | port=80 | username=myUser | password=secret |
        | Connect To | host=192.0.2.51 | username=myUser | password=secret |

        This function returns a connection index, which can be used to change
        connections during a test suite. Example:

        | ${switch1}= | Connect To | host=192.0.2.51 | username=myUser | password=secret |

        You can confirm which interface eAPI is listening on by running:
        | veos-node>show management api http-commands
        | *Enabled:        Yes*
        | *HTTPS server:   running, set to use port 443*
        | HTTP server:    shutdown, set to use port 80
        | VRF:            default
        | Hits:           28
        | Last hit:       2128 seconds ago
        | Bytes in:       1547
        | Bytes out:      283966
        | Requests:       1
        | Commands:       1
        | Duration:       0.055 seconds
        |    User        Hits       Bytes in       Bytes out    Last hit
        | ----------- ---------- -------------- --------------- ----------------
        |   admin       1          1547           283966       2128 seconds ago
        |
        | URLs
        | ---------------------------------------
        | *Management1 : https://192.0.2.50:443*

        You can confirm connectivity by firing up a browser and point it to
        https://<my_url>:<my_port>/command-api

        If you are new to eAPI see the Arista EOS Central article,
        [https://eos.arista.com/arista-eapi-101|Arista eAPI 101]
        """

        host = str(host)
        transport = str(transport)
        port = int(port)
        username = str(username)
        password = str(password)
        if alias:
            alias = str(alias)
        try:
            client = pyeapi.connect(host=host,
                                    transport=transport,
                                    username=username,
                                    password=password,
                                    port=port)
            client_node = pyeapi.client.Node(client)
            client_node.autorefresh = autorefresh
            client_node.enable_authentication(enablepwd)
            conn_indx = self._connection.register(client_node, alias)
        except Exception as e:
            raise e

        # Always try "show version" when connecting to a node so that if
        #  there is a configuration error, we can fail quickly.
        try:
            ver = self._connection.current.enable(['show version'
                                                   ])[0]['result']
            mesg = "Created connection to {}://{}:{}@{}:{}/command-api: "\
                "model: {}, serial: {}, systemMAC: {}, version: {}, "\
                "lastBootTime: {}".format(
                    transport, username, '****', host, port,
                    ver['modelName'], ver['serialNumber'],
                    ver['systemMacAddress'],
                    ver['version'], ver['bootupTimestamp'])
            logger.write(mesg, 'INFO', False)
        except Exception as e:
            raise e

        self.connections[conn_indx] = dict(conn=client,
                                           node=client_node,
                                           index=conn_indx,
                                           transport=transport,
                                           host=host,
                                           username=username,
                                           password=password,
                                           port=port,
                                           alias=alias,
                                           autorefresh=autorefresh)
        return conn_indx
Ejemplo n.º 35
0
 def test_logger_to_python_with_html(self):
     logger.info("Foo", html=True)
     logger.write("Doo", 'INFO', html=True)
     logger.write("Joo", 'HTML')
     self.assertEquals(self.handler.messages, ['Foo', 'Doo', 'Joo'])
Ejemplo n.º 36
0
 def log(self, msg, level='INFO', html=False):
     if level.upper() in LOG_LEVELS:
         logger.write(msg, level, html)
Ejemplo n.º 37
0
 def _log(self, msg, level):
     if logger:
         logger.write(msg, level)
     else:
         print '*%s* %s' % (level, msg)
Ejemplo n.º 38
0
 def test_logged_to_python(self):
     logger.info("Foo")
     logger.debug("Boo")
     logger.trace("Goo")
     logger.write("Doo", 'INFO')
     self.assertEquals(self.handler.messages, ['Foo', 'Boo', 'Goo', 'Doo'])
Ejemplo n.º 39
0
def log_html():
    logger.write('<b>debug</b>', level='DEBUG', html=True)
    logger.info('<b>info</b>', html=True)
    logger.warn('<b>warn</b>', html=True)
 def write(self, msg, level, html=False):
     logger.write(msg, level, html)
Ejemplo n.º 41
0
def log_with_all_levels():
    for level in 'trace debug info warn'.split():
        msg = '%s msg' % level
        logger.write(msg+' 1', level)
        getattr(logger, level)(msg+' 2', html=False)
    logger.write('whatever', level='invalid')
Ejemplo n.º 42
0
def write(message, level):
    logger.write(message, level)