我正在尝试在Django中基于函数的视图上做一个TestCase,我得到了: AssertionError:200!= 302:响应未按预期重定向:响应代码为200(预期为302)错误。 该视图就像博客项目中的帖子一样,我认为我的帖子发布方式有误,但我不了解如何以正确的方式进行测试。
This is my related views:
## view where the button like appears
class PostDetailView(FormMixin, generic.DetailView):
model = Post
form_class = CreateComments
def get_success_url(self):
return reverse('post-detail', kwargs={'pk': self.object.id})
def get_context_data(self, **kwargs):
context = super(PostDetailView, self).get_context_data(**kwargs)
actual_post = get_object_or_404(Post, id=self.kwargs['pk'])
liked = False
if actual_post.likes.filter(id=self.request.user.id).exists():
liked = True
context['total_likes'] = actual_post.total_likes()
context['liked'] = liked
context['form'] = CreateComments()
return context
def post(self, request, *args, **kwargs):
self.object = self.get_object()
form = self.get_form()
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
def form_valid(self, form):
form.instance.author = self.request.user
form.instance.blog_post = get_object_or_404(Post, pk=self.kwargs['pk'])
form.save()
return super(PostDetailView, self).form_valid(form)
# related model:
class Post(models.Model):
"""Model representing a blog post"""
title = models.CharField(max_length=200, help_text='Enter a post title')
description = models.TextField(max_length=1000, help_text='Enter a description for the post')
date = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
likes = models.ManyToManyField(User, related_name='blog_post')
def total_likes(self):
return self.likes.count()
def __str__(self):
"""String for representing the Model object"""
return self.title
def get_absolute_url(self):
"""Returns the url to acces a detail record for this book"""
return reverse('post-detail', kwargs={'pk': self.pk})
## view of the proper like:
def LikeView(request, pk):
post = get_object_or_404(Post, id=request.POST.get('post_id'))
liked = False
if post.likes.filter(id=request.user.id).exists():
post.likes.remove(request.user)
liked = False
else:
post.likes.add(request.user)
liked = True
return HttpResponseRedirect(reverse('post-detail', args=[str(pk)]))
## urls.py
path('post/like/<int:pk>/', LikeView, name='like-post'),
## test with error:
def test_likes(self):
login = self.client.login(username='user1', password='user1senha')
post = self.client.get(reverse('post-detail', kwargs={'pk': '1'}))
response = self.client.post(reverse('post-detail', kwargs={'pk': '1'}), post.context['object'].likes.add(post.context['user']))
self.assertEqual(response.context['total_likes'], 1)
def test_likes_redirects_to_correct_template(self):
login = self.client.login(username='user1', password='user1senha')
post = self.client.get(reverse('post-detail', kwargs={'pk': '1'}))
response = self.client.post(reverse('post-detail', kwargs={'pk': '1'}), post.context['object'].likes.add(post.context['user']))
self.assertRedirects(response, reverse('post-detail', kwargs={'pk': '1'}))
在这些测试中,我要添加类似内容,但assertRedirects失败,请帮助我!
答案 0 :(得分:0)
我认为您的帖子没有返回您的期望。我建议在调试器中查看响应(或只在assertRedirects语句前面使用print(response))。帖子发布期间可能有错误。
好消息是该测试可能会按设计工作。