我正在为我的博客应用程序编写单元测试。我的一个post请求测试不断获得HTTP 200结果,虽然我期望HTTP 301.这是测试代码:
def test_create_user_post(self):
response = self.client.post("/create_user/", {
"user": self.user, "full_name": "Test User", "location":
"Istanbul", "age": 26
})
self.assertEqual(response.status_code, 301)
创建用户视图使用用户外键创建新用户。这是UserProfile
模型:
class UserProfile(models.Model):
user = models.OneToOneField(User, unique=True)
full_name = models.CharField(max_length=200)
age = models.IntegerField(blank=True)
location = models.CharField(max_length=300)
slug_name = models.SlugField(blank=True)
profile_pic = StdImageField(
upload_to='images/profile', blank=True, variations={'thumbnail': (450, 300)})
def save(self, *args, **kwargs):
self.slug_name = slugify(self.full_name)
super(UserProfile, self).save(*args, **kwargs)
以下是create_user
视图:
def create_user(request):
if request.method == 'POST':
form = UserForm(
request.POST, initial={'user': request.user.username})
if form.is_valid():
form.save()
return HttpResponseRedirect("/blogs/")
else:
form.non_field_errors()
else:
form = UserForm(initial={'user': request.user.username})
return render(request, "BlogApp/create_user.html", {"form": form})
我没有用户的其他帖子请求返回301响应,我对它持怀疑态度。这是另一个可以正常运行的帖子请求测试示例:
def test_comment_post_in_blog(self):
response = self.client.post("/blog/11", {"comment_text": 'This is a '
'test '
'comment.'})
self.assertEqual(response.status_code, 301)
self.assertEqual(response['Location'], "http://testserver/blog/11/")
我找不到问题,希望我能清楚地解释清楚。希望能听到你们的一些答案!