Chr*_*cio 34 django selenium integration-testing
所以我有一个Selenium功能测试套件.我已经在一些测试中测试了登录/注册功能,方法是将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')
Run Code Online (Sandbox Code Playgroud)
在我的Selenium测试中,所以我不必在每次测试中重复冗长的手动登录过程(因为我已经在之前的测试中测试过登录系统,如前所述)
截至目前,我只是为每个需要登录的测试复制并粘贴"登录流程"Selenium说明.这导致我的测试每次增加5-6秒,这使我的function_tests.py文件非常臃肿.
我所有的谷歌搜索都带我到教我如何用Selenium测试登录的页面.
提前致谢.
Yev*_*lev 30
您无法从selenium驱动程序登录用户.没有一些黑客,这是不可能的.
但是你可以通过将它移动到setUp方法每个TestCase登录一次.
您还可以通过创建LiveServerTestCase所包含的类来避免复制粘贴.
UPDATE
这段代码对我有用:
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/')
Run Code Online (Sandbox Code Playgroud)
til*_*cog 16
在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
Run Code Online (Sandbox Code Playgroud)
现在,在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(
email='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')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5286 次 |
| 最近记录: |