File: users.py

package info (click to toggle)
python-pytest-djangoapp 1.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 396 kB
  • sloc: python: 1,116; makefile: 114; sh: 6
file content (92 lines) | stat: -rw-r--r-- 2,117 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
from typing import Union

import pytest

from .utils import get_stamp

if False:  # pragma: nocover
    from django.contrib.auth.models import AbstractUser, AnonymousUser  # noqa


TypeUser = Union['AbstractUser', 'AnonymousUser']


@pytest.fixture()
def user_model() -> TypeUser:
    """Returns user model class.

    Example::

        def test_this(user_model):
            model_cls = user_model

    """
    from django.contrib.auth import get_user_model

    return get_user_model()


@pytest.fixture()
def user_create(user_model):
    """Allows Django user object generation.

    Example::

        def test_this(user_create):
            user = user_create()

    .. note:: User password is accessible via `password_plain` attribute.

    :param superuser: Whether to create a superuser.
    :param anonymous: Whether to create an anonymous user.
    :param attributes: Additional user object attributes to initialize.

    """
    from django.contrib.auth.models import AnonymousUser

    def user_create_(*, superuser: bool = False, anonymous: bool = False, attributes: dict = None) -> TypeUser:

        if anonymous:
            return AnonymousUser()

        attributes = attributes or {}
        manager = user_model._default_manager

        username = (('admin' if superuser else 'user') + '_' + get_stamp())

        kwargs = {
            'username': username,
            'email': f'{username}@example.com',
            'password': 'password',
        }

        kwargs.update(attributes)

        if superuser:
            user = manager.create_superuser(**kwargs)
        else:
            user = manager.create_user(**kwargs)

        # Keep plain password for test purposes.
        user.password_plain = kwargs['password']

        return user

    return user_create_


@pytest.fixture()
def user(user_create) -> TypeUser:
    """Exposes Django user object.

    Shortcut for `user_create` fixture.

    Example::

        def test_this(user):
            username = user.username

    .. note:: User password is accessible via `password_plain` attribute.

    """
    return user_create()