Django:测试管理员用户

时间:2013-03-28 05:35:29

标签: python django unit-testing

我需要在django应用中测试我的一个视图,这需要admin user具有某些权限

如何创建test user并设置一些权限,例如staff statusgroup permissions

我可以使用工厂吗。

1 个答案:

答案 0 :(得分:1)

要创建裸超级用户,请执行python manage.py createsuperuser https://docs.djangoproject.com/en/dev/ref/django-admin/#createsuperuser

要初始设置权限,请创建自定义django-admin命令 app_name/commands/management/create_test_user.py

from django.contrib.auth.models import User, Group, Permission
from django.core.management.base import BaseCommand

class Command( BaseCommand ):

    help = "Creates test user"
    args = '<username> <password>'

    def handle( self, username, password ):

        user, created = User.objects.get_or_create( username=username ) 
        user.set_password( password )
        user.is_staff = True
        user.save()

        custom_perm = Permission.objects.get( codename='custom_perm_name' )
        user.user_permissions.add( custom_perm )

        if created:
            print "%s created" % username
        else:
            print "%s updated" % username

然后:

python manage.py create_test_user admin1 qwe123