使用Selenium2library在python中创建自定义关键字的问题

问题描述 投票:0回答:1

我的一个团队成员在python中创建了一个自定义关键字。该关键字使用Selenium2Library的关键字。以下代码位于“C:\ Python27 \ Lib \ site-packages \ Selenium2Library \ keywords_browsermanagement.py”中

# Public, open and close
def select_popup(self):
    BuiltIn().sleep(3)
    handles = self._current_browser().get_window_handles()
    self._info("Window Names: %s " % handles)
    self._info("Pop Up Window being selected: %s " % handles[-1])
    print "in function"
    if len(handles) >= 1:
        self._current_browser().switch_to_window(handles[-1])

现在,只要此关键字select_popup位于_browsermanagement.py中,一切正常。我想将此关键字移动到一个单独的文件中,因为我正在修改属于Selenium2Library的文件,这不是一个好习惯。现在,当我把它放在MyLib.py中时,当我在RIDE中开始测试时,它会给我错误。这是错误消息。

[ ERROR ] Error in file 'D:\Automation\My_Resource.robot': Importing test library 'D:\Automation\MyResources\my.py' failed: NameError: global name 'self' is not defined
Traceback (most recent call last):
  File "D:\Automation\MyResources\my.py", line 15, in <module>
    select_popup();
  File "D:\Automation\MyResources\my.py", line 8, in select_popup
    handles = self._current_browser().get_window_handles()

我认为它没有找到selenium2library对象的参考。有人可以帮助我将自定义python关键字隔离到不同的文件。

robotframework
1个回答
2
投票

您应该创建自己的库并继承Selenium2Library。像这样的东西:

*** Settings ***
Library           MySelenium2Library
Suite Teardown    Close All Browsers

*** Test Cases ***
StackOverflow
    Open Browser    http://www.google.com/    Chrome

MySelenium2Library可以与您的机器人脚本位于同一文件夹中,它看起来像这样:

from Selenium2Library import Selenium2Library

class MySelenium2Library(Selenium2Library):
    def select_popup(self):
        BuiltIn().sleep(3)
        handles = self._current_browser().get_window_handles()
        self._info("Window Names: %s " % handles)
        self._info("Pop Up Window being selected: %s " % handles[-1])
        print "in function"
        if len(handles) >= 1:
            self._current_browser().switch_to_window(handles[-1])

8月31日至18日更新

新版本的SeleniumLibrary似乎需要@keyword装饰器:Example in GitHub

该库的新版本如下所示:

from SeleniumLibrary import SeleniumLibrary
from SeleniumLibrary.base import keyword

class MySeleniumLibrary(SeleniumLibrary):
    @keyword
    def select_popup(self):
        BuiltIn().sleep(3)
        handles = self._current_browser().get_window_handles()
        self._info("Window Names: %s " % handles)
        self._info("Pop Up Window being selected: %s " % handles[-1])
        print "in function"
        if len(handles) >= 1:
            self._current_browser().switch_to_window(handles[-1])
© www.soinside.com 2019 - 2024. All rights reserved.