AssertionError: PermissionDenied not raised

I'm new to testing in django , i'm trying to test a view that raises PermissonDenied when the test user is not authenticated , this is part of the view code

@login_required
def files_raw(request):
    user = request.user  # Get the current user

    # Initialize the base SQL query
    base_sql_query = ""

    # Check user conditions
    if user.is_superuser:
        # If the user is a superuser, they can access all data, so no need to change the base query.
        base_sql_query = "SELECT * FROM files"
    elif user.groups.filter(name='RNA').exists():
        # User is in the 'RNA' group, update the base query to include 'RNA'.
        base_sql_query = "SELECT * FROM files WHERE files.Sample_id LIKE '%RNA'"
    elif user.groups.filter(name='WGS').exists():
        # User is in the 'WGS' group, update the base query to exclude 'RNA'.
        base_sql_query = " SELECT * FROM files WHERE files.Sample_id NOT LIKE '%RNA'"
    else:
     # If none of the conditions are met, raise a PermissionDenied with a custom error message.
        print("DEBUG: Conditions not met for user:", user) 
        raise PermissionDenied("You are not authorized to access this data")

    # Execute the raw SQL query
    with connection.cursor() as cursor:
        cursor.execute(base_sql_query)
        # Initialize an empty list to store the results
        files = []
        
        # Iterate over the cursor to fetch one row at a time
        for row in cursor:
            # Process the row
            file_id, file_name, file_size_gb, md5, sample_value, url = row
            # You can process the row data here or append it to the 'files' list
            files.append({
                'file_id': file_id,
                'file_name': file_name,
                'file_size_gb': file_size_gb,
                'md5': md5,
                'sample_value': sample_value,
                'url': url
            })
            
    # Create a context dictionary with the files list and pass it to the template
    context = {'files': files}
    return render(request, 'files_list.html', context)

In which I send base_sql_query to the database based on the group of the user. So, in the test part I started with a test for an unauthenticated user , the code is down below

class FilePageTests(TestCase):
    def setUp(self):
        # Create a user without necessary permissions
        self.no_permissions_user = User.objects.create_user(username='no_permissions_user', password='password')

        # Create a group (e.g., 'NoPermissionsGroup')
        self.no_permissions_group = Group.objects.create(name='NoPermissionsGroup')

        # Add the user to the group
        self.no_permissions_user.groups.add(self.no_permissions_group)

    def test_unauthenticated_access(self):
        # Log in with the user without permissions
        self.client.login(username='no_permissions_user', password='password')

        # Print user information for debugging
        print("DEBUG: User groups:", self.no_permissions_user.groups.all())

        # Test that accessing the URL raises a PermissionDenied with a custom error message
        with self.assertRaises(PermissionDenied):
            response = self.client.get("/file/")
            self.assertEqual(response.status_code, 403)

So, basically i can't see why the test would raise the following error

AssertionError: PermissionDenied not raised

the origin of the error is the last line of the test which is

self.assertEqual(response.status_code, 403)

If anyone has any idea how to fix this error it would be much appreciated :)

all details are described above.

Back to Top