python-3.x - user.check_password 断言失败

标签 python-3.x django-rest-framework

我有一些测试试图在 API 应用程序中验证我的用户创建过程。

我遇到的问题是,当我尝试验证用户密码是否创建为散列对象时,测试失败。

测试:

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': 'test@email.com',
            '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)

序列化器:

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)

失败的测试:

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

根据我从文档等中可以看出的,我有正确的语法。

Wjhat 缺失/不正确,我需要修复此错误?

最佳答案

原来问题出在我的 UserSerializer 类中。

查看此问题:

Django users being created with cleartext passwords

关于python-3.x - user.check_password 断言失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61856983/

相关文章:

python - tf.where 导致优化器在 tensorflow 中失败

python - 如何将值列表转换为字典列表,并将相同的键添加到每个值?

Django Rest Framework 模型序列化器没有唯一的共同验证

django - 我真的需要 Django Rest Framework 来使用 Django 开发 Restful api 吗?

python-3.x - Azure 函数 HTTP 触发器 : How to return exception from python worker log to the API caller

python - 如何找到使用 Turtle Python Graphics 绘制的圆的半径?

python - 欧拉计划 #17 的意外结果(Python 3 与 Python 2.7)

python - django rest 框架中基于类的 View 的自定义装饰器

Django休息框架: How to set a field to null via PATCH request?

django - 在 django 中何时使用viewsets.Viewset和viewsets.ModelViewSet的困惑