Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting HttpResponseNotFound in Django test get method

I am building a test case for an endpoint. Visiting the endpoint in the local development using the browser works fine — I get the expected response. However, during the test, I get an HttpResponseNotFound in which the endpoint is not found on the server.

#views.py
class ExampleView(APIView):
    permission_classes = (permissions.AllowAny,)

    def get(self, request):
        print('GOT HERE')
        qs = Example.objects.last()
        
        if self.request.user.is_authenticated:
            if self.request.user.is_subscribed:
                message = {
                    'info': 'User can download template.',
                    'template': qs.file.url
                }
                return Response(message, status.HTTP_200_OK)

        message = {
            'info': 'User cannot download template.',
            'template': None
        }
        return Response(message, status.HTTP_400_BAD_REQUEST)

In my urls.py

#urls.py
urlpatterns = [
    path('admin/', admin.site.urls),
    path('request/download_template', ExampleView.as_view()),
]

My test build

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class TestExample(APITestCase):
    fixtures = ['fixtures/initial', 'fixtures/auth', 'fixtures/example']

    def test_forecast_template_authenticated(self):
        response = self.client.get(
            '/request/download_template/')
        
        print('result', response)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

The response

<HttpResponseNotFound status_code=404, "text/html; charset=utf-8">

I am trying to debug but I do not even reach the print statement I have in my view. I have been figuring out where could be my mistake but its been hours. Why am I getting that response? Where could be my mistake?

>Solution :

In your test you are using different url:

def test_forecast_template_authenticated(self):
    response = self.client.get(
        '/request/download_template/')

Than you have set in your urls:

path('request/download_template', ExampleView.as_view()),

Notice the slash at the end.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading