1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

selenium webdriverでステータスコードのチェック

1
Posted at

テスト自動化ツール「selenium webdriver」最初の一歩に続きまして、少し実践的なテストコードを書いてみます。
どうやらselenium-webdriverではステータスコードのチェックができないようなので、仕方なくjavascriptを使ってゴニョゴニョすることにしました。

class StatusChecker
  require 'selenium-webdriver'
  
  def initialize
    @driver = Selenium::WebDriver.for :firefox
  end

  def check(host, paths, protocol='http')
    return unless @driver
    @driver.navigate.to "#{protocol}://#{host}"
    puts "[host] #{host}"
    begin
      paths.each do |path|
        statuscode = get_statuscode(path)
        puts "#{statuscode}, #{path}"
      end
    rescue => e
      puts e.message
      quit
    end
  end

  def quit
    @driver.quit if @driver
    @driver = nil
  end

  private def get_statuscode(path)
    begin
      @driver.execute_script( get_statuscode_script(path) )
      element = nil
      loop do
        element = @driver.find_elements(:id, 'selenium_status')
        if element && element.size > 0
          if !element[0].attribute("value").empty?
            break
          end
        end
        sleep 0.5
      end
      return element[0].attribute("value")
    rescue => e
      raise e.message
    end
  end

  private def get_statuscode_script(path)
    script = %[
      var elm = document.getElementById('selenium_status');
      if( elm == null ) {
        elm = document.createElement('input');
        elm.id = 'selenium_status';
        document.body.appendChild(elm);
      }
      elm.setAttribute('value', '');
      
      var request = new XMLHttpRequest();
      request.open('get', '#{path}', true);
      request.onload = function (event) {
          elm.setAttribute('value', request.status);
      };
      request.onerror = function (event) {
          elm.setAttribute('value', request.status);
      };
      request.send(null);
    ]
    script
  end
end

checker = StatusChecker.new
checker.check('example.com', ['/', '/hoge/'], 'https')
checker.check('www.example.com', ['/', '/poge/'], 'https')
checker.quit

javascriptのところが冗長なので、本当は関数化してinitializeのタイミングで設置して使いまわすのが良いと思いますが、書き直すのが面倒だったのでこのまま公開しちゃいます。
気になる人は適宜修正してください。笑

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?