gpt4 book ai didi

python - Robot Framework 从类中创建两个实例而不是一个

转载 作者:行者123 更新时间:2023-12-04 00:32:27 25 4
gpt4 key购买 nike

我有一个 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

问题是什么??

我这样改变了我的类(class):
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

这就是我想要的,并且在应用 Bryan 的回答后得到了:

enter image description here

最佳答案

您需要设置库的范围。

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

Robot Framework attempts to keep test cases independent from each other: by default, it creates new instances of test libraries for every test case. However, this behavior is not always desirable, because sometimes test cases should be able to share a common state. Additionally, all libraries do not have a state and creating new instances of them is simply not needed.



如果您想为每个测试套件创建一次类,您可以像这样设置范围:
class TestClass(object):

ROBOT_LIBRARY_SCOPE = 'TEST SUITE'

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

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

关于python - Robot Framework 从类中创建两个实例而不是一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27637902/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com