-1

私はdjangoで書かれた私のプロジェクトのテストケースを書いています.Here {u'message': u'', u'result': {u'username': u'john', u'user_fname': u'', u'user_lname': u'', u'cur_time': 1442808291000.0, u'dofb': None, u'sex': u'M', u'u_email': u'', u'role': u'', u'session_key': u'xxhhxhhhx', u'mobile': None}, u'error': 0} we can see other field are empty because I just created user in test cases, but not given other info. データベースは本番データベースから作成されますが、初期化されず、空のままです。そのため、他のフィールドを空にしています。空のデータベースを照会しています。

ログイン REST APIの次のテスト ケースを作成しました。python manage.py testで実行します。上記の問題の解き方を教えてください。

注: 次のアプローチが正しくない場合は、他のアプローチを提案できます。

from django.test import TestCase
from django.test.client import Client
from django.contrib.auth.models import User
import json

class TestAPI(TestCase):

      def setUp(self):
            self.c=Client() #Create Client object that simulates request to a url similar to a browser can
            User.objects.create_user(username="john", password="xxx")

      def test_login_api(self):
            credential_test=dict()
            c_test =Client()

            credential_test["username"]="john"
            credential_test["password"]="xxx"
            data=json.dumps(credential_test)
            #print 'data is'
            #print data
            response_test =c_test.put('/api/login', data)
            content_test=json.loads(response_test.content)
            print 'content'
4

2 に答える 2

1

変更してみてください:

User.objects.create(username="john", password="xxx")

に:

User.objects.create_user(username='john', password='xxx')

メソッドのcreate_user使用set_password方法。

class UserManager(models.Manager):
    # ...   
    def create_user(self, username, email=None, password=None):
        """
        Creates and saves a User with the given username, email and password.
        """
        now = timezone.now()
        if not username:
            raise ValueError('The given username must be set')
        email = UserManager.normalize_email(email)
        user = self.model(username=username, email=email,
                          is_staff=False, is_active=True, is_superuser=False,
                          last_login=now, date_joined=now)

        user.set_password(password)
        user.save(using=self._db)
        return user
于 2015-09-21T04:04:03.547 に答える