AssertionError: PermissionDenied не поднят
Я новичок в тестировании в 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 в базу данных, основываясь на группе пользователя. Итак, в тестовой части я начал с теста для неаутентифицированного пользователя, код приведен ниже
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)
Если у кого-нибудь есть идеи, как исправить эту ошибку, буду очень признателен :)
все детали описаны выше.