How to selenium test a website that uses Google OAuth

时间:2016-04-15 11:02:12

标签: selenium oauth google-api

I'm building a website that uses Google OAuth to authenticate users and to perform actions in Google (sending emails, creating calendar events, etc.) on the user's behalf.

I want to use selenium to test that the website works as I expect. This includes website specific stuff (e.g. pressing this button causes this entry in the DB), but also Google specific stuff (e.g. pressing this button causes this exact email to be sent).

How do I reasonably test this using selenium? How can I log in automatically? Is there any way at all for me to test that user X can't perform these certain actions but user Y can?

Currently I save a JSONified user record (with Google credentials) in a file and load that file when the tests set up. If the file can't be found then it boots up a browser window and sleeps until I've manually signed in using that browser window. This feels hacky and fragile. It also prevents me from having CI testing because the user record file is only available on my machine.

1 个答案:

答案 0 :(得分:4)

您可以创建允许不同权限的不同帐户。然后只需像真实用户那样自动执行登录。 这是通过GMail登录StackOverflow的Python示例:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Firefox()
wait = WebDriverWait(driver, 10)

driver.get("https://stackoverflow.com/users/login")

# Click GMail login
driver.find_element_by_xpath("//span[.='Google']").click()

# type email
wait.until(EC.presence_of_element_located((By.ID, "Email"))).send_keys('...')

# click next
wait.until(EC.presence_of_element_located((By.ID, "next"))).click()

# type password
wait.until(EC.presence_of_element_located((By.ID, "Passwd"))).send_keys('...')

# click signin
wait.until(EC.presence_of_element_located((By.ID, "signIn"))).click()

# wait for the end of the redirection
wait.until(EC.presence_of_element_located((By.ID, "nav-questions")))