[英]How to test login rest api in django?
Edit2:我明白了为什么我会出错,密码不匹配。 这是由于测试数据库本身不包含用户名和密码。
编辑1:
接下来,我尝试为登录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类中定义test时, 如果不是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'
所以从我看来,用户名和密码是正确的。 怎么了 ?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.