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): def setUp(self): # 初始化测试客户端和请求工厂 self.client = Client() self.factory = RequestFactory() # 设置评论需要审核才能显示 from blog.models import BlogSettings value = BlogSettings() value.comment_need_review = True value.save() # 创建超级用户用于登录测试 self.user = BlogUser.objects.create_superuser( email="liangliangyy1@gmail.com", username="liangliangyy1", password="liangliangyy1") def update_article_comment_status(self, article): """批量启用文章下的所有评论""" comments = article.comment_set.all() for comment in comments: comment.is_enable = True comment.save() def test_validate_comment(self): # 登录测试用户 self.client.login(username='liangliangyy1', password='liangliangyy1') # 创建测试分类 category = Category() category.name = "categoryccc" category.save() # 创建测试文章 article = Article() article.title = "nicetitleccc" article.body = "nicecontentccc" article.author = self.user article.category = category article.type = 'a' article.status = 'p' article.save() # 获取评论提交的URL comment_url = reverse( 'comments:postcomment', kwargs={ 'article_id': article.id}) # 测试发布第一条评论 response = self.client.post(comment_url, { 'body': '123ffffffffff' }) self.assertEqual(response.status_code, 302) # 验证重定向 #断言:评论未审核时不显示 article = Article.objects.get(pk=article.pk) self.assertEqual(len(article.comment_list()), 0) # 审核通过所有评论 self.update_article_comment_status(article) self.assertEqual(len(article.comment_list()), 1) # 验证评论已显示 # 测试发布第二条评论 response = self.client.post(comment_url, { 'body': '123ffffffffff', }) self.assertEqual(response.status_code, 302) article