lapinkoira
lapinkoira

Reputation: 8978

Django REST test ignores factory's url

I have a weird error writing a APITestCase for a Django REST view.

This is my code:

class CreateUserTest(APITestCase):
    def setup(self):
        self.superuser = User.objects.create_superuser('[email protected]', '1989-10-06', 'vishnupassword')
        self.client.login(username='vishnu', password='vishnupassword')
        self.data = a bunch of trivial data

    def test_can_create_user(self):
        print "create user"
        self.setup()
        self.token = Token.objects.get(user_id=self.superuser.id)
        self.api_key = settings.API_KEY
        self.factory = APIRequestFactory()
        self.request = self.factory.post('/api/v1/uaaaaaasers/?api_key=%s' % self.api_key,
                                    self.data,
                                    HTTP_AUTHORIZATION='Token {}'.format(self.token))
        force_authenticate(self.request, user=self.superuser)
        self.view = UserList.as_view()
        self.response = self.view(self.request)
        self.response.render()
        #print self.response.content
        self.assertEqual(self.response.status_code, status.HTTP_201_CREATED)

As you see I run a factory.post to an intentionally wrong url /api/v1/uaaaaaasers/

But the test doesnt complain:

Creating test database for alias 'default'... 
create user .
---------------------------------------------------------------------- 

Ran 1 test in 0.199s

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

Shouldnt it crash with that wrong url? How do I know the test is going fine?

Upvotes: 0

Views: 333

Answers (2)

Vikalp Jain
Vikalp Jain

Reputation: 1419

You are testing it all wrong... The response that you have tested is from the direct view call...

self.view = UserList.as_view()
self.response = self.view(self.request)
self.response.render()
    #print self.response.content
self.assertEqual(self.response.status_code, status.HTTP_201_CREATED)

your above case will always call the view...

In actual testcases we hit the urls with the client and test that response

self.response = self.client.post('/api/v1/uaaaaaasers/?api_key=%s' % self.api_key,
                                self.data,
                                HTTP_AUTHORIZATION='Token {}'.format(self.token))
self.assertEqual(self.response.status_code, status.HTTP_201_CREATED)

Upvotes: 1

Alasdair
Alasdair

Reputation: 308769

If you want to test posting a request to an invalid url, use the test client instead of the request factory.

class CreateUserTest(APITestCase):

    def test_can_create_user(self):
       ...
       response = self.client.post(
           '/api/v1/uaaaaaasers/?api_key=%s' % self.api_key,
           self.data,
           ...
       )
       ...

Upvotes: 1

Related Questions