Robot Framework makes two instances from the class instead of one

落爺英雄遲暮 提交于 2019-12-10 12:03:03

问题


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

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

And my scenario file is "scenario.robot":

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

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

This is my project structure:

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

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:

What is the problem??

I changed my class this way:

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

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


回答1:


You need to set the scope of your library.

From the Robot Framework User's Guide (emphasis mine):

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):
        ...

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



来源:https://stackoverflow.com/questions/27637902/robot-framework-makes-two-instances-from-the-class-instead-of-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!