【问题标题】:Robot Framework Keyword with Python: Error with unmatched string or IP. How to fix this?使用 Python 的机器人框架关键字:字符串或 IP 不匹配时出错。如何解决这个问题?
【发布时间】:2015-09-24 10:45:30
【问题描述】:

我正在尝试为机器人框架编写一个关键字,正如@Brayan Oakley 在问题中所建议的那样:

How to write python function to test the matched strings (to use for Robot framework keyword)?

我的 Python 文件:

import os,re

def check_IP():
    cmd = ' netstat -ano '
    output = os.popen(cmd).read()
    match1 = re.findall('.* (1.1.1.1).*',output)
    mat1 = ['1.1.1.1']
    if match1 == mat1:
        print "IP addr found"
    if match1 != mat1:
        raise Exception('No matching IP...')

check_IP()

我正在尝试匹配“netstat -ano”命令中的 IP 地址。如果匹配,我会按预期收到“找到 IP 地址”消息。

但如果没有找到 IP 地址,我会按预期收到异常,但会显示以下错误消息。

C:\Users\test\Desktop>python check.py
Traceback (most recent call last):
  File "check.py", line 13, in <module>
    check_IP()
  File "check.py", line 11, in check_IP
    raise Exception('No matching IP...')
Exception: No matching IP...

C:\Users\test\Desktop>

请问有什么解决办法吗?

【问题讨论】:

    标签: python python-2.7 robotframework


    【解决方案1】:

    代码正在按照您的要求执行。您在机器人上下文之外运行代码,这就是 python 处理异常的方式。

    如果您不想查看堆栈跟踪,请捕获异常并打印您想要的任何消息。

        try:
            check_IP()
        except Exception as e
            print str(e)
    

    当然,如果您使用check_IP 作为关键字,您会想要删除所有这些代码。

    【讨论】:

      【解决方案2】:

      使用以下机器人文件:

      *** Settings ***
      Documentation   Test Stability Tests
      Library        Network.py
      
      *** Test Cases ***
      Test: Test Robot File
          Check Network Status
      

      使用以下 Python 文件

      import os, re
      def check_network_status():
          cmd = ' netstat -ano '
          output = os.popen(cmd).read()
          match1 = re.findall('.* (1.1.1.1).*',output)
          mat1 = ['1.1.1.1']
          if match1 == mat1:
              print("IP Address found")
          elif match1 != mat1:
              raise AssertionError("IP Address not Found")
      

      注意:不要调用 Python 文件中的函数。 只需在 python 文件中创建类和函数(如果你想在将来)。 它们会在运行时自动被取消。

      【讨论】:

        猜你喜欢
        • 2015-12-18
        • 1970-01-01
        • 1970-01-01
        • 2021-07-21
        • 1970-01-01
        • 2013-11-08
        • 1970-01-01
        • 2021-08-15
        • 2016-01-03
        相关资源
        最近更新 更多