Search code examples
pythondjangounit-testingdjango-viewsdjango-testing

Writing a unit test for a DJANGO view


Hi i am new in DJANGO and I have problems understanding how the unit tests should be designed for django. Please help me design a unit test case for following view.

def camera_gallery(request,gallery_id=None):
        #endpoint is url from where i get JSON data
    endpoint = settings.GALLERYAPI+'?galleryId='+ gallery_id+'&api_key=' + settings.GALLERY_API_KEY

    response = requests.get(endpoint)
    if response.status_code == 200:
        json_response = json.loads(response.content)
        context = json_response
    else:
        raise Http404
    return render(request, 'app/gallery_secondary.html',context)

Solution

  • The Django testing tutorial has sample code for verifying the 200 vs. 404 return codes as well as checking that the response contains a particular string, so you should start with that.

    Also, you might want to mock out the requests library with Mox so that you're not making actual HTTP requests to those services. This technique is known as dependency injection (see Wikipedia, SO, and Martin Fowler for more info).