I can't create tests that involve authorization groups

Salutations,

I've been creating tests for testing web

I've been looking all over the internet to find the solution.

I've been building a fixture for a group that allows users to create blog posts. It's a series of test I've been building for the sake of authorization purposes. I've using both Pytest fixtures and factories with similar results.

Here's the Test Class:

import pytest
import factory
from django.contrib.auth import get_user_model
from posts.models import Post
from members.models import Member
from factories import MemberFactory, PostFactory
from faker import Faker
from django.contrib.auth.models import Group

# Create your tests here.
User = get_user_model()
fake = Faker()





#Fixture
@pytest.fixture(scope="session")
def contributor_group(db):
    return Group.objects.create("Contributor")



@pytest.fixture(scope="session")
def authorized_user(db):
    authorized_user = MemberFactory()
    return authorized_user


 

# Post Tests
class TestPosts:
#Disallows user to create a post if they're not a contributor
    @pytest.mark.django_db
    def test_is_not_contributor(db):
        reg = MemberFactory()
        
        assert reg.has_post_permissions() is False
#Allows a user to create a post if they're a contributor.     
    @pytest.mark.django_db
    def test_can_post(db):
        contributor_group.
        print(authorized_user)
        
        print(contributor_group)
        print(authorized_user.has_post_permissions())
        assert authorized_user.has_post_permissions() is True

I've also created Factories for both of them.

import factory
from faker import Faker
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth import get_user_model
from posts.models import Post
from members.models import Member
fake = Faker()
User = get_user_model()

class MemberFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = User
        

    username = factory.Faker('user_name')
    email = factory.Faker('email')
    password = 'password'
    is_active = True
    is_superuser = False
    
    @classmethod
    def has_post_permissions(self):
        self.has_post_permissions()

    


class PostFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Post

    title = fake.text(150)
    author = factory.SubFactory(MemberFactory)
    content = fake.text()

I've created the "Contributor" Group using the development Admin page. I can't seem to understand why the groups are registering the groups and user classes. I've even tried to created the MemberFactory, but I ended with the same result. I would like to know how I can integrate authorization Groups into my tests. I can't seem to figure it out.

Thanks in advance.

You should be testing the permission by creating the object to completely test the functionality of you view also, here is something that you can improve upon:

test_permissions.py

import pytest

from myapp.models import Post

from django.urls import reverse
from django.test import Client
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType

User = get_user_model()


@pytest.mark.django_db
class TestPermissions:

    def test_post_add_contributor_group_permission(db):
        client = Client()

        user = User.objects.create_user(
            username="testuser",
            email="test@example.com",
            password="pass123"
        )

        post_data = {
            "title": "Post Title",
            "content": "post content",
            "author": user.id
        }

        group = Group.objects.create(name="Contributor")
        client.login(username="testuser", password="pass123")

        # Send request without permission
        response = client.post(reverse("post-add"), post_data)
        assert response.status_code == 200
        assert Post.objects.all().count() == 0

        # Add permission to group, group to user and resend request
        content_type = ContentType.objects.get_for_model(Post)
        permission = Permission.objects.get(
            content_type=content_type,
            codename__icontains="add"
        )
        group.permissions.add(permission)
        user.groups.add(group)

        response = client.post(reverse("post-add"), post_data)

        assert response.status_code == 200
        assert Post.objects.all().count() == 1

views.py

def create_post(request):
    if request.method == "POST":
        title = request.POST.get("title")
        content = request.POST.get("content")
        user_id = request.POST.get("author")

        if request.user.has_perm("myapp.add_post"):
            Post.objects.create(
                title=title,
                content=content,
                author=User.objects.get(pk=user_id)
            )
        else:
            pass

    return render(request, "post_create.html")

Back to Top