下面我试图为登录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 and Password mismatch', u'result': {}, u'error': 1}
。每个变量前都有u
。我觉得问题在这里....
测试使用为该测试运行创建的单独数据库,您需要创建一个fixture来用该用户填充数据库,或者在login
调用之前添加创建一个数据库的代码,如:
User.objects.create(username="john", password="xxx")