为什么我的测试视图响应为空?

时间:2018-07-06 17:22:42

标签: django django-views django-testing django-unittest django-tests

我的帖子详细信息视图如下。

class PostDetailView(AjaxResponseMixin, UpdateView):
model = UserPost
context_object_name = 'post'
template_name = 'feed/post_detail.html'
form_class = CommentForm

def get_initial(self):
    initial_data = super(PostDetailView, self).get_initial()
    obj = self.get_object()
    initial_data.update({
        "content_type": obj.get_content_type,
        "object_id": obj.id
    })
    return initial_data

def get_context_data(self, **kwargs):
    # comment_form = CommentForm
    context = super(PostDetailView, self).get_context_data(**kwargs)
    kwargs['form_comment'] = context['form']  # comment_form
    try:
        total_views = r.incr('userpost:{}:views'.format(self.object.pk))
        kwargs['total_views'] = total_views
    except (redis.exceptions.ConnectionError,
            redis.exceptions.BusyLoadingError):
        pass

    return super(PostDetailView, self).get_context_data(**kwargs)

def get_success_url(self):
    try:
        total_views = r.incr('userpost:{}:views'.format(self.object.pk))
    except (redis.exceptions.ConnectionError,
            redis.exceptions.BusyLoadingError):
        pass
    return reverse_lazy('feed:post_detail', kwargs={'pk': self.object.pk})

def form_valid(self, form):
    c_type = form.cleaned_data.get("content_type")
    obj_id = form.cleaned_data.get('object_id')
    content_data = form.cleaned_data.get("content")
    parent_obj = None
    try:
        parent_id = int(self.request.POST.get("parent_id"))
    except:
        parent_id = None

    if parent_id:
        parent_qs = Comment.objects.filter(pk=parent_id)
        if parent_qs.exists() and parent_qs.count() == 1:
            parent_obj = parent_qs.first()

    new_comment, created = Comment.objects.get_or_create(
        user=self.request.user,
        content_type=c_type,
        object_id=obj_id,
        content=content_data,
        parent=parent_obj,
    )
    if created:
        ct = ContentType.objects.get_for_id(c_type.id)
        obj = ct.get_object_for_this_type(pk=obj_id)
        create_action(self.request.user, 'commented on', obj)
    return super(PostDetailView, self).form_valid(form)

def form_invalid(self, form):
    print("invalid form")

我正在编写如下的测试用例。

class PostDetailViewTests(TestCase):
@classmethod
def setUpTestData(cls):
    user = User.objects.create_user(username='chitra', password='password123')
    cls.post = UserPost(author=user, post_body="Test post", )
    cls.post.save()


def setUp(self):
    login = self.client.login(username='chitra', password='password123')
    user = auth.get_user(self.client)
    assert user.is_authenticated

def test_postdetail_view_page_status_code(self):
    """
    Test that a PostDetailView page is rendering correctly
    """
    response = self.client.get(reverse_lazy('feed:post_detail', kwargs={'pk': self.post.pk}))
    self.assertEquals(response.status_code, 200, 'post doesnt exist with pk={}'.format(self.post.pk))
    self.assertTemplateUsed(response, 'feed/post_detail.html', 'Template used is wrong')

def test_postdetail_view_post_comment(self):
    """
    Test that a comment is posted ot post correctly
    """
    user = User.objects.get(pk=1)
    resp = self.client.post(reverse_lazy('feed:post_detail', kwargs={'pk': self.post.pk}), {'content': 'just a comment'})
    self.assertEqual(resp.status_code, 200)
    # co.refresh_from_db()
    self.assertTrue(Comment.objects.filter().exists())

Comment / forms.py

class CommentForm(ModelForm):

class Meta:
    model = Comment
    fields = ['content_type', 'object_id', 'content']  # list of fields you want from model
    widgets = {'content_type':  HiddenInput(), 'object_id': HiddenInput(),
        'content': Textarea(attrs={'rows': 4, 'cols': 65}),
   }

comment / models.py

class Comment(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
parent = models.ForeignKey("self", null=True, blank=True, on_delete=models.CASCADE)
content = models.TextField()
timestamp = models.DateTimeField(auto_now_add=True)
objects = CommentManager()

好,在这里,“ test_postdetail_view_page_status_code”测试通过,但发布失败,即“ test_postdetail_view_post_comment”,此处的响应为None!

基本上,视图只是帖子的显示,带有评论列表和评论列表(如果有)的评论表单,评论正文(即字段内容)是唯一的输入参数,并且内容类型用于保存评论对象,如图所示。我正在使用方法'get_initial',以帖子ID初始化内容类型对象(请参阅),我认为resp是None,因为我需要先将显示称为self.client.get,然后使用self.client.post在这里?,我认为没有调用get_initial,所以它没有内容类型数据吗?我不确定如何调试它以检查测试用例在哪里失败!

对此表示感谢,谢谢!

0 个答案:

没有答案