在使用robotframework进行自动化测试时,一般都是用Open Browser打开浏览器,但是在有的测试场景中需要设置一些特殊的参数进行测试,比如设置测试环境信息,设置文件下载路径等场景,Open Browser就不能够支持了。
我们的测试场景中有文件下载的步骤,文件下载地址一般会是浏览器的默认下载地址,在团队测试中,不同环境的默认下载地址可能是不同的,尤其是支持跨平台的测试,所以就需要统一设置文件下载路径。
网上的资料大多都是通过python方法进行创建,代码一般如下:
|
以上代码的问题在于,自己创建的driver并不是在robot的BrowserManagerment对象容器中,后续的许多操作都需要自己来控制,对于已经成型的框架,改动起来是非常不可取的。
于是尝试其他的方法,查看selenium的源码,在BrowserManagerment的文件中有一个Create WebDriver关键字,官方的解释是,该关键字同Open Browser,但是允许传递参数直接创建driver,当Open Browser不能满足的情况下,可以使用Create WebDriver进行创建driver,该关键字定义如下:
@keyword
def create_webdriver(self, driver_name, alias=None, kwargs={}, **init_kwargs):
但是,如何使用该关键字呢,百度上几乎找不到相应的方法,于是在国外的网站上找,找到了一些方法,尝试起来都会报各种错误,几经折腾之后,最后在stackoverflow上的一篇文章,找到了解决方法,原文代码如下:
*** Test Cases ***
Specifying a Known Mobile Device
${mobile emulation}= Create Dictionary deviceName=Google Nexus 5
${chrome options}= Evaluate sys.modules['selenium.webdriver'].ChromeOptions() sys, selenium.webdriver
Call Method ${chrome options} add_experimental_option mobileEmulation ${mobile emulation}
Create Webdriver Chrome chrome_options=${chrome options}
Goto https://stackoverflow.com
Sleep 10 secs
Specifying Individual Device Attributes
${device metrics}= Create Dictionary width=${360} height=${640} pixelRatio=${3.0} userAgent=Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 5 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19
${mobile emulation}= Create Dictionary deviceMetrics=${device metrics}
${chrome options}= Evaluate sys.modules['selenium.webdriver'].ChromeOptions() sys, selenium.webdriver
Call Method ${chrome options} add_experimental_option mobileEmulation ${mobile emulation}
Create Webdriver Chrome chrome_options=${chrome options}
Goto https://stackoverflow.com
Sleep 10 secs
由于我只需要设置文件下载路径,所以改成设置浏览器的默认下载目录,修改后如下:
*** Keywords ***
打开浏览器
[Arguments] ${level_name} ${downloadPath}
${url} get_xpath login_page relax ${level_name}
log ${url}
${prefs}= Create Dictionary download.default_directory=/home/root/download
${chrome options}= Evaluate sys.modules['selenium.webdriver'].ChromeOptions() sys, selenium.webdriver
Call Method ${chrome options} add_experimental_option prefs ${prefs}
Create Webdriver Chrome chrome_options=${chrome options}
Go To ${url}
MAXIMIZE BROWSER WINDOW
该方法在Windows和linux下均测试成功,如果设置的路径不存在,则会自动创建文件夹。
附:
欢迎关注技术公众号:架构师成长营