如何让Robot Framework调用的测试向控制台返回信息

9 投票
3 回答
7508 浏览
提问于 2025-04-16 15:03

我有一个机器人框架的测试套件,它会调用一个Python方法。我希望这个Python方法能在控制台上返回一条消息,但不让测试失败。具体来说,我是想测量一个过程的时间。

我可以用“raise”来返回一条消息到控制台,但这样会导致测试失败。

 def doSomething(self, testCFG={}):
    '''
    Do a process and time it. 
    '''
testCFG['operation'] = 'doSomething'
startTime = time.time()
response=self.Engine(testCFG)
endTime = time.time()
duration = int(round(endTime-startTime))
raise "doSomething took", duration//60 , "minutes and", duration%60, "seconds."
errmsg = 'doSomething failed'
if testCFG['code']: raise Exception(errmsg)

或者我可以用“print”把消息返回到日志文件和报告中,这样就不会让测试失败,但这些信息只能在报告里看到,而不能在控制台上看到。

 def doSomething(self, testCFG={}):
    '''
    Do a process and time it. 
    '''
testCFG['operation'] = 'doSomething'
startTime = time.time()
response=self.Engine(testCFG)
endTime = time.time()
duration = int(round(endTime-startTime))
print "doSomething took", duration//60 , "minutes and", duration%60, "seconds."
errmsg = 'doSomething failed'
if testCFG['code']: raise Exception(errmsg)

如果我选择“print”这个选项,我得到的是这样的结果:

==============================================================================
Do Something :: Do a process to a thing(Slow Process).                | PASS |
------------------------------------------------------------------------------
doSomething :: Overall Results                                        | PASS |
1 critical test, 1 passed, 0 failed
1 test total, 1 passed, 0 failed
==============================================================================

我想要的是这样的结果:

==============================================================================
Do Something :: Do a process to a thing(Slow Process).                | PASS |
doSomething took 3 minutes and 14 seconds.
------------------------------------------------------------------------------
doSomething :: Overall Results                                        | PASS |
1 critical test, 1 passed, 0 failed
1 test total, 1 passed, 0 failed
==============================================================================

3 个回答

0

让你的库返回一个字符串,然后使用 Set Test Message 来显示这个字符串。

My Test Case  [Documentation]  display data returned from lib call
  ${r} =  mylib.libfunc  arg=param
  Set Test Message  libfunc returned ${r}

参考链接: http://robotframework.googlecode.com/hg/doc/libraries/BuiltIn.html#Set%20Test%20Message

更新内容:

  1. 新链接: http://robotframework.org/robotframework/latest/libraries/BuiltIn.html#Set%20Test%20Message
  2. 新的 Log To Console 命令可以实时输出到控制台(也就是说,在测试执行过程中输出,而不是像 Set Test Message 只在测试用例结束时输出)。
2

你可以使用 robot.api 这个库。这里是这个库的文档。

https://robot-framework.readthedocs.org/en/latest/_modules/robot/api/logger.html

13

既然你在用Python,有两种简单的方法可以选择:

  1. 把你的信息写到stderr。这些信息会同时写入机器人的日志文件和控制台。不过有个限制,就是这些信息只有在你执行的关键词完成后才会显示在控制台上。好处是这种方法也适用于基于Java的库。

  2. 把你的信息写到sys.__stdout__。机器人只会拦截sys.stdoutsys.stderr,而不会干扰sys.__stdout__(以及sys.__stderr__),这也是所有正常工作的Python程序应该遵循的做法。这些信息只会显示在控制台上,但你也可以把它们写入sys.stdout,这样它们也会出现在日志文件里。

撰写回答