Hello everyone, I’m seeing errors when I run automated tests for my Register APIView API endpoint. I’m building a test with DRF and I think I set up everything correctly, I’m following the DRF docs.
Here is my automated test (test_register.py)
class UserRegisterTests(APITestCase): def test_register_user(self): url = reverse('arborfindr:register') data = {'email': 'mye...@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(), 2) self.assertEqual(User.objects.post().email, 'mye...@mail.com') self.assertTrue(User.objects.check_password('mypassword123'))register serializers
class RegisterSerializer(serializers.ModelSerializer): password = serializers.CharField(style={'input_type': 'password'}, write_only=True) class Meta: model = User fields = ['email', 'username', 'password'] extra_kwargs = { 'password': {'write_only': True} } def validate(self, valid): if valid['password'] != valid['password']: raise serializers.ValidationError({"password": "Passwords do not match."}) return valid def create(self, validated_data): user = User.objects.create_user( email=validated_data['email'], username=validated_data['username'], password=validated_data['password'] ) return userviews.py
# 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)Finally here is the error traceback
Found 1 test(s). Creating test database for alias 'default'... System check identified no issues (0 silenced). F ====================================================================== FAIL: 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 12, in test_register_user self.assertEqual(response.status_code, status.HTTP_201_CREATED) ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ AssertionError: 400 != 201 ---------------------------------------------------------------------- Ran 1 test in 0.015sHere is the link to the example I followed for testing with DRF Testing - Django REST framework.
Please I need help with this, in the docs the Response is set to status.HTTP_201_CREATED but not sure if I should change the status code.
Please let me know if you need anything else from me.