-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'
1
  • 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 Commented Sep 21, 2015 at 6:03

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

4 Comments

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..
how are u trying to catch they, and where?
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.
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.

2 Comments

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 that sounds like a different question. The answer for this question is pretty good: stackoverflow.com/questions/4606756/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.