用硒进行django登录测试

时间:2017-04-26 02:42:17

标签: python django selenium

在我的应用程序中,我有一个登录页面。我目前正在使用User中的django.contrib.auth.model模型。

这是我对Selenium的测试,基于PhantomJS(因为我在容器中):

class TestLogin(TestCase):

    def setUp(self):
        self.driver = webdriver.PhantomJS()
        self.driver.set_window_size(1120, 550)
        self.user = User.objects.create_user(username='this_is_a_test', password="dockercompose")


    def test_good_login(self):
        expected_url = "http://localhost:8080"
        self.driver.get("http://localhost:8080/login")
        self.driver.find_element_by_id('id_username').send_keys("this_is_a_test")
        self.driver.find_element_by_id('id_password').send_keys("dockercompose")
        self.driver.find_element_by_id('login_form').submit()
        print(self.driver.page_source)
        assert self.driver.current_url == expected_url

我的测试失败了,这是print(self.driver.page_source)

<html>
    <body>
        <h2>Login</h2>
        <form method="post" id="login_form">
            <input type="hidden" name="csrfmiddlewaretoken"
                   value="zRNkCIYxymsGLFKcZlpLTjbfBcvZxAVFTrAQyvy2wTyiKeISZCRIkraVV7OfS6DG">
            <ul class="errorlist nonfield">
                <li>Please enter a correct username and password. Note that both fields may be case-sensitive.</li>
            </ul>
            <p><label for="id_username">Username:</label> <input type="text" name="username" value="this_is_a_test" autofocus=""
                                                                 maxlength="254" required="" id="id_username"></p>
            <p><label for="id_password">Password:</label> <input type="password" name="password" required="" id="id_password">
            </p>
            <button name="submit_button" type="submit">Login</button>
        </form>
    </body>
</html>

我在测试中做了User.objects.all(),并且创建了用户this_is_a_test

如果你能提供帮助,那可能会很好:)谢谢!

要求:

的Django == 1.11
硒== 3.4.0

更新

我已使用User创建了python manage.py createsuperuserUser始终为(username="this_is_a_test", password="dockercompose"。然后我的测试成功了。 因此,使用User创建的django.contrib.auth.model似乎未存储到我的测试数据库中。

这在我的设置文件中:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'my_db',
        'USER': 'django',
        'PASSWORD': 'django',
        'HOST': 'database_container',
        'PORT': '3306',
        'TEST': {
            'USER': 'django',
            'PASSWORD': 'django',
            'NAME': 'my_db_test'
        }
        } 
}

2 个答案:

答案 0 :(得分:0)

我建议更换

self.driver.find_element_by_id('login_form').submit()

self.driver.find_element_by_name('submit_button').click()

然后尝试,也等到页面加载。

答案 1 :(得分:0)

谢谢大家,我已经解决了我的问题。

使用LiveServerTestCase解决了我的问题。:)