使用 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')
相关推荐
这个DBA有点耶5 小时前
从MySQL 5.7到8.0:JSON查询性能差在哪?虚拟列索引vs多值索引怎么选
数据库·mysql·架构
胡写代码5 小时前
数据库审计字段,别再每张表各写一套了——我统一成这 6 个字段
数据库
SelectDB9 小时前
为什么 JSON 正在成为分析数据库新的竞争点?
数据库·json·agent
ClouGence10 小时前
开源数据库管理工具 CloudDM 4.2.0 发布,新增 GoldenDB、KingbaseES 等数据源
数据库·dba·devops
发霉的馒头10 小时前
ORA-00845: MEMORY_TARGET not supported on this system的解决方法
数据库
ikun_文10 小时前
Django框架路由Router的使用
python·pycharm·django
草莓熊Lotso12 小时前
【Redis 初阶】Set 类型深度解析:去重集合的运算能力与实战场景
linux·网络·数据库·windows·redis·tcp/ip·缓存
煎饼皮皮侠13 小时前
【设计】设计一个web版的数据库管理平台后端(之五) --借鉴mybatis
数据库·mybatis
东风破_19 小时前
danci 2:创建的单词书到底存在哪里?从 Supabase 一路理解 ORM、Drizzle 和 RLS
数据库·后端·node.js
九皇叔叔20 小时前
《MySQL 体系架构详解:Server 层、SQL 执行流程与 InnoDB、MyISAM、MEMORY 存储引擎》
sql·mysql·架构