我想用watir测试交互式身份验证。我需要在selenium服务器上打开一次浏览器,在没有用户交互的情况下输入他的登录名/密码(存储在服务器上,用户不输入它们,他只需要输入验证码),出现带有“输入验证码”标签的新文本字段,然后系统向用户发送验证码并关闭浏览器(这里我需要以某种方式保存会话)。用户收到验证码并将其发送到服务器,服务器打开新浏览器(恢复某种方式保存的会话)并输入从用户收到的验证码。
我可以保持浏览器打开,只需在显示的文本字段中输入验证码,但如果用户不会向我发送他收到的验证码,浏览器将保持打开状态,不是很好的解决方案。
所以,我试过这样的事情:
params = { login: 'userexample.com', password: '123456' }
adapter = Adapters::Test.new(params)
adapter.sign_in #opens browser, fills credentials fields, clicks 'get verification code', 'enter verification code' field appears
cookies = adapter.browser.cookies.to_a #save browser state
url = adapter.browser.url
adapter.browser.close
adapter = Adapters::Test.new(params)
adapter.browser.goto url
adapter.browser.cookies.clear
cookies.each do |saved_cookie|
adapter.browser.cookies.add(saved_cookie[:name], saved_cookie[:value])
end
adapter.browser.refresh #I should be on the same page with appeared 'enter verification code' field, but nothing happens after refresh, I am still on the main page with only login/password fields.
如何保存浏览器状态,关闭它然后使用相同的会话重新打开?
答案 0 :(得分:3)
def prepare_for_sign_in
browser.goto login_url
browser.text_field(:name => "login").set("admin")
browser.text_field(:name => "password").set("admin")
browser.a(:class => "enter").click
until browser.div(:text => /Welcome/).present? do
if browser.div(:class => 'error').text.include?("incorrect username or password")
raise InvalidCredentials.new("Invalid login or password.")
end
end
# here you need to sleep few secs or use similar conditional wait
Watir::Wait.until { browser.cookies.to_a.first[:name] == "JSESSIONID" }
params["interactive_data"] = {
"cookies" => JSON.parse(browser.cookies.to_a.to_json),
"proceed_url" => browser.url
}
end
def sign_in
restore_cookies(params["interactive_data"]["proceed_url"])
browser.text_field(:name => "sms").set('123456')
browser.a(:text => "Proceed").click
end
def restore_cookies(url)
browser.goto url
browser.cookies.clear
params["interactive_data"]["cookies"].each do |cookie|
browser.cookies.add(
cookie["name"],
cookie["value"],
{
domain: cookie["domain"],
path: cookie["path"],
expires: cookie["expires"],
secure: cookie["secure"]
}
)
end
browser.goto url
browser.refresh
end
还有一些源代码,但我不能分享所有这些,但逻辑是相似的