在Selenium测试中验证用户

问题描述 投票:1回答:1

我正在使用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='[email protected]', 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'...

有谁知道它有什么问题?

django selenium-webdriver
1个回答
0
投票

我对该主题进行了更深入的研究,发现session与RequestContext无关,它包含{{ user }}变量(以及其余的上下文)。因此,在Selenium测试中对用户进行身份验证的最简单方法是在站点上打开登录页面并使用测试用户凭据填写表单。之后,我的测试成功通过了。

© www.soinside.com 2019 - 2024. All rights reserved.