如何在django测试中验证用户的删除操作

时间:2017-10-27 06:14:47

标签: django

我在尝试通过测试登录时遇到错误。在前端,我可以删除一个cartItem,没有任何问题,但在测试时,测试套件无法登录进行删除操作。

错误

        with self.login(username=user.username,
>                       password=user.password):

applications/startupconfort/tests/test_frontend.py:137: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
env_python3/lib/python3.6/site-packages/test_plus/test.py:238: in login
    return login(self, *args, **credentials)
env_python3/lib/python3.6/site-packages/test_plus/test.py:66: in __init__
    "login failed with credentials=%r" % (credentials)
E   AssertionError: False is not true : login failed with credentials={'username': 'helloworld', 'password': '(password)'}

test.py

def test_auth_user_can_delete_his_cartitem(self):
    user = mixer.blend(
        User,
        username='helloworld',
        password='(password)',
        email='adddd@gmail.com')
    products = mixer.cycle(3).blend(
        CartItem,
        customer=user)
    self.assertTrue(user.is_authenticated())
    #login attempt
    with self.login(username=user.username, 
                    password=user.password):
        response = self.delete('startupconfort:delete_this_item',  products[0].pk)
        self.assertEqual(200, response.status_code)

urls.py

url(r'^delete/(?P<pk>\d+)/$',
    CartItemDeleteView.as_view(),
    name="delete_this_item"),

模板(HTML)

  <form class="right" method="POST" action="{% url 'startupconfort:delete_this_item' cartitem.id %}">

我正在使用django-test_plus

1 个答案:

答案 0 :(得分:0)

user.password是存储在数据库中的哈希密码值,而不是密码本身。如果您尝试使用该用户登录,则会失败。

相反,您需要使用实际密码字符串登录:

with self.login(username=user.username, password='(password)'):
    # This will log the user in correctly