#wzc: 评论模块的测试用例
from django.test import Client, RequestFactory, TransactionTestCase
from django.urls import reverse

from accounts.models import BlogUser
from blog.models import Category, Article
from comments.models import Comment
from comments.templatetags.comments_tags import *
from djangoblog.utils import get_max_articleid_commentid


class CommentsTest(TransactionTestCase):
    """wzc: 评论功能测试类"""

    def setUp(self):
        """wzc: 测试初始化设置"""
        self.client = Client()
        self.factory = RequestFactory()

        #wzc: 设置博客配置，评论需要审核
        from blog.models import BlogSettings
        value = BlogSettings()
        value.comment_need_review = True
        value.save()

        #wzc: 创建测试用户
        self.user = BlogUser.objects.create_superuser(
            email="liangliangyy1@gmail.com",
            username="liangliangyy1",
            password="liangliangyy1")

    def update_article_comment_status(self, article):
        """wzc: 更新文章所有评论为启用状态"""
        comments = article.comment_set.all()
        for comment in comments:
            comment.is_enable = True
            comment.save()

    def test_validate_comment(self):
        """wzc: 测试评论验证流程"""
        self.client.login(username='liangliangyy1', password='liangliangyy1')

        #wzc: 创建测试分类和文章
        category = Category.objects.create(name="categoryccc")
        article = Article.objects.create(
            title="nicetitleccc",
            body="nicecontentccc",
            author=self.user,
            category=category,
            type='a',
            status='p'
        )

        comment_url = reverse('comments:postcomment', kwargs={'article_id': article.id})

        #wzc: 测试发表评论
        response = self.client.post(comment_url, {'body': '123ffffffffff'})
        self.assertEqual(response.status_code, 302)

        #wzc: 验证评论状态
        article = Article.objects.get(pk=article.pk)
        self.assertEqual(len(article.comment_list()), 0)

        #wzc: 启用评论后验证
        self.update_article_comment_status(article)
        self.assertEqual(len(article.comment_list()), 1)

        #wzc: 测试评论模板标签功能
        comment = Comment.objects.first()
        tree = parse_commenttree(article.comment_list(), comment)
        self.assertEqual(len(tree), 1)

        data = show_comment_item(comment, True)
        self.assertIsNotNone(data)

        #wzc: 测试工具函数
        s = get_max_articleid_commentid()
        self.assertIsNotNone(s)

        from comments.utils import send_comment_email
        send_comment_email(comment)