togatttiのエンジニアメモ

過度な期待はしないでください.

SeleniumRCの構築手順とチュートリアル

概要

SeleniumRCを利用して、アプリケーションのテストを行う手順を備忘録として示す。

また、Pythonチュートリアルも書いた。

イメージ図

ローカルPCとSeleniumRCとアプリケーション等の関連を示した図

f:id:togattti1990:20140406145225p:plain

補足
  1. SeleniumRCをVPS上で起動させる。

  2. ローカルPCに用意した、テストスクリプトを実行する。

  3. SeleniumRCが自動でブラウザを起動し、アプリケーション操作/テストする。

SeleniumRCの構築

下記、構築はVPSで行う。

環境
準備

必要なパッケージをインストールする

$ sudo apt-get update
$ sudo apt-get install openjdk-7-jdk xvfb firefox

SeleniumRCをダウンロードする

$ cd ~
$ wget http://selenium-release.storage.googleapis.com/2.41/selenium-server-standalone-2.41.0.jar 
起動

ディスプレイ番号の指定

$ export DISPLAY=:1

仮想フレームバッファ実行

$ Xvfb :1 -ac -screen 0 1280x1024x24 &

SeleniumRCを起動する

$ java -jar selenium-server-standalone-2.41.0.jar  &

デフォルトでは4444ポートで起動する。

テストスクリプト作成

以下、ローカルPC(Mac 10.9)で行う。

Pythonでテストの触りだけ紹介する。

準備

Python 2.7を使う。

seleniumモジュールをインストールする。

$ sudo easy_intall selenium

テスト書く。

Firefoxでwww.google.co.jpを開いて、titleタグ内にTitlesの中 の文字列が含まれているかどうかをテストしている。

# coding: utf8 
import unittest
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

class HandleGoogleTest(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Remote(
            command_executor='http://***.***.***.***:4444/wd/hub',
            desired_capabilities=DesiredCapabilities.FIREFOX)

    def test_search_in_google(self):
        driver = self.driver
        driver.get("https://www.google.co.jp/")
        Titles = ['Google', 'Yahoo']

        for t in Titles:
            self.assertIn(t, driver.title)

    def tearDown(self):
        self.driver.close()

if __name__ == "__main__":
    unittest.main()

command_executor欄はhttp://...:4444ではなく、 http://...:4444/wd/hubが正しい。

実行

実行すると、Yahooが含まれないため失敗する。

F
======================================================================
FAIL: test_search_in_google (__main__.HandleGoogleTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test.py", line 19, in test_search_in_google
    self.assertIn(t, driver.title)
AssertionError: 'Yahoo' not found in u'Google'

----------------------------------------------------------------------
Ran 1 test in 4.987s

FAILED (failures=1)
参考

SeleniumRCを知らない場合は公式を読む。

http://docs.seleniumhq.org/projects/remote-control/

Xvfbの起動、設定はここらへん。 今回はUbuntuで行っているので、インストール手順は異なる。

https://gist.github.com/textarcana/5855427

Pythonseleniumモジュールの使い方はここら辺を。

http://selenium-python.readthedocs.org/installation.html#introduction