Edit2:我知道为什么我得到错误,密码不匹配。这是由于测试数据库本身不包含用户名和密码。
Edit1:
下面我试图为登录api编写测试用例,当我在任何类之外编写测试时,它不会给出任何错误,但是当我创建类class TestCase(TestCase):
并定义方法def test_login(self):
时。它给出了密码不匹配,但外部相同的代码运行成功。
from django.test import TestCase
from django.test import Client
import json
#Creating test out side class
credential=dict()
c =Client()
credential["username"]="john"
credential["password"]="xxx"
response =c.put('/api/login', data=json.dumps(credential))
print("content")
print(response.content)
"""
{"message": "", "result": {"username": "john", "session_key": "xyz"}, "error": 0}
"""
print("session_key")
content = json.loads(response.content)
key = content['result']['session_key']
print key
#Creating test inside class
class TestCase(TestCase):
def test_login(self):
User.objects.create(username="john", password="xxx")
credential=dict()
c =Client()
credential["username"]="john"
credential["password"]="xxx"
response =c.put('/api/login', data=json.dumps(credential))
content=json.loads(response.content)
print 'content'
print content
{u'message': u'Username and Password mismatch', u'result': {}, u'error': 1}
在这里我们可以看到消息的不同格式成功{"message": "", "result": {"username": "john", "session_key": "xyz"}, "error": 0}
失败{u'message': u'username=john and password=xxx Username and Password mismatch', u'result': {}, u'error': 1}
。
login api编写如下,但是当我在Test_login类中定义测试时,它不会进入if part,而是进入else part。在其他部分,我试图打印用户名和密码与响应。我得到的响应是{u'message': u'username=john and password=xxx Username and Password mismatch', u'result': {}, u'error': 1}
这里我们可以看到用户名和密码是正确的。为什么它不去如果部分。我在网上研究得到类似的问题。它也提到了同样的问题。所以从我看到的,用户名和密码是正确的。
后端登录api
user = auth.authenticate(username=username, password=password)
if user is not None:
print 'if user is not None:'
msg=Some response
else:
msg = strtemp+' username='+username+' and password='+password+' Username and Password mismatch'
所以从我看到的,用户名和密码是正确的。
我认为是你没有正确设置密码。
正如你想知道的,django哈希模型User
的密码。而不是调用User.objects.create(username="john", password="xxx")
你只需要:User.objects.create_user('john', password='xxx')
.
除了答案,我想告诉你,你不应该调用你的测试类TestCase
。只是为了保持你的代码整洁,并可能避免一些未来的麻烦。