You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写测试用例验证访客用户无法编辑他人帖子

验证未登录访客无法编辑帖子的Django测试用例实现

结合你的现有代码和需求,可通过Django自带的TestCase框架编写测试用例,验证未登录用户无法访问编辑接口。以下是具体实现:

测试逻辑说明

你的edit视图已通过@login_required装饰器限制未登录用户访问,未登录用户发起请求时会被重定向到登录页面。测试用例需要验证这一重定向行为,同时确保帖子内容不会被未登录用户篡改。

测试用例代码

在应用目录下创建tests.py文件,添加如下代码:

from django.test import TestCase
from django.urls import reverse
from django.contrib.auth.models import User
from .models import Post

class PostEditAuthTest(TestCase):
    def setUp(self):
        # 初始化测试数据:创建测试用户和测试帖子
        self.test_user = User.objects.create_user(username='testuser', password='testpass123')
        self.test_post = Post.objects.create(user=self.test_user, content='原始帖子内容')

    def test_unauthenticated_user_cannot_edit_post(self):
        # 构造编辑接口的URL
        edit_url = reverse('edit', args=[self.test_post.id])
        # 模拟未登录用户发送POST请求尝试编辑
        response = self.client.post(edit_url, {'content': '被篡改的内容'})
        
        # 验证响应为登录重定向(状态码302)
        self.assertEqual(response.status_code, 302)
        # 验证重定向目标为登录页面
        self.assertRedirects(response, reverse('login'))
        
        # 从数据库重新获取帖子,确认内容未被修改
        updated_post = Post.objects.get(id=self.test_post.id)
        self.assertEqual(updated_post.content, '原始帖子内容')

    def test_unauthenticated_user_cannot_access_edit_page(self):
        # 测试未登录用户通过GET请求访问编辑接口的情况
        edit_url = reverse('edit', args=[self.test_post.id])
        response = self.client.get(edit_url)
        
        # 验证同样被重定向到登录页
        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, reverse('login'))

代码解释

  • setUp方法:在每个测试方法执行前创建测试用户和帖子,避免重复初始化操作。
  • test_unauthenticated_user_cannot_edit_post:模拟未登录用户的POST编辑请求,双重验证重定向行为和帖子内容完整性。
  • test_unauthenticated_user_cannot_access_edit_page:补充验证GET请求的访问限制,确保所有访问方式都被拦截。

运行测试

在项目根目录执行以下命令启动测试:

python manage.py test network

补充建议

你还可以补充测试用例验证登录用户仅能编辑自己的帖子,进一步完善接口权限的测试覆盖。

内容的提问来源于stack exchange,提问作者Javier

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 15:54:49