Pytest-django:设置用户权限

时间:2017-02-14 07:32:26

标签: django pytest pytest-django

我使用pytest 3.0.6和pytest-django 3.1.2为Django工作。我有这个非常简单的测试失败,我不明白发生了什么:

# test_mytest.py
import pytest
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType


@pytest.mark.django_db
def test_user_has_perm(django_user_model):
    # Create a new user
    john_doe = django_user_model.objects.create_user('johndoe', email='jd@example.com', password='123456')

    # Get or create the permission to set on user
    user_ct = ContentType.objects.get(app_label='auth', model='user')
    p, _ = Permission.objects.get_or_create(content_type=user_ct, codename='delete_user', name="Can delete user")

    # User don't have the permission
    assert john_doe.has_perm(p) is False

    # Set permission to user
    john_doe.user_permissions.add(p)
    assert john_doe.has_perm(p) is True  # ---> FAIL

以防万一,测试结果如下:

$ pytest
============================= test session starts =============================
platform win32 -- Python 3.5.3, pytest-3.0.6, py-1.4.32, pluggy-0.4.0
Django settings: testsite.settings (from ini file)
rootdir: D:\Dev\foss\django-modern-rpc, inifile: tox.ini
plugins: pythonpath-0.7.1, django-3.1.2, cov-2.4.0
collected 1 items

modernrpc\tests\test_test_test.py F

================================== FAILURES ===================================
_____________________________ test_user_has_perm ______________________________

django_user_model = <class 'django.contrib.auth.models.User'>

    @pytest.mark.django_db
    def test_user_has_perm(django_user_model):
        # Create a new user
        john_doe = django_user_model.objects.create_user('johndoe', email='jd@example.com', password='123456')

        # Get or create the permission to set on user
        user_ct = ContentType.objects.get(app_label='auth', model='user')
        p, _ = Permission.objects.get_or_create(content_type=user_ct, codename='delete_user', name="Can delete user")

        # User don't have the permission
        assert john_doe.has_perm(p) is False

        # Set permission to user
        john_doe.user_permissions.add(p)
>       assert john_doe.has_perm(p) is True  # ---> FAIL
E       assert False is True
E        +  where False = <bound method PermissionsMixin.has_perm of <User: johndoe>>(<Permission: auth | user | Can delete user>)
E        +    where <bound method PermissionsMixin.has_perm of <User: johndoe>> = <User: johndoe>.has_perm

modernrpc\tests\test_test_test.py:20: AssertionError
========================== 1 failed in 0.32 seconds ===========================

配置块,来自tox.ini:

[pytest]
DJANGO_SETTINGS_MODULE = testsite.settings
norecursedirs = .git __pycache__ build dist venv* .tox .vscode .cache *.egg-info
python_paths = modernrpc/tests
testpaths = modernrpc/tests
python_files = test_*.py dummy_*.py

数据库配置,来自测试设置:

BASE_DIR = os.path.dirname(os.path.dirname(__file__))
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'modern_rpc.sqlite3'),
    },
}

我做错了什么?

2 个答案:

答案 0 :(得分:5)

您需要使用字符串'app_label.codename'

  

如果用户具有指定的权限,则返回True,其中perm的格式为&#34;&lt; app label&gt;。&lt; permission codename&gt;&#34;。

此外,如果自上次调用user._perm_cache后更改了权限,则必须清除user._user_perm_cachehas_perm,或者从数据库中检索此用户的新实例以确保存在没有缓存:

 del john_doe._perm_cache
 del john_doe._user_perm_cache 
 # OR
 john_doe = django_user_model.objects.get(username='johndoe')

这是因为has_perm将调用auth后端,后端将首先查询这些缓存。

答案 1 :(得分:2)

来自docs

  

has_perm(perm,obj = None)

     

如果用户具有指定的权限,则返回True,其中perm的格式为

     

"<app label>.<permission codename>"

     

(请参阅权限文档)。如果用户处于非活动状态,则此方法   将永远返回False。

     

如果传入了obj,则此方法不会检查模型的权限,而是检查此特定对象的权限。

因此,此方法接受字符串而不是权限对象

john_doe.has_perm('auth.delete_user')

应该返回True。 (delete_user权限已分配auth个应用,因为您已使用user_ct创建该应用,其中user_ct的应用为auth}。

但是在您的示例中,这不会立即发生,因为还有permission check caching

在您重新获取对象后它将起作用

#Be aware this only works after Django 1.9+
#https://code.djangoproject.com/ticket/26514
john_doe.refresh_from_db()
#Otherwise use:
john_doe = User.objects.get(pk=john_doe.pk)