Home > database >  I am unable to identify my error in writing unit test for Django rest_farmework
I am unable to identify my error in writing unit test for Django rest_farmework

Time:12-01

I am trying to write a unit test to check my view for password reset in Django rest_framework. I can't identify where is the error and why am I getting the error. I am a beginner in django rest_framework. I would appreciated your help.

my View.py

from user_authentication.models import User as Client
from rest_framework.response import Response
from rest_framework.views import APIView

class Password_Reset(APIView):
    def post(self, request):
        username = request.data.get('username')
        if Client.objects.filter(username = username).exists():
            new_password = request.data.get('new_password')
            confirm_password = request.data.get('confirm_password')
            if new_password == confirm_password:
                user = Client.objects.filter(username = username).first()
                user.set_password(new_password)
                user.save()
                return Response({"message": "your password has been changed"}, 201)
        else:
            return Response({"message": "This email address doesn't exist"}, 404)

my model.py

from django.db import models
from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    created_at=models.DateTimeField(auto_now_add=True)
    email = models.EmailField(verbose_name="Email", max_length=60, unique=True)
    date_of_birth= models.DateField(verbose_name="Date of Birth", max_length=10)
    def __str__(self):
        return self.username

my urls.py

from django.urls import path
from user_authentication.views import Login, Logout, Register, Password_Reset

urlpatterns = [
    path('login/', Login.as_view()),
    path('logout/', Logout.as_view()),
    path('register/', Register.as_view()),
    path('login/password_reset', Password_Reset.as_view())
]

my Unit Test for password reset

from rest_framework.test import APITestCase
from user_authentication.models import User
from user_authentication.views import Password_Reset, Register, Login, Logout


class ViewTest(APITestCase):
    def test_password_reset(self):
        url = 'login/password_reset'
        response = self.client.post(url, {'username': "developer", "new_password": "abc1234", 
                                          "confirm_password": "abc1234"})
        user = User.objects.get(username = 'developer')
        password= "abc1234"
        self.assertTrue(user.check_password(password))
        response.status_code

my Error

(venv) PS C:\Users\Lenovo\Documents\GitHub\E-commerce\garments> python manage.py test
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
E
======================================================================
ERROR: test_password_reset (user_authentication.tests.ViewTest)       
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\Lenovo\Documents\GitHub\E-commerce\garments\user_authentication\tests.py", line 10, in test_password_reset
    user = User.objects.get(username = 'developer')
  File "C:\Users\Lenovo\Documents\GitHub\E-commerce\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\Lenovo\Documents\GitHub\E-commerce\venv\lib\site-packages\django\db\models\query.py", line 435, in get
    raise self.model.DoesNotExist(
user_authentication.models.User.DoesNotExist: User matching query does not exist.

----------------------------------------------------------------------
Ran 1 test in 0.031s

FAILED (errors=1)
Destroying test database for alias 'default'...

CodePudding user response:

You need to create a user first before :

class ViewTest(APITestCase):
    def setUp(self):
        user = User.objects.create_user('developer', 'abc1234')
    
    def test_password_reset(self):
        # ...

CodePudding user response:

I didn't create the user and also my URL was wrong. Thanks, @Rvector

class ViewTest(APITestCase):

    def test_password_reset(self):
        user = User.objects.create_user(username = 'xxx', password= 'xxx', 
                                        first_name= 'xxx', last_name = 'xxx', 
                                        date_of_birth = 'xxx')
        url = '/login/password_reset/'
        response = self.client.post(url, {'username': 'xxx', 'xxx': 'abc12345', 
                                          'confirm_password': 'xxx'})
        user = User.objects.get(username="xxx")
        password= "xxx"
        self.assertTrue(user.check_password(password))
        print(response.status_code)



  • Related