4

我想用 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.

如何保存浏览器状态,关闭它,然后使用同一个会话重新打开?

4

1 回答 1

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

还有一些源代码,但我不能全部分享,但逻辑是相似的

于 2013-09-12T09:56:44.087 回答