LoginSignup
6
12

More than 5 years have passed since last update.

pythonでseleniumのテストコードを書いてみる

Last updated at Posted at 2017-09-03

概要

エンドツーエンドテストのコードをpythonにて書く必要が出てきたので、
作業内容を忘れないようメモする。

テスト環境

下記、別記事に記載のdocker環境を使って行います。

dockerでE2Eテスト環境 (python3 + selenium) を構築
http://qiita.com/reflet/items/89ff50c991168adb3a9b

簡単なテストコードを書いて実行してみる

下記サイトにある簡易なテストコードを参考にコードを作成する

[参考サイト] 2.1. Simple Usage
http://selenium-python.readthedocs.io/getting-started.html#simple-usage

python_org_search.py
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
driver = webdriver.Remote(
    command_executor='http://selenium-hub:4444/wd/hub',
    desired_capabilities=DesiredCapabilities.CHROME)

driver.get("http://www.python.org")
assert "Python" in driver.title
elem = driver.find_element_by_name("q")
elem.clear()
elem.send_keys("pycon")
elem.send_keys(Keys.RETURN)
assert "No results found." not in driver.page_source
driver.close()

上記コードを実行してみる

ターミナル
# python python_org_search.py

ユニットテストを書いてみる

下記サイトを参考にテストコードを作成し、実行してみる。

[参考サイト] 2.3. Using Selenium to write tests
http://selenium-python.readthedocs.io/getting-started.html#using-selenium-to-write-tests

test_python_org_search.py
import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

class PythonOrgSearch(unittest.TestCase):

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

    def test_search_in_python_org(self):
        driver = self.driver
        driver.get("http://www.python.org")
        self.assertIn("Python", driver.title)
        elem = driver.find_element_by_name("q")
        elem.send_keys("pycon")
        elem.send_keys(Keys.RETURN)
        assert "No results found." not in driver.page_source

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

if __name__ == "__main__":
    unittest.main()
ターミナル
# python test_python_org_search.py

参考サイト

6
12
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
6
12