-1

I am writing a test cases for my project written in django, it's giving an unexpected output that looks like {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} Here we can see other field are empty because I just created user in test cases, but not given other info. database is created from the production database, but not initialized, it remains empty. That's why it is giving other field empty. It is querying empty database.

I have written following test case for login REST API. and running it by python manage.py test. Please tell me how to solve above problem.

Note: If following approach is not correct then you can suggest other approach.

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'
e4c5
  • 48,268
  • 10
  • 82
  • 117
geeks
  • 1,833
  • 3
  • 28
  • 46
  • Django test client expects a dictionary as postdata, not a json dump of a dictionary. And why are you authenticating with PUT instead of POST? put i usually for file uploads – e4c5 Sep 21 '15 at 06:03

2 Answers2

1

Try change it :

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

to:

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

The method create_user use set_password method.

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
Paulo Pessoa
  • 2,230
  • 16
  • 28
  • thanks its working, but in response other details are empty, like user_first name and user_last name, Thats why I am trying to initialize with production database.. – geeks Sep 21 '15 at 04:07
  • how are u trying to catch they, and where? – Paulo Pessoa Sep 21 '15 at 04:08
  • this user table is related with other tables so for this it will empty, that why i want to initialize test database with production database. – geeks Sep 21 '15 at 04:23
  • I think this can help u, http://stackoverflow.com/questions/1646468/how-to-run-django-unit-tests-on-production-database – Paulo Pessoa Sep 21 '15 at 04:27
1

Two approaches:

  1. Expand your use of setUp() to create records for the other models and establish a valid set of relationships between the models you create. It's the configuration-via-code approach.
  2. Use fixtures to prepopulate your test dbs. If you do some research you can find out how to create some fixtures using an existing, valid db. However I would advise you to sanitize any production data that you use for testing. Aka a configuration-via-data approach.
Sean Azlin
  • 816
  • 7
  • 18
  • I current approach testing is very slow So I want to use sqlite3 for speed-up So please tell me how to initialize sqlite3 with production database... – geeks Sep 21 '15 at 05:20
  • @geeks that sounds like a different question. The answer for this question is pretty good: http://stackoverflow.com/questions/4606756/how-can-i-specify-a-database-for-django-tests-to-use-instead-of-having-it-build – Sean Azlin Sep 21 '15 at 05:36