Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

user.check_password assertion failing

I have some tests trying to validate my user creation process in an API application.

The issue I am having is that when I try to validate a users password was created as a hashed object the test is failing.

Test:

CREATE_USER_URL = reverse('user:create')


def create_user(**params):
    return get_user_model().objects.create_user(**params)
...

def test_create_valid_user_success(self):
        """Test creating user with valid user is successful"""
        payload = {
            'email': '[email protected]',
            'password': 'testpass',
            'name': 'Test Name'
        }
        res = self.client.post(CREATE_USER_URL, payload)

        self.assertEqual(res.status_code, status.HTTP_201_CREATED)
        user = get_user_model().objects.get(**res.data)
        self.assertTrue(user.check_password(payload['password']))
        self.assertNotIn('password', res.data)

Serializer:

from django.contrib.auth import get_user_model

from rest_framework import serializers


class UserSerializer(serializers.ModelSerializer):
    """Serializer for users object"""

    class Meta:
        model = get_user_model()
        fields = ('email', 'password', 'name')
        extra_kwargs = {
            'password': {
                'write_only': True,
                'min_length': 8
            }
        }

        def create(self, validated_data):
            """Create a new user with encrypted password and return it"""
            return get_user_model().objects.create_user(**validated_data)

Failed Test:

FAIL: test_create_valid_user_success (user.tests.test_user_api.PublicUserApiTests)
Test creating user with valid user is successful
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/app/user/tests/test_user_api.py", line 33, in test_create_valid_user_success
    self.assertTrue(user.check_password(payload['password']))
AssertionError: False is not true

From what I can tell from documentation etc, I have the correct syntax.

Wjhat is missing/incorrect that I need in order to fix this error?

like image 966
3therk1ll Avatar asked Dec 05 '25 15:12

3therk1ll


1 Answers

Turns out the issue was indentation in my UserSerializer class.

See this issue:

Django users being created with cleartext passwords

like image 85
3therk1ll Avatar answered Dec 09 '25 00:12

3therk1ll



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!