所以我有一个硒功能测试套件。我已经在几个测试中测试了登录/注册功能,方法是将Selenium客户机导航到注册页面,输入用户名和密码,然后告诉Selenium使用相同的凭据登录。现在,我想测试站点“登录所需”区域的其他部分,而不必告诉Selenium单击并在测试浏览器中输入文本。
换句话说,我想使用这样的东西(在我的视图单元测试中我使用得很好):
self.client = Client()
self.user = User.objects.create_user('temporary', 'temporary@gmail.com', 'temporary')
self.user.save()
self.client.login(username='temporary', password='temporary')在我的Selenium测试中,我不必在每个测试中重复冗长的手动登录过程(因为我已经在前面的测试中测试了登录系统)。
现在,我只需复制并粘贴每个需要登录的测试的“登录流”Selenium指令。这导致我的测试每增加5-6秒,使我的function_tests.py文件非常臃肿。
我所有的谷歌都把我带到了教我如何用Selenium测试登录的页面。
提前谢谢。
发布于 2014-03-19 05:43:14
无法从selenium驱动程序登录用户。没有一些黑客是不可能的。
但是,您可以通过将每个TestCase移动到setUp方法来登录一次。
还可以通过创建从LiveServerTestCase继承的类来避免复制粘贴。
更新
这段代码适用于我:
self.client.login(username=superuser.username, password='superpassword') #Native django test client
cookie = self.client.cookies['sessionid']
self.browser.get(self.live_server_url + '/admin/') #selenium will set cookie domain based on current page domain
self.browser.add_cookie({'name': 'sessionid', 'value': cookie.value, 'secure': False, 'path': '/'})
self.browser.refresh() #need to update page for logged in user
self.browser.get(self.live_server_url + '/admin/')发布于 2015-09-22 04:20:45
在Django 1.8中,可以创建预验证的会话cookie并将其传递给Selenium。
为了做到这一点,您必须:
会话和cookie创建逻辑如下所示:
# create_session_cookie.py
from django.conf import settings
from django.contrib.auth import (
SESSION_KEY, BACKEND_SESSION_KEY, HASH_SESSION_KEY,
get_user_model
)
from django.contrib.sessions.backends.db import SessionStore
def create_session_cookie(username, password):
# First, create a new test user
user = get_user_model()
user.objects.create_user(username=username, password=password)
# Then create the authenticated session using the new user credentials
session = SessionStore()
session[SESSION_KEY] = user.pk
session[BACKEND_SESSION_KEY] = settings.AUTHENTICATION_BACKENDS[0]
session[HASH_SESSION_KEY] = user.get_session_auth_hash()
session.save()
# Finally, create the cookie dictionary
cookie = {
'name': settings.SESSION_COOKIE_NAME,
'value': session.session_key,
'secure': False,
'path': '/',
}
return cookie现在,在您的Selenium测试中:
#selenium_tests.py
# assuming self.webdriver is the selenium.webdriver obj.
from create_session_cookie import create_session_cookie
session_cookie = create_session_cookie(
username='test@email.com', password='top_secret'
)
# visit some url in your domain to setup Selenium.
# (404 pages load the quickest)
self.driver.get('your-url' + '/404-non-existent/')
# add the newly created session cookie to selenium webdriver.
self.driver.add_cookie(session_cookie)
# refresh to exchange cookies with the server.
self.driver.refresh()
# This time user should present as logged in.
self.driver.get('your-url')发布于 2020-04-30 04:35:28
在GitHub上有一个库可用于此目的:django-selenium-登录
https://stackoverflow.com/questions/22494583
复制相似问题