mardi 7 mai 2019

Writing Tests for Custom Views (Django REST)

I am writing a Twitter-like Django based RESTful application which supports basic functionalities like login, signup, create/delete/read tweets, follow/unfollow. I'd like to write tests for my application to ensure that it is working properly.

I tried using APIRequestFactory() but in vain.

My User class

class User(models.Model):
    user_id = models.AutoField(primary_key=True)
    email = models.EmailField(max_length=80, default="email")
    username = models.CharField(max_length=280, unique=True)
    password = models.CharField(max_length=20)
    isactive = models.BooleanField(default=False)

    def __str__(self):
        return str(self.username)

My register custom view:

@csrf_exempt 
def RegistrationView(request):  
        if request.method == 'POST':
            body_unicode = request.body.decode('utf-8')
            body = json.loads(body_unicode)

            email = body['email']
            username = body['username']
            temp_username = User.objects.filter(username= username).first()
            if temp_username is not None:
                print('This username already exists in our database! Please try another username.')
                return JsonResponse({'result' : -1})

            password = body['password']
            user_obj=User.objects.create(email=email,username=username, password=password)
            user_obj.save()

            if user_obj is not None:
                base64username = base64.b64encode( bytes(username, "utf-8") )
                base64username_string = base64username.decode("utf-8")
                print('Success!')
                email_subject = "Welcome to TwitClone!"
                email_from = "me@gmail.com"
                email_to = [user_obj.email]
                email_content = "Hello there! Thanks for joining the TwitClone Community!\n\nPlease click on this link to activate your account: http://127.0.0.1:8000/myapp/activate/"+base64username_string
                x = send_mail(subject = email_subject, from_email = email_from, recipient_list = email_to, message = email_content, fail_silently=False)
                return JsonResponse({'result' : 1})
            else:
                print('There was an error. :(')
                return JsonResponse({'result' : -1})
        else:
            print('There was an error. :(')
            return JsonResponse({'result' : -1})

I have more classes and views too, but I am just putting these two up to provide an understanding of how I've coded the project.

How do I test this registration view process correctly?

Aucun commentaire:

Enregistrer un commentaire