使用 Django 测试脚本验证用户角色与权限:自动化测试用户仪表盘访

在开发基于角色的 Web 应用时(如学生-教师系统),确保不同角色用户只能访问其授权页面是至关重要的。Django 提供了强大的认证和测试工具,可以帮助我们快速创建测试用户、模拟登录并验证页面访问权限。

本文将介绍一个简洁但功能完整的 Django 测试脚本 ,它能自动创建具有特定角色的用户,并验证他们是否能正确访问各自的仪表盘页面(如学生仪表盘 /users/student/dashboard/ 和教师仪表盘 /users/teacher/dashboard/)。


背景:为什么需要这样的测试?

在典型的教育类或企业管理系统中,我们通常有如下需求:

  • 学生只能访问学生专属页面;
  • 教师只能访问教师专属页面;
  • 管理员拥有更高权限;
  • 未登录用户应被重定向到登录页。

手动测试这些场景既繁琐又容易遗漏。而通过编写自动化脚本,我们可以在开发过程中快速验证权限逻辑是否按预期工作。


脚本解析

python 复制代码
from django.contrib.auth.models import User
from users.models import UserProfile
from django.test import Client
import traceback


def ensure_user(username, password, role):
    if not User.objects.filter(username=username).exists():
        u = User.objects.create_user(username=username, password=password, email=f"{username}@example.com")
    else:
        u = User.objects.get(username=username)
    if not hasattr(u, 'profile'):
        UserProfile.objects.create(user=u, role=role)
    else:
        u.profile.role = role
        u.profile.save()
    return u


def check(path, username, password):
    client = Client()
    ok = client.login(username=username, password=password)
    print(f'logged in {username}:', ok)
    try:
        resp = client.get(path)
        print(f'GET {path} ->', resp.status_code)
        # Print short content for inspection
        try:
            print(resp.content.decode('utf-8')[:2000])
        except Exception:
            print('<could not decode response content>')
    except Exception:
        traceback.print_exc()


if __name__ == '__main__':
    ensure_user('test_student', 'pass123', 'student')
    ensure_user('test_teacher', 'pass123', 'teacher')

    check('/users/student/dashboard/', 'test_student', 'pass123')
    check('/users/teacher/dashboard/', 'test_teacher', 'pass123')
相关推荐
高级程序源5 小时前
django校园寻物通失物招领平台32261-计算机课程设计、毕业设计
vue.js·python·mysql·小程序·django·flask·课程设计
WeiXin_DZbishe5 小时前
基于springboot宠物领养系统-计算机毕设 附源码【课程设计】94217
vue.js·spring boot·python·django·php·课程设计
KIDULT°6 小时前
MySQL系列 (1):数据库原理
运维·数据库·mysql·云计算
我不是程序员三三6 小时前
透明加密软件偶发解密异常排错实录:文件时能打开时乱码
数据库·域智盾
snhna6 小时前
向量数据库深度实战:从 HNSW 到 pgvector、Milvus 选型与 RAG 落地
数据库·人工智能·python·postgresql·milvus
天行健,君子而铎6 小时前
数据分类分级的范式转换:从规则匹配到场景化高准确率一键部署
网络·数据库·安全
牛战士coding7 小时前
MySQL 读写分离完整链路:主从复制、多数据源与 @DS 路由
数据库·mysql
Wx-bishekaifayuan8 小时前
springboot汉中旅游服务平台41442-计算机课程设计、毕业设计
spring boot·后端·python·django·课程设计·express·旅游
goehou8 小时前
MCP 查数实战:让 LLM 安全地查数据库(只读账号、SQL 校验、参数漂移)
数据库·ai·llm·教程·mcp·function calling
我不会插花弄玉8 小时前
7.函数【由浅入深-MySQL】
android·数据库·mysql