jeudi 27 août 2015

Example of how to write Django Test

I have to write some tests for some services I build that connect our backend to a mobile app another team member is building. I was asked to write some unit tests once I finished them. I am not familiar with Django testing so I wanted to ask if someone could give me an example of how you would test one of the services. That way I can then learn by example and do the rest on my own?

This is one example of a service I built that finds if there is a user by that email in our database and return a json object:

@csrf_exempt
def user_find(request):
    args = json.loads(request.body, object_hook=utils._datetime_decoder)
    providedEmail = args['providedEmail']
    try:
        user = User.objects.get(email=providedEmail)
        user_dict = {'exists': 'true', 'name': user.first_name, 'id': user.id}
        return HttpResponse(json.dumps(user_dict))
    except User.DoesNotExist:
        user_dict = {'exists': 'false'} 
        return HttpResponse(json.dumps(user_dict))

What would be the correct way to test something like this? I am guessing I have to mimic a request somehow that gives me an email and then have two tests where one matches and one doesn't match an existing user and make sure each returns the appropriate object. Is this the correct way of thinking about it? Can someone help me out a bit with the syntax?

Aucun commentaire:

Enregistrer un commentaire