在开发基于角色的 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')