Robot Framework从类中生成两个实例而不是一个实例 [英] Robot Framework makes two instances from the class instead of one

查看:683
本文介绍了Robot Framework从类中生成两个实例而不是一个实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个python类:

I have a python class:

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的关键字文件:

I have wrote a keyword file named "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:

And my scenario file is "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 。该脚本打印两个初始化,这意味着它已经初始化了两次对象:

I change directory to the Test/Scenarios and type pybot scenario.robot in the command line. The script prints two initialized which means it had been initialized the object twice:

问题是什么?

我改变了我的课程:

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的答案后我得到了:

This is what I wanted and I have got after applying Bryan's answer:

推荐答案

你需要设定范围你的图书馆。

You need to set the scope of your library.

来自机器人框架用户指南(强调我的):


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

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.

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

If you want to have the class created once per test suite, you can set the scope like this:

class TestClass(object):

    ROBOT_LIBRARY_SCOPE = 'TEST SUITE'

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

如果你希望在整个测试运行的整个过程中只对类进行一次实例化,你可以设置 ROBOT_LIBRARY_SCOPE 'GLOBAL'

If you want the class instantiated just once for the life of the entire test run you can set ROBOT_LIBRARY_SCOPE to 'GLOBAL'.

这篇关于Robot Framework从类中生成两个实例而不是一个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆