测试ModelSerializers

时间:2016-08-27 10:29:43

标签: python django django-rest-framework

我正在尝试学习测试序列化程序的最佳方法,但遇到一些问题。在下面的示例中,我正在测试是否正在创建新用户。即可以哈希密码。我得到的错误是:

  

TypeError:create()缺少1个必需的位置参数:   ' validated_data'

我不确定我需要传递的内容为var requestSourceOrdered = requests .GroupBy(x => x.REQ_SOURCE) .SelectMany(x => x.OrderBy(y => y.REQ_DATE)) .ToList()

serializers.py

validated_data

tests.py

class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ('url', 'username', 'email', 'password')
        extra_kwargs = {
            'url': {'view_name': 'user-detail'},
            'password': {'write_only': True}
        }

    def create(self, validated_data):
        user = User.objects.create_user(
            username=validated_data['username'],
            email=validated_data['email'])

        user.set_password(validated_data['password'])
        user.save()

        return user

    def update(self, instance, validated_data):
        user = User.objects.get(id=instance.id)
        user.set_password(validated_data['password'])
        user.save()

        return user

1 个答案:

答案 0 :(得分:1)

您在测试中调用了create。您应该致电is_valid然后save

user = UserSerializer(data=data, context=self.serializer_context)
user.is_valid(raise_exception=True)
user.save()