我正在使用Selenium webdriver在Django项目中测试用户身份验证,并创建了一个测试:
class EditorBlogTest(StaticLiveServerTestCase):
def setUp(self):
self.browser = webdriver.Chrome()
def tearDown(self):
self.browser.quit()
def create_session_store(self):
user = User.objects.create(email='a@b.com', username='TestUser')
engine = import_module(settings.SESSION_ENGINE)
store = engine.SessionStore()
store[SESSION_KEY] = user.pk
store.save()
return store
def test_user_authenticated(self):
store = self.create_session_store()
self.browser.get(self.live_server_url + '/dashboard/')
self.browser.add_cookie({
'name': settings.SESSION_COOKIE_NAME,
'value': store.session_key,
'path': '/',
})
self.browser.get(self.live_server_url + '/dashboard/blog/add/')
hello_box = self.browser.find_element_by_id('hello')
self.assertIsNotNone(self.browser.get_cookie('sessionid'))
self.assertEqual('Hello, TestUser', hello_box.text)
在模板中有一行:
<div id="hello">Hello, {{ user }}</div>
但测试失败了:
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
F
======================================================================
FAIL: test_session_creation (functional_tests.dashboard.test_blog.EditorBlogTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/django/my_project/functional_tests/dashboard/test_blog.py", line 26, in test_user_authenticated
self.assertEqual('Hello, TestUser', hello_box.text)
AssertionError: 'Hello, TestUser' != 'Hello, AnonymousUser'
- Hello, TestUser
+ Hello, AnonymousUser
----------------------------------------------------------------------
Ran 1 test in 2.406s
FAILED (failures=1)
Destroying test database for alias 'default'...
有没有人知道它有什么问题?
答案 0 :(得分:0)
我对该主题进行了更深入的研究,发现该会话与 RequestContext 无关,它包含{{ user }}
变量(以及其余的上下文)。因此,在Selenium测试中对用户进行身份验证的最简单方法是在站点上打开登录页面并使用测试用户凭据填写表单。之后我的测试成功了。