我正在为CreateUser视图编写测试用例,但测试失败。它抛出以下错误
profile_data = validated_data.pop('profile'( 键错误: 'profile'
我在这里做错了什么?我做错了a=在我的视图/序列化程序中还是我的测试代码是错误的? 它完美地创造了用户。
models.py
class Profile(models.Model):
user = models.OneToOneField(get_user_model(),on_delete=models.CASCADE)
address = models.CharField(max_length=250,blank=True,null=True)
contact = models.CharField(max_length=250,blank=True,null=True)
serializers.py
class UserSerializer(serializers.ModelSerializer):
profile = ProfileSerializer(required=False)
email = serializers.EmailField(validators=[UniqueValidator(queryset=get_user_model().objects.all())])
password1 = serializers.CharField(required=True, write_only=True)
password2 = serializers.CharField(required=True, write_only=True)
class Meta:
model = get_user_model()
fields = ['first_name', 'last_name', 'username', 'email', 'password1', 'password2', 'profile']
def validate_password1(self, password):
validators.validate_password(password=password)
def validate_password2(self, password):
validators.validate_password(password=password)
def validate(self, data):
if data['password1'] != data['password2']:
raise serializers.ValidationError("The two password fields didn't match.")
return data
# def validate_username(self, validated_data):
# username = validated_data['username']
# print('usr',username)
# if len(username) < 6 and len(username) > 15:
# raise ValidationError('Username must be between 6 and 15 characters long')
# return username
def create(self, validated_data):
user = get_user_model().objects.create(
username=validated_data['username'],
email=validated_data['email'],
first_name=validated_data['first_name'],
last_name=validated_data['last_name'],
)
user.set_password(validated_data['password2'])
user.is_staff = True
user.save()
profile_data = validated_data.pop('profile')
Profile.objects.create(
user=user, address=profile_data['address'], contact=profile_data['contact']
)
return user
views.py
class CreateUser(generics.CreateAPIView):
serializer_class = UserSerializer
queryset = get_user_model().objects.all()
tests.py
class UserCreateListTest(APITestCase):
def setUp(self):
self.client = Client()
def test_create_user(self):
url = reverse('users:create_user')
user = {'first_name':'first','last_name':'last','username':'username','email':'email@email.com',
'password1':'1234@password.com','password2':'1234@password.com',
"profile": {
"user": 1,
"address": "add",
"contact": "cc"
},
}
response = self.client.post(url,data=user,format='json')
print(response.status_code)
print(response.json())
return self.assertEqual(response.status_code,status.HTTP_201_CREATED)
在测试中,将类替换为Client
rest_framework.test.APIClient
def setUp(self):
self.client = Client()
这是不必要的。APITestCase
已经提供了self.client
APIClient