LoginSignup
3
1

More than 3 years have passed since last update.

Selenium さんなら Cookie の賞味期限を知っている

Last updated at Posted at 2019-09-07

弊社某プロジェクトの結合テストで,付与した Cookie の有効期限を確かめるケースがありました.
弊社では自動テストツールを独自に開発して結合テストを行っていたが,ドメインに付与されている Cookie の中身まで見ることができませんでした.
わたしは個人的に JavaScript の document.cookie で Cookie の中身を見る方法を知っていましたが,それでも有効期限を見ることはできませんでした.
そこでふと思ったのが, Selenium さんなら Cookie の有効期限が取れるのではないか,と.
調べてみたらありましたので紹介しておきます.

環境

Ruby

$ ruby -v
ruby 2.5.3p105 (2018-10-18 revision 65156) [x64-mingw32]

chromedriver.exe

お使いの Chrome のバージョンと合ったものを下記からダウンロードします.その際に保存先のパスを控えておいてください.
Downloads - ChromeDriver - WebDriver for Chrome

使用したメソッド

driver.manage.all_cookies

手順

適当にディレクトリを用意し,その中に以下の 2 ファイルを用意する

  • Cookie を有効期限付きで付与する Javascript の入った html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Cookie Test</title>
    <script type="text/javascript">
        document.cookie = 'key=value; max-age=1800;'
    </script>
</head>
<body>
<p id="aaa">Displayed</p>
</body>
</html>
  • Cookie の有効期限を確かめる Ruby スクリプト
require 'selenium-webdriver'

# Browser Config
Selenium::WebDriver::Chrome::Service.driver_path = ENV['DRIVER_PATH']
wait = Selenium::WebDriver::Wait.new(:timeout => 10)
options = Selenium::WebDriver::Chrome::Options.new
options.prefs['profile.default_content_setting_values.notifications'] = 2 # ignore chrome popup

# Run Browser
driver = Selenium::WebDriver::for(:chrome, options: options)
now = Time.now
driver.get('localhost:8000/index.html')
wait.until { driver.find_element(:id, 'aaa').displayed? }
all_cookies = driver.manage.all_cookies # Get Cookies
p all_cookies
driver.quit

# Check Cookie's Expire
expires = all_cookies[0][:expires].to_time
diff = expires - now
if (diff - 1800).abs <= 1
  puts 'OK'
end

ビルトインサーバを立ち上げる

ruby -rwebrick -e 'WEBrick::HTTPServer.new(:DocumentRoot => "./html/", :Port => 8000).start'

Ruby スクリプトを実行する

DRIVER_PATH に先ほど控えていた chromedriver のパスを入れます.

DRIVER_PATH=${ your path to chromedriver } ruby getCookieExpire.rb

結果

Chrome の Developer Tools で見ていたものがすべて取れました.

DevTools listening on ws://127.0.0.1:50670/devtools/browser/2de236f9-70a3-46b6-9565-d95b0efe1850
[{:name=>"key", :value=>"value", :path=>"/", :domain=>"localhost", :expires=>#<DateTime: 2019-09-07T01:42:39+00:00 ((2458734j,6159s,709238028n),+0s,2299161j)>, :secure=>false}]
OK

Process finished with exit code 0

今後弊社のテストがはかどりそうな気がします♬

3
1
1

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
3
1