Getting errors when running automated test for my DRF APi
I’m performing some automated tests on my register/login APIViews (API endpoints) with DRF for my Django project.
The trouble I’m running into, I’m not able to successfully run the tests with python manage.py test.
I’m sure I set up everything for my APIViews/tests correctly with DRF docs, however I’m getting a traceback error suggesting something might be wrong with my response = self.client.post(url, data, format='json') in my UserRegisterTests
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from ..models import User
class UserRegisterTests(APITestCase):
def test_register_user(self):
url = reverse('register')
data = {'email': 'myemail@mail.com', 'password': 'mypassword123'}
response = self.client.post(url, data, format='json')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(User.objects.count(), 1)
self.assertEqual(User.objects.post().email, 'myemail@mail.com')
self.assertTrue(User.objects.check_password('mypassword1123'))
And there might be something wrong with the if serializer.is_valid(): in my register APIView (views)
# API endpoint for registration
@authentication_classes([JWTAuthentication])
class RegisterView(APIView):
def post(self, request):
serializer = RegisterSerializer(data=request.data, context={'request': request})
if serializer.is_valid():
serializer.save()
return Response({
'message': 'successfully registered',
}, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
This may be of some help, here is my RegisterSerializer
class RegisterSerializer(serializers.ModelSerializer):
password = serializers.CharField(style={'input_type': 'password'}, write_only=True)
class Meta:
model = User
fields = ['email', 'password', 'password2']
def validate(self, valid):
if valid['password'] != valid['password2']:
raise serializers.ValidationError({"password": "Passwords do not match."})
return valid
def create(self, validated_data):
user = User.objects.register_user(
email=validated_data['email'],
pasword=validated_data['password']
)
return user
Here is my traceback error
Found 1 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
E
======================================================================
ERROR: test_register_user (arborfindr.test.test_register.UserRegisterTests.test_register_user)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/coreyj/Documents/ArborHub/MyProject/arborfindr/test/test_register.py", line 11, in test_register_user
response = self.client.post(url, data, format='json')
File "/home/coreyj/Documents/ArborHub/MyProject/.venv/lib64/python3.13/site-packages/rest_framework/test.py", line 295, in post
response = super().post(
path, data=data, format=format, content_type=content_type, **extra)
File "/home/coreyj/Documents/ArborHub/MyProject/.venv/lib64/python3.13/site-packages/rest_framework/test.py", line 209, in post
return self.generic('POST', path, data, content_type, **extra)
~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/coreyj/Documents/ArborHub/MyProject/.venv/lib64/python3.13/site-packages/rest_framework/test.py", line 233, in generic
return super().generic(
~~~~~~~~~~~~~~~^
method, path, data, content_type, secure, **extra)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/coreyj/Documents/ArborHub/MyProject/.venv/lib64/python3.13/site-packages/django/test/client.py", line 676, in generic
return self.request(**r)
~~~~~~~~~~~~^^^^^
File "/home/coreyj/Documents/ArborHub/MyProject/.venv/lib64/python3.13/site-packages/rest_framework/test.py", line 285, in request
return super().request(**kwargs)
~~~~~~~~~~~~~~~^^^^^^^^^^
File "/home/coreyj/Documents/ArborHub/MyProject/.venv/lib64/python3.13/site-packages/rest_framework/test.py", line 237, in request
request = super().request(**kwargs)
File "/home/coreyj/Documents/ArborHub/MyProject/.venv/lib64/python3.13/site-packages/django/test/client.py", line 1092, in request
self.check_exception(response)
~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^
File "/home/coreyj/Documents/ArborHub/MyProject/.venv/lib64/python3.13/site-packages/django/test/client.py", line 805, in check_exception
raise exc_value
File "/home/coreyj/Documents/ArborHub/MyProject/.venv/lib64/python3.13/site-packages/django/core/handlers/exception.py", line 55, in inner
response = get_response(request)
File "/home/coreyj/Documents/ArborHub/MyProject/.venv/lib64/python3.13/site-packages/django/core/handlers/base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/coreyj/Documents/ArborHub/MyProject/.venv/lib64/python3.13/site-packages/django/views/decorators/csrf.py", line 65, in _view_wrapper
return view_func(request, *args, **kwargs)
File "/home/coreyj/Documents/ArborHub/MyProject/.venv/lib64/python3.13/site-packages/django/views/generic/base.py", line 104, in view
return self.dispatch(request, *args, **kwargs)
~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/coreyj/Documents/ArborHub/MyProject/.venv/lib64/python3.13/site-packages/rest_framework/views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "/home/coreyj/Documents/ArborHub/MyProject/.venv/lib64/python3.13/site-packages/rest_framework/views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^
File "/home/coreyj/Documents/ArborHub/MyProject/.venv/lib64/python3.13/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
raise exc
File "/home/coreyj/Documents/ArborHub/MyProject/.venv/lib64/python3.13/site-packages/rest_framework/views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "/home/coreyj/Documents/ArborHub/MyProject/arborfindr/views.py", line 80, in post
if serializer.is_valid():
~~~~~~~~~~~~~~~~~~~^^
File "/home/coreyj/Documents/ArborHub/MyProject/.venv/lib64/python3.13/site-packages/rest_framework/serializers.py", line 223, in is_valid
self._validated_data = self.run_validation(self.initial_data)
~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^
File "/home/coreyj/Documents/ArborHub/MyProject/.venv/lib64/python3.13/site-packages/rest_framework/serializers.py", line 442, in run_validation
value = self.to_internal_value(data)
File "/home/coreyj/Documents/ArborHub/MyProject/.venv/lib64/python3.13/site-packages/rest_framework/serializers.py", line 495, in to_internal_value
for field in fields:
^^^^^^
File "/home/coreyj/Documents/ArborHub/MyProject/.venv/lib64/python3.13/site-packages/rest_framework/serializers.py", line 378, in _writable_fields
for field in self.fields.values():
^^^^^^^^^^^
File "/home/coreyj/Documents/ArborHub/MyProject/.venv/lib64/python3.13/site-packages/django/utils/functional.py", line 47, in __get__
res = instance.__dict__[self.name] = self.func(instance)
~~~~~~~~~^^^^^^^^^^
File "/home/coreyj/Documents/ArborHub/MyProject/.venv/lib64/python3.13/site-packages/rest_framework/serializers.py", line 372, in fields
for key, value in self.get_fields().items():
~~~~~~~~~~~~~~~^^
File "/home/coreyj/Documents/ArborHub/MyProject/.venv/lib64/python3.13/site-packages/rest_framework/serializers.py", line 1078, in get_fields
info = model_meta.get_field_info(model)
File "/home/coreyj/Documents/ArborHub/MyProject/.venv/lib64/python3.13/site-packages/rest_framework/utils/model_meta.py", line 39, in get_field_info
forward_relations = _get_forward_relationships(opts)
File "/home/coreyj/Documents/ArborHub/MyProject/.venv/lib64/python3.13/site-packages/rest_framework/utils/model_meta.py", line 96, in _get_forward_relationships
not field.remote_field.through._meta.auto_created
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute '_meta'
----------------------------------------------------------------------
Ran 1 test in 0.016s
FAILED (errors=1)
Destroying test database for alias 'default'...
Please help me, I want to know why my automated tests aren’t running properly.
You misunderstood the answer from the first link, this answer suggests as a solution replacing the model in the Meta class as in the code below. Also make sure you have set AUTH_USER_MODEL='custom_user_app.CustomUserModel' in the settings file.
# You need to replace the direct import of your model with the one shown below
# from .models import User
from django.contrib.auth import get_user_model
User = get_user_model()
class RegisterSerializer(serializers.ModelSerializer):
password = serializers.CharField(
style={'input_type': 'password'},
write_only=True,
)
class Meta:
model = User
fields = ['email', 'password', 'password2']
...
Also try the same trick in your tests. This should fix your initial error, but there are still problems in your code, for example, the create serializer method, replace the pasword keyword with password. I hope you are now clearer on what you should try to do, you should now check it yourself and let me know if your problem has been fixed?