I've a model called Reminder that should be secured by django-guardian. Therefore I've created a very simple test that
- creates a user
- creates a Reminder instance
- assign permissions to the created reminder instance to the created user
- check those permissions again
class ReminderPermissionsTestCase(TestCase):
def setUp(self):
content_type = ContentType.objects.get_for_model(Reminder)
add_perm = Permission.objects.create(
codename="add_reminder",
name="Can add reminder",
content_type=content_type
)
view_perm = Permission.objects.create(
codename="view_reminder",
name="Can view reminder",
content_type=content_type
)
change_perm = Permission.objects.create(
codename="change_reminder",
name="Can change reminder",
content_type=content_type
)
delete_perm = Permission.objects.create(
codename="delete_reminder",
name="Can delete reminder",
content_type=content_type
)
editor_user = get_user_model().objects.create(username="user_user")
reminder_crud = Reminder.objects.create(
open=True,
reminder_date="2023-09-03 12:00:00",
subject="Reminder with CRUD permissions",
created_by=editor_user,
reminder_text="This is a reminder with CRUD permissions."
)
def test_editor_has_crud_permissions(self):
editor_user = get_user_model().objects.get(username="editor_user")
reminder_crud = Reminder.objects.get(subject="Reminder with CRUD permissions")
assign_perm("change_reminder", editor_user, reminder_crud)
assign_perm("delete_reminder", editor_user, reminder_crud)
self.assertTrue(editor_user.has_perm("change_reminder", reminder_crud))
self.assertTrue(editor_user.has_perm("delete_reminder", reminder_crud))
unfotuantely the test fails with
File "/usr/local/lib/python3.11/site-packages/django/db/models/query.py", line 637, in get
raise self.model.DoesNotExist(
__fake__.Permission.DoesNotExist: Permission matching query does not exist
Full trace here: https://hastebin.com/share/afesunalel.scss
As you can see I've already explicitly created the permissions standard objects. Unfortunately nothing helps. The permissions table stays empty
SELECT * FROM public.auth_permission
ORDER BY id ASC
that might explain the error.
Thankful for any hint how to solve this.
I could solve my problem by raising the verbosity level
python manage.py test --verbosity 2 reminders
this showed that it is not my test code that fails but a migration when creating the test database