AssertionError:未引发 PermissionDenied

AssertionError: PermissionDenied not raised

提问人:Wael 提问时间:11/13/2023 最后编辑:Wael 更新时间:11/14/2023 访问量:47

问:

我是django测试的新手,我正在尝试测试一个在测试用户未经过身份验证时引发PermissonDenied的视图,这是视图代码的一部分

@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)

其中,我根据用户的组将base_sql_query发送到数据库。 因此,在测试部分中,我从对未经身份验证的用户进行测试开始,代码如下

from django.test import TestCase
from django.test import SimpleTestCase
from django.urls import reverse

from django.contrib.auth.models import User, Group

from django.core.exceptions import PermissionDenied


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)

所以,基本上我不明白为什么测试会引发以下错误

AssertionError: PermissionDenied not raised

错误的根源是测试的最后一行,即

self.assertEqual(response.status_code, 403)

如果有人知道如何修复此错误,将不胜感激:)

所有细节均如上所述。

Django 单元测试 测试 视图 django 模板

评论

0赞 CoffeeBasedLifeform 11/14/2023
您的调试打印输出了什么?
0赞 Wael 11/14/2023
它打印此消息DEBUG: User groups: <QuerySet [<Group: NoPermissionsGroup>]
0赞 CoffeeBasedLifeform 11/14/2023
调试打印从未到达过吗?到底够了吗?也许由于 URL 配置等其他问题,请求永远不会到达?你能用你的IDE进行调试吗(这将使这变得容易得多)?files_rawfiles_rawfiles_raw
0赞 Wael 11/14/2023
使用 vscode 进行调试时,会在 import 语句级别引发此错误django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
0赞 CoffeeBasedLifeform 11/14/2023
您是否使用 Django 的命令运行测试?docs.djangoproject.com/en/4.2/intro/tutorial05/#running-teststest

答: 暂无答案