Unit tests when using a User model

348 views
Skip to first unread message

FoxMaSk

unread,
Apr 29, 2017, 4:32:46 PM4/29/17
to Django REST framework
Hi,

As I'm totally new with DRF, and just started my first project with it, I dont see from which side I can take the code to make my unit tests.


And if I start from the beginning with 

  • APIRequestFactory, 
    • with "Creating test requests", as I my model own a FK with the User model, I dont know how I can use this example
    • with "Forcing authentication", the example says to use "user = User.objects.get(username='olivia')" but how do we create the user first of all ? Or do I need to care about it and the test does not need to care about the existence of the data in the User model ?
  • APIClient
    • with "Making Request", the request is done but what when we have to connect a user first to then only get the data of that user, how do we do ?
I feel stuck until I dont have this clarifications. 
Can someone explain me what I'm missing ?

in case you need to see, my code is there https://github.com/orotangi/orotangi/tree/master/orotangi/api

Thanks 

Regards.

Tom Christie

unread,
May 1, 2017, 1:17:49 PM5/1/17
to Django REST framework
Use APIclient, and use .autuenticate(user)

Fox MaSk

unread,
May 1, 2017, 5:12:56 PM5/1/17
to django-res...@googlegroups.com
Hi Tom,

thanks for your reply

When using http://www.django-rest-framework.org/api-guide/testing/#apiclient with force_authenticated() now I got :

  File "/home/foxmask/DjangoVirtualEnv/orotangi/orotangi/orotangi/api/test.py", line 48, in test_create_book
    self.assertEqual(response.status_code, status.HTTP_201_CREATED)
AssertionError: 403 != 201

test.py looks like this 
def test_create_book(self):
"""
Ensure we can create a new book object.
"""

data = {'name': 'Book1',
'user': self.user.username}

response = self.client.post('/api/orotangi/books/', data, format='json')

self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(Books.objects.count(), 1)
self.assertEqual(Books.objects.get().name, 'Book1')

line 48 is the 1rst assertEqual()

I noticed that the 403 error is related to this settings


REST_FRAMEWORK = {
[...]
 'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication'
),
'TEST_REQUEST_DEFAULT_FORMAT': 'json'
}

But In my setup() I wrote :


def setUp(self):
"""

:return:
"""
try:
self.user = User.objects.get(username='john')
except User.DoesNotExist:
self.user = User.objects.create_user(username='john',
email='jo...@doe.info',
password='doe')

self.client = APIClient(enforce_csrf_checks=True)
self.client.force_authenticate(user=self.user)

so I was expecting to fill the session 

What did I do wrong ?

regards.

2017-05-01 19:17 GMT+02:00 Tom Christie <christ...@gmail.com>:
Use APIclient, and use .autuenticate(user)

--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-framework+unsub...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--

Tom Christie

unread,
May 2, 2017, 6:44:10 AM5/2/17
to Django REST framework
Not sure, but start by removing the "enforce_csrf_checks=True" from your test case.
That's almost certainly not what you want.

FoxMaSk

unread,
May 2, 2017, 9:04:25 AM5/2/17
to Django REST framework
Hi,
I could investigate deeper and find the the cause is due to the settings DjangoModelPermissions
When the user is created, no permissions are set for him.

If I comment this settings that gives :

----------------------------------------------------------------------
Ran 1 test in 0.071s

OK
Destroying test database for alias 'default'...

How do I set permissions to the user that will fit the DjangoModelPermissions requirements ??

Regards

Fox MaSk

unread,
May 3, 2017, 4:06:03 AM5/3/17
to django-res...@googlegroups.com
So to finish that topic, as I set REST_FRAMEWORK that way in my settings

REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
'rest_framework.permissions.DjangoModelPermissions'
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication'
),
'TEST_REQUEST_DEFAULT_FORMAT': 'json'
}

I made a permissions.py that overwrite the properties perms_map of DjangoModelPermissions

Now everything is ok when the test try to create object with a connected user.

This, This look like this 


class OrotangiTests(APITestCase):

    def setUp(self):
        self.user = User.objects.create_user(username='john',
                                             email='jo...@doe.info',
                                             password='doe')

        self.client = APIClient()
        self.client.force_authenticate(user=self.user)


class BooksTests(OrotangiTests):

    def test_get_books(self):
        """
        Ensure we can get the books list.
        """
        url = reverse('books-list')
        response = self.client.get(url, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_create_book(self):
        """
        Ensure we can create a new book object.
        """

        data = {'name': 'Book1',
                'user': self.user.username}

        url = reverse('books-list')
        response = self.client.post(url, data, format='json')

        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(Books.objects.count(), 1)
        self.assertEqual(Books.objects.get().name, 'Book1')



Regards


--
Reply all
Reply to author
Forward
0 new messages