背景说明
在文章《Python+Robot Framework实现系统登陆》中,做了系统的线上UI登陆巡检,但当时每个系统的登陆脚本都是独立维护的,随着部门规划要求,很多系统都使用了统一登陆页面,如果还用之前的维护方式,如果统一登陆页面的按钮路径发生了变化,就需要重复调整n个地方。
因此,需要对之前的脚本进行改造,使用resource 文件定义统一登陆页面,每个系统脚本中直接调用,这样每次调整只用调整一次就可以了。
在Robot Framework中,resource 文件是一种用于共享关键字和变量的文件。Resource文件可以包含一组关键字和全局变量,供其他测试套件或资源文件使用。使用Resource文件可以帮助我们提高测试用例的可读性、可维护性和复用性。
具体实现:
- 首先,将统一登陆页面的代码,提取维护到一个新的文件中,比如UnifiedLogin.resource。这里需要注意要在 *** Keywords *** 中使用 [Arguments]来声明需要传入的参数
*** Settings ***
Library Selenium2Library
Library ../common/capcha_result.py
*** Variables ***
# chrome前台执行,headlesschrome后台静默执行
${BROWSER} headlesschrome
&{USERINFO} username=** password=**
*** Keywords ***
Open Browser To Login Page
[Arguments] ${LOGIN URL}
# 打开网址
Open Browser ${LOGIN URL} ${BROWSER}
# 等待,直到捕获到页面元素,这里用系统名称
Wait Until Page Contains Element xpath=***
# 断言title
Title Should Be 统一登录认证
Input Username
# 输入账号
[Arguments] ${username}
Input Text xpath=*** ${username}
Input Password
# 输入密码
[Arguments] ${password}
${password} decrypt ${password}
Input Text xpath=*** ${password}
Input Capcha
# 点击更新验证码
click element xpath=***
sleep 1
# 验证码截屏
${filepath} Capture Element Screenshot xpath*** 验证码.png
# 通过图片扫描出图片中的数字
${capcha} capcha_result ${filepath}
# 输入验证码
Input Text xpath=*** ${capcha}
Input Information Is Correct
Sleep 2
Page Should Not Contain Image xpath=***
Submit Credentials
# 点击登录按钮
Click Button xpath=***
Input Capcha and Submit Credentials
FOR ${var} IN RANGE 10
Input Capcha
Submit Credentials
${result} run keyword and return status Input Information Is Correct
Exit For Loop If ${result}==True
Run KeyWord If ${var}==9 Close Browser
END
Home Page Should Be Open
[Arguments] ${assertion_loc}
sleep 5
PAGE SHOULD CONTAIN ELEMENT ${assertion_loc}
- 在每个系统的登陆脚本中,引入该统一登陆脚本即可,引入语法为:
Resource UnifiedLogin.resource
具体实现代码为:
*** Settings ***
Documentation **系统
Resource UnifiedLogin.resource
*** Variables ***
${LOGIN URL} http://***.com.cn/
# ${BROWSER} chrome
&{USERINFO} username=** password=**
*** Test Cases ***
Login Platform
[Documentation] **系统登陆
Open Browser To Login Page ${LOGIN URL}
Input Username ${USERINFO.username}
Input Password ${USERINFO.password}
Input Capcha and Submit Credentials
Home Page Should Be Open xpath=**
[Teardown] Close Browser
两点说明
- 在resource文件中不可以出现 *** Test Cases ***,其他语法和robot文件一样
- 在调用resource的脚本中,定义的变量或关键字,如果跟resource中的名称一样,会优先使用该脚本中定义的变量或关键字,因此在上面具体实现的代码中,使用的用户名和密码,将会是该文件中定义的,而不是resource中定义的用户名和密码
同理如果在代码中重新写了 *** Keywords *** 中的 Home Page Should Be Open,就不会使用resource中的Home Page Should Be Open