0

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?

Hanny
  • 2,078
  • 6
  • 24
  • 52

1 Answers1

2

Follow the redirection chain til the end:

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

Reference: Test tools, Making requests

Raydel Miranda
  • 13,825
  • 3
  • 38
  • 60
  • Argh. When I do that I get a `404` returned. Bummer. If I hit the URL in a browser, I get the expected results. Perhaps it's something to do with trailing/beginning slashes in the URL. – Hanny Apr 24 '19 at 19:44
  • @Hanny I recommend you to name your URL patterns and use reverse() in order to get the desired url. Is better fot getting more robust tests. Take a look this question and you'll see what I mean: https://stackoverflow.com/questions/12818377/django-name-parameter-in-urlpatterns – Raydel Miranda Apr 24 '19 at 20:28
  • Is that what `basename` is for? When I do `reverse('MySpecificModels')` it doesn't find anything, so I suppose it isn't - but I can't find much documentation on how to properly name the route in the `router.register` line. I appreciate the link, and I think you're answer is right, so I'll mark it as such. – Hanny Apr 25 '19 at 13:03
  • As another side point to those who might stumble on this: even using `reverse('MySpecificModels-list')` per the documentation continues to give 404 error - despite finding the appropriate URL (which is listed in the URL's of the application). – Hanny Apr 25 '19 at 14:02