# 导入Django测试客户端、请求工厂、测试用例 from django.test import Client, RequestFactory, TestCase # 导入URL反向解析 from django.urls import reverse # 导入时区工具 from django.utils import timezone # 导入延迟翻译函数 from django.utils.translation import gettext_lazy as _ # 导入账户模型 from accounts.models import BlogUser # 导入博客模型 from blog.models import Article, Category # 导入项目工具函数 from djangoblog.utils import * # 导入当前应用的工具函数 from . import utils # 在这里创建测试 class AccountTest(TestCase): """账户功能测试类""" def setUp(self): """测试前置设置,每个测试方法执行前都会调用""" # 创建测试客户端 self.client = Client() # 创建请求工厂 self.factory = RequestFactory() # 创建测试用户 self.blog_user = BlogUser.objects.create_user( username="test", # 用户名 email="admin@admin.com", # 邮箱 password="12345678" # 密码 ) # 设置新测试密码 self.new_test = "xxx123--=" def test_validate_account(self): """测试账户验证功能""" # 获取当前站点 site = get_current_site().domain # 创建超级用户 user = BlogUser.objects.create_superuser( email="liangliangyy1@gmail.com", # 邮箱 username="liangliangyy1", # 用户名 password="qwer!@#$ggg" # 密码 ) # 从数据库获取刚创建的用户 testuser = BlogUser.objects.get(username='liangliangyy1') # 尝试登录 loginresult = self.client.login( username='liangliangyy1', # 用户名 password='qwer!@#$ggg' # 密码 ) # 断言登录成功 self.assertEqual(loginresult, True) # 访问管理员页面 response = self.client.get('/admin/') # 断言页面访问成功 self.assertEqual(response.status_code, 200) # 创建分类 category = Category() category.name = "categoryaaa" # 分类名称 category.creation_time = timezone.now() # 创建时间 category.last_modify_time = timezone.now() # 最后修改时间 category.save() # 创建文章 article = Article() article.title = "nicetitleaaa" # 文章标题 article.body = "nicecontentaaa" # 文章内容 article.author = user # 文章作者 article.category = category # 文章分类 article.type = 'a' # 文章类型 article.status = 'p' # 文章状态:发布 article.save() # 访问文章管理页面 response = self.client.get(article.get_admin_url()) # 断言页面访问成功 self.assertEqual(response.status_code, 200) def test_validate_register(self): """测试用户注册功能""" # 断言注册前邮箱不存在 self.assertEquals( 0, len(BlogUser.objects.filter(email='user123@user.com'))) # 发送注册POST请求 response = self.client.post(reverse('account:register'), { 'username': 'user1233', # 用户名 'email': 'user123@user.com', # 邮箱 'password1': 'password123!q@wE#R$T', # 密码 'password2': 'password123!q@wE#R$T', # 确认密码 }) # 断言注册后邮箱存在 self.assertEquals( 1, len(BlogUser.objects.filter(email='user123@user.com'))) # 获取刚注册的用户 user = BlogUser.objects.filter(email='user123@user.com')[0] # 生成验证签名 sign = get_sha256(get_sha256(settings.SECRET_KEY + str(user.id))) # 构建验证URL路径 path = reverse('accounts:result') # 构建完整验证URL url = '{path}?type=validation&id={id}&sign={sign}'.format( path=path, # 路径 id=user.id, # 用户ID sign=sign # 签名 ) # 访问验证URL response = self.client.get(url) # 断言页面访问成功 self.assertEqual(response.status_code, 200) # 登录用户 self.client.login(username='user1233', password='password123!q@wE#R$T') # 获取用户并设置为管理员 user = BlogUser.objects.filter(email='user123@user.com')[0] user.is_superuser = True # 设置为超级用户 user.is_staff = True # 设置为工作人员 user.save() # 删除侧边栏缓存 delete_sidebar_cache() # 创建分类 category = Category() category.name = "categoryaaa" # 分类名称 category.creation_time = timezone.now() # 创建时间 category.last_modify_time = timezone.now() # 最后修改时间 category.save() # 创建文章 article = Article() article.category = category # 文章分类 article.title = "nicetitle333" # 文章标题 article.body = "nicecontentttt" # 文章内容 article.author = user # 文章作者 article.type = 'a' # 文章类型 article.status = 'p' # 文章状态:发布 article.save() # 访问文章管理页面 response = self.client.get(article.get_admin_url()) # 断言页面访问成功 self.assertEqual(response.status_code, 200) # 登出用户 response = self.client.get(reverse('account:logout')) # 断言登出成功(重定向状态码) self.assertIn(response.status_code, [301, 302, 200]) # 再次访问文章管理页面(应该被重定向到登录页) response = self.client.get(article.get_admin_url()) # 断言被重定向 self.assertIn(response.status_code, [301, 302, 200]) # 使用错误密码尝试登录 response = self.client.post(reverse('account:login'), { 'username': 'user1233', # 用户名 'password': 'password123' # 错误密码 }) # 断言登录失败(重定向状态码) self.assertIn(response.status_code, [301, 302, 200]) # 再次访问文章管理页面(应该仍然被重定向) response = self.client.get(article.get_admin_url()) # 断言被重定向 self.assertIn(response.status_code, [301, 302, 200]) def test_verify_email_code(self): """测试邮箱验证码功能""" # 测试邮箱 to_email = "admin@admin.com" # 生成验证码 code = generate_code() # 设置验证码到缓存 utils.set_code(to_email, code) # 发送验证邮件 utils.send_verify_email(to_email, code) # 验证正确验证码 err = utils.verify("admin@admin.com", code) # 断言验证成功(返回None) self.assertEqual(err, None) # 验证错误验证码 err = utils.verify("admin@123.com", code) # 断言验证失败(返回错误信息字符串) self.assertEqual(type(err), str) def test_forget_password_email_code_success(self): """测试成功获取忘记密码验证码""" # 发送获取验证码的POST请求 resp = self.client.post( path=reverse("account:forget_password_code"), # URL路径 data=dict(email="admin@admin.com") # 请求数据:邮箱 ) # 断言响应状态码为200 self.assertEqual(resp.status_code, 200) # 断言响应内容为"ok" self.assertEqual(resp.content.decode("utf-8"), "ok") def test_forget_password_email_code_fail(self): """测试获取忘记密码验证码失败情况""" # 发送空数据的POST请求 resp = self.client.post( path=reverse("account:forget_password_code"), # URL路径 data=dict() # 空数据 ) # 断言返回错误信息 self.assertEqual(resp.content.decode("utf-8"), "错误的邮箱") # 发送无效邮箱的POST请求 resp = self.client.post( path=reverse("account:forget_password_code"), # URL路径 data=dict(email="admin@com") # 无效邮箱格式 ) # 断言返回错误信息 self.assertEqual(resp.content.decode("utf-8"), "错误的邮箱") def test_forget_password_email_success(self): """测试成功重置密码""" # 生成验证码 code = generate_code() # 设置验证码到缓存 utils.set_code(self.blog_user.email, code) # 准备请求数据 data = dict( new_password1=self.new_test, # 新密码 new_password2=self.new_test, # 确认密码 email=self.blog_user.email, # 邮箱 code=code, # 验证码 ) # 发送重置密码的POST请求 resp = self.client.post( path=reverse("account:forget_password"), # URL路径 data=data # 请求数据 ) # 断言重定向响应(状态码302) self.assertEqual(resp.status_code, 302) # 验证用户密码是否修改成功 blog_user = BlogUser.objects.filter( email=self.blog_user.email, ).first() # 类型注解:BlogUser # 断言用户存在 self.assertNotEqual(blog_user, None) # 断言新密码验证通过 self.assertEqual(blog_user.check_password(data["new_password1"]), True) def test_forget_password_email_not_user(self): """测试重置密码时邮箱不存在的情况""" # 准备请求数据(不存在的邮箱) data = dict( new_password1=self.new_test, # 新密码 new_password2=self.new_test, # 确认密码 email="123@123.com", # 不存在的邮箱 code="123456", # 验证码 ) # 发送重置密码的POST请求 resp = self.client.post( path=reverse("account:forget_password"), # URL路径 data=data # 请求数据 ) # 断言返回表单页面(状态码200) self.assertEqual(resp.status_code, 200) def test_forget_password_email_code_error(self): """测试重置密码时验证码错误的情况""" # 生成验证码 code = generate_code() # 设置验证码到缓存 utils.set_code(self.blog_user.email, code) # 准备请求数据(错误的验证码) data = dict( new_password1=self.new_test, # 新密码 new_password2=self.new_test, # 确认密码 email=self.blog_user.email, # 邮箱 code="111111", # 错误的验证码 ) # 发送重置密码的POST请求 resp = self.client.post( path=reverse("account:forget_password"), # URL路径 data=data # 请求数据 ) # 断言返回表单页面(状态码200) self.assertEqual(resp.status_code, 200)