fixtures.py 3.8 KB
import json

import pytest

from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
from oauth2_provider.models import get_application_model
from rest_framework.test import APIClient

User = get_user_model()

CONTENT_TYPE_JSON = 'application/json'


def create_user(username, first_name='Admin', last_name='Root', email=None, *, is_active=True,
                documento_identidad='24262155'):
    user, created = User.objects.get_or_create(
        username=username,
        documento_identidad=documento_identidad,
        email='{}@root.com'.format(username) if email is None else email,
        defaults=dict(
            first_name=first_name,
            last_name=last_name,
            password='password',
            is_active=is_active
        )
    )

    return user


def crear_grupo_administrador():
    grupo, _ = Group.objects.get_or_create(name='administrador')

    PERMISSIONS = {
        'auth': {
            'group': ['add', 'change', 'view', 'delete']
        },
        'organismo': {
            'organismo': ['add', 'change', 'view', 'delete'],
        },
        'usuario': {
            'usuario': ['add', 'change', 'view', 'delete'],
        }
    }
    agregar_varios_permisos_grupo(PERMISSIONS, grupo)
    return grupo


def agregar_permisos_grupo(permisos_por_modelo, grupo, app):
    # Loop models in group
    for model_name in permisos_por_modelo:
        # Loop permissions in group/model
        model_ct = ContentType.objects.get(app_label=app, model=model_name)
        for perm_name in permisos_por_modelo[model_name]:
            # Generate permission name as Django would generate it
            codename = perm_name + "_" + model_name
            name = "Can " + perm_name + " " + model_name
            permission, _ = Permission.objects.get_or_create(codename=codename,
                                                             content_type=model_ct,
                                                             defaults={'name': name})
            grupo.permissions.add(permission)


def agregar_varios_permisos_grupo(permisos_por_app, grupo):
    # iterar sobre nombres de apps
    for nombre_app in permisos_por_app:
        agregar_permisos_grupo(permisos_por_app[nombre_app], grupo, nombre_app)


@pytest.fixture
def get_default_test_user():
    test_user = create_user(username='test_user', first_name='Test', last_name='User', email='test@user', documento_identidad='12345678')
    return test_user


@pytest.fixture
def crear_usuarios():
    usuario1 = create_user(username='usuario1', first_name='Usuario', last_name='J',
                           email='test@user1', documento_identidad='12345777')

    usuario2 = create_user(username='usuario2', first_name='Usuario', last_name='S',
                           email='test@user2', documento_identidad='12345679')

    usuario3 = create_user(username='usuario3', first_name='Usuario', last_name='P',
                           email='test@user3', documento_identidad='12345699')

    return usuario1, usuario2, usuario3


def get_client_application():
    Application = get_application_model()
    application, _ = Application.objects.get_or_create(
        name='TestApp',
        client_type=Application.CLIENT_CONFIDENTIAL,
        authorization_grant_type=Application.GRANT_CLIENT_CREDENTIALS,
        skip_authorization=True
    )

    return application


def client_authorized():
    app = get_client_application()
    client = APIClient()
    r = client.post('/oauth2/token/', {
        'grant_type': 'client_credentials',
        'client_id': app.client_id,
        'client_secret': app.client_secret
    })
    response = json.loads(r.content)
    client = APIClient()
    client.credentials(HTTP_AUTHORIZATION='Bearer ' + response['access_token'])
    return client