LoginSignup
2
2

More than 1 year has passed since last update.

[Python]Seleniumを用いたDocker環境でのE2Eテスト方法 メモ

Posted at
  • Docker環境でのSeleniumを用いたE2Eテスト方法についてメモする。

構成

docker-selenium.png

事前準備

  • Docker環境で動かすため、こちらの構成でdocker-compose.ymlやDockerfileなどdocker-seleniumを利用するための設定を準備する。

テストコードtest.py

  • seleniumでQiita検索した結果を確認する。
  • テストコードの大まかな書き方
    1. テスト前処理:ドライバ設定などを記述する。
    2. テスト実行:ブラウザ操作とその際の期待結果を記述する。
    3. テスト後処理:ドライバクローズなどを記述する。
import os
import unittest
from selenium.webdriver.common.keys import Keys
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.expected_conditions import presence_of_element_located
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

class SampleTest(unittest.TestCase):
    # テスト前処理: ドライバ設定
    def setUp(self):
        self.driver = webdriver.Remote(
            command_executor=os.environ["SELENIUM_URL"],
            desired_capabilities=DesiredCapabilities.CHROME.copy()
        )
    # テスト後処理:ドライバクローズ
    def tearDown(self):
        self.driver.quit()

    # Qiita検索 テスト
    def test_qiita_search(self):
        # 任意のHTMLの要素が特定の状態になるまで待つ
        # ドライバとタイムアウト値を指定
        wait = WebDriverWait(self.driver, 10)
        # テスト対象へアクセス
        self.driver.get("https://qiita.com/")
        # 検索ボックス入力→検索実行
        self.driver.find_element(By.NAME, "q").send_keys(
            "selenium" + Keys.RETURN)
        # 1件目の検索結果を取得(描画されるまで待機)
        first_result = wait.until(
            presence_of_element_located((By.CSS_SELECTOR, "h1")))
        print("first_result:"+first_result.get_attribute("textContent"))
        # タイトルに`selenium`が含まれるかを判定
        assert "selenium" in (
            first_result.get_attribute("textContent")).lower()

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

動作確認

  • ビルド→起動→コンテナの中に入る。
docker-compose build --no-cache
docker-compose up -d
docker-compose exec app bash
  • コード実行
cd test
python test.py
  • 期待値
...省略
----------------------------------------------------------------------
Ran 1 test in 7.221s

OK

参考情報

2
2
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
2
2