使用 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')
相关推荐
markfeng817 小时前
Python+Django+H5+MySQL项目搭建
python·django
Turnip120220 小时前
深度解析:为什么简单的数据库"写操作"会在 MySQL 中卡住?
后端·mysql
爱可生开源社区20 小时前
2026 年,优秀的 DBA 需要具备哪些素质?
数据库·人工智能·dba
随逸1771 天前
《从零搭建NestJS项目》
数据库·typescript
加号32 天前
windows系统下mysql多源数据库同步部署
数据库·windows·mysql
シ風箏2 天前
MySQL【部署 04】Docker部署 MySQL8.0.32 版本(网盘镜像及启动命令分享)
数据库·mysql·docker
李慕婉学姐2 天前
Springboot智慧社区系统设计与开发6n99s526(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·spring boot·后端
QQ4022054962 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
百锦再2 天前
Django实现接口token检测的实现方案
数据库·python·django·sqlite·flask·fastapi·pip
starlaky2 天前
Django入门笔记
笔记·django