0

次に、ログイン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すべての変数の前にあります。ここに問題があると思います....

4

1 に答える 1

0

テストでは、そのテスト実行用に作成された別のデータベースを使用します。フィクスチャを作成してデータベースにそのユーザーを入力するか、呼び出しの前にフィクスチャを作成するコードを追加する必要があります。login

User.objects.create(username="john", password="xxx")
于 2015-09-18T13:07:19.957 に答える