I am trying to test that my custom permissions in DRF work properly, so I need to imitate some requests made by users with different rights (the rights are stored as attributes in the db in a table linked to the default User table).
I am using RequestFactory for setting the request user, but it doesn't seem to work properly, as it still sees the request user as AnonymousUser, and returns AttributeError when checking the permission.
Here's an example of my testcase:
class TestSingleClient(TestCase):
def setUp(self):
self.factory = RequestFactory()
self.user = User.objects.create(
username='admin',
password='admin',
first_name='Name',
last_name='Surname',
email='[email protected]',
is_staff=True
)
AccountProfile.objects.create(
phone='8999999999',
occupation='tst_occupation',
user=self.user
)
Client.objects.create(
name='Client1',
type=0)
def test_get_single_client(self):
client = Client.objects.get(name='Client1')
request = self.factory.get('/system/clients/{}/'.format(client.id))
request.user = self.user
response = ClientView.as_view()(request, id=client.id)
client_data = Client.objects.get(id=client.id)
serializer = ClientSerializer(client_data)
self.assertEqual(response.data, serializer.data)
self.assertEqual(response.status_code, status.HTTP_200_OK)
which results in:
File "***/core/extra.py", line 10, in my_permissions_func
roles = AccessRoles.objects.filter(user_groups=user.user_profile.group_id, can_read=True).\
AttributeError: 'AnonymousUser' object has no attribute 'user_profile'
Any suggestions for fixing that?
P.S. A similar topic was discussed here: Django RequestFactory doesn't store a User, which didn't bring me any closer to the answer.