LoginSignup
9
10

More than 5 years have passed since last update.

Selenium Python Bindingsとpy.testでデータ駆動テストのさわりを試す

Last updated at Posted at 2014-05-24

背景

Seleniumを使ってデータ駆動型テストを勉強してみたかったので、
pythonのテストフレームワークであるpy.testを使って書いてみた。

スクリプトの概要

  • スクリプトはGoogleさんのトップページから検索を行い、検索結果を確認する簡単なもの。
  • py.testに組み込まれているpytest.mark.parametrize デコレータを使って、検索ボックスに入力する文字列と、検索後の文字列をinput, expectedで定義。
pram_test.py
# -*- coding: utf-8 -*-

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import pytest
import time

@pytest.mark.parametrize(("input", "expected"), [
    ("red", "<em>RED</em>/レッド - Wikipedia"),
    ("青", "<em>青</em> - Wikipedia"),
    ("きいろ", "五丁目 千 <em>きいろ</em>"),
])

def test_search(input, expected):
    driver = webdriver.Chrome()
    driver.get("http://www.google.co.jp/")
    elem = driver.find_element_by_name("q")
    elem.send_keys(input)
    elem.send_keys(Keys.RETURN)
    time.sleep(1)
    assert expected in driver.page_source
    driver.close()

テストの実行結果

  • 1つのテストでもセットしたテストデータは3件なので、3件のテストがコレクトされていることがわかる。
  • テスト自体は1つしか書いてないので、スクリプトの変更も楽。
# py.test -v -s pram_test.py
=========================================================== test session starts ============================================================
platform darwin -- Python 3.3.3 -- pytest-2.5.1 -- /Users/hoge/local/py3/bin/python
collected 3 items 

pram_test.py:8: test_search[red-<em>RED</em>/レッド - Wikipedia] PASSED
pram_test.py:8: test_search[青-<em>青</em> - Wikipedia] PASSED
pram_test.py:8: test_search[きいろ-五丁目 千 <em>きいろ</em>] PASSED

======================================================== 3 passed in 13.50 seconds =========================================================
  • py.testは機能豊富っぽいので、今後もいろいろ試していきたい。
9
10
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
9
10