Search code examples
pythondjangodjango-rest-frameworkdjango-testing

Testing API endpoint in DRF - accessing the specific url by name?


I've got a project with the following structure:

  • Project
    • app1
    • app2

Each app is using django rest framework.

My project urls.py file looks like this:

import app1.rest_api

urlpatterns = [
    path('admin/', admin.site.urls),
    path('app2/', include('app2.urls')),
    path('app1/', include('app1.urls')),
    path('api/app1/', include(
        app1.rest_api.router.urls)),

In my rest_api.py file I have the following routes setup:

router = routers.DefaultRouter()
router.register(r'myspecificmodel',
                MySpecificModelViewSet, base_name='MySpecificModels')
router.register(r'myothermodels', MyOtherModelsViewSet,
                base_name='MyOtherModels')

I have a test_api.py file in the app1/tests directory that looks like this:

from rest_framework import status
from rest_framework.test import APITestCase, APIClient


class URLTest(APITestCase):
    def setUp(self):
        self.client = APIClient()

    def test_url_returns_200(self):
        url = '/api/app1/myspecificmodels'
        response = self.client.get(url)
        # response = self.client.get(url, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(len(response.data), 1)

This gets me a 301 ResponsePermanentRedirect

How would I best go about testing that API endpoint? Is there a way to name the route and test it with reverse as that might be a little easier?


Solution

  • Follow the redirection chain til the end:

    response = self.client.get(url, follow=True)
    

    Reference: Test tools, Making requests