- 画面テストで期待値画像と取得したスクリーンショット画像を比較する方法を調べたため、その内容をメモしておく。
- それぞれのハッシュ値を比較し、差分があるかを確認する。
構成
root_dir - screenshot_compare.py
|_ image_comparison - actual_img.png
|_ expected_img.png
コードscreenshot_compare.py
-
image_comparison
ディレクトリに期待値画像expected_img.png
を保存 -
Seleniumで対象ページ(標準入力でURL指定)にアクセスし、スクリーンショット取得
actual_img.png
-
期待値画像とスクリーンショットのハッシュ値を比較し、差分があるかを確認
import sys
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
import hashlib
# 標準入力から対象ページのURLを取得
args = sys.argv
target_url = args[1]
options = Options()
options.add_argument('--headless')
# ハッシュ計算
def hash_it(path):
with open(path, 'rb') as f:
hasher = hashlib.md5()
hasher.update(f.read())
return hasher.hexdigest()
directory = "./image_comparison"
# スクリーンショット
actual_img = "{}/{}".format(directory, "actual_img.png")
# 期待値
expected_img = "{}/{}".format(directory, "expected_img.png")
with webdriver.Chrome("./chromedriver.exe", options=options) as driver:
# ページ上のすべての要素が読み込まれるまで待機
wait = WebDriverWait(driver, 15)
# ドライバが設定されるまでの待ち時間を設定する。
driver.implicitly_wait(10)
driver.get(target_url)
wait.until(EC.presence_of_all_elements_located)
# ウィンドウサイズ調整
w = driver.execute_script("return document.body.scrollWidth;")
h = driver.execute_script("return document.body.scrollHeight;")
driver.set_window_size(w, h)
# スクリーンショット取得※ページ全体を保存
driver.save_screenshot("image_comparison/actual_img.png")
# ブラウザクローズ
driver.quit()
# 取得結果と期待値を比較
actual_img_hash = hash_it(actual_img)
expected_img_hash = hash_it(expected_img)
try:
assert actual_img_hash == expected_img_hash
print("Images match.")
except AssertionError:
print("Images do not match. {} and {}".format(
actual_img_hash, expected_img_hash))
動作確認
-
正常系(差分なし)
python screenshot_compare.py https://www.correct_example.com Images match.
-
異常系(差分あり)
python screenshot_compare.py https://www.incorrect_example.com Images do not match. de04f78148d64ab0ced3adef4975277d and 5b4b490ab46938f920ebac3570950e87