pybot失败时如何创建带有变量的.txt文件

How to create .txt file with variables when pybot fails

我有一个场景,当 pybot 失败时我需要创建文本文件。当测试用例失败时,它应该触发一个文本文件,该文件应该由 jenkins 下游作业获取并更新它的环境变量

当作业失败时,我正在制作下游作业测试部署 运行,如图所示。我还需要在失败时传递一个更新环境变量的文件

创建 jenkins 作业时,"Trigger even if the build fails" 有一个选项。


(来源:bristiel.com

阅读此博客 post 了解完整的上下文: http://laurent.bristiel.com/create-jenkins-job-for-robot-framework/

编辑:

要在 stderr 上记录环境变量,您可以这样做:

import os
import sys
class Proxy():
    def __init__(self,out):
        self.out=out
    def write(self,msg):
        self.out.write(msg)
        exists=os.path.isfile("environ vars.txt")
        with open("environ vars.txt",'a' if exists else 'w') as f:
            f.write(str(os.environ))

sys.stderr=Proxy(sys.stderr)

最简单的解决方案是创建一个 suite teardown 关键字来写入文件。例如:

*** Settings ***
Library           OperatingSystem
Suite Teardown    Save variables on failure

*** Test Case ***
Example
    fail    trigger saving of variables

*** Keywords ***
Save variables on failure
    run keyword if any tests failed    save variables to file

Save variables to file
    append to file    /tmp/variables.txt    export FOO='this is foo'\n
    append to file    /tmp/variables.txt    export BAR='this is bar'\n

稍微复杂一点的例子是创建一个python模块,可以作为listener使用,然后在pybot完成后写入文件。

例如,python 模块可能如下所示:

class TestMonitor(object):
    ROBOT_LISTENER_API_VERSION = 2

    def __init__(self):
        self.ROBOT_LIBRARY_LISTENER = self

    def end_suite(self, name, attrs):
        if attrs['id'] == "s1" and attrs['status'] == "FAIL":
            with open("/tmp/variables.txt", "w") as f:
                f.write("export FOO='this is foo'\n")
                f.write("export BAR='this is bar\n")

您可以像导入任何其他库一样将它导入您的套件。例如:

*** Settings ***
Library           TestMonitor

*** Test Case ***
Example
    fail    trigger saving of variables