Robot Framework从类中生成两个实例而不是一个实例

时间:2014-12-24 13:46:34

标签: python import robotframework

我有一个python类:

from robot.api import logger
class TestClass(object):
    def __init__(self, arg1, arg2):
        self.arg1 = arg1
        self.arg2 = arg2
        logger.info('initialized', also_console=True)

    def print_arg1(self):
        print self.arg1

    def print_arg2(self):
        print self.arg2

我写了一个名为“CommonKeywords.robot”的关键字文件:

*** Settings ***
Library     ../Libs/TestClass.py     arg1   arg2        WITH NAME    class1

*** Keywords ***
print arg1 class1
    class1.print_arg1

print arg2 class1
    class1.print_arg2

我的方案文件是“scenario.robot”:

*** Settings ***
Resource    ../Keywords/CommonKeywords.robot

*** Test Cases ***
Test Prints
    print arg1 class1

这是我的项目结构:

Test
---- Keywords
     ---- CommonKeywords.robot
---- Scenarios
     ---- scenario.robot
---- Libs
     ---- TestClass.py

我将目录更改为Test/Scenarios并在命令行中键入pybot scenario.robot。该脚本打印两个initialized,这意味着它已经初始化了两次对象:

enter image description here

问题是什么?

我改变了我的课程:

from robot.api import logger
class TestClass(object):
    ROBOT_LIBRARY_SCOPE = 'GLOBAL'
    def __init__(self, arg1, arg2):
        self.arg1 = arg1
        self.arg2 = arg2
        logger.info('initialized', also_console=True)

    def print_arg1(self):
        print self.arg1

    def print_arg2(self):
        print self.arg2

这是我想要的,我在应用布莱恩的答案后得到了:

enter image description here

1 个答案:

答案 0 :(得分:3)

您需要设置库的范围。

来自Robot Framework User's Guide(强调我的):

  

Robot Framework试图让测试用例独立于每个测试用例   other:默认情况下,它为创建测试库的新实例   每个测试用例。但是,这种行为并不总是令人满意的,   因为有时测试用例应该能够共享一个共同的状态。   此外,所有库都没有状态并创建新的   它们的实例根本不需要。

如果您希望每个测试套件创建一次类,您可以像这样设置范围:

class TestClass(object):

    ROBOT_LIBRARY_SCOPE = 'TEST SUITE'

    def __init__(self, arg1, arg2):
        ...

如果您希望在整个测试运行期间仅对该类进行一次实例化,则可以将ROBOT_LIBRARY_SCOPE设置为'GLOBAL'