A.J.
A.J.

Reputation: 8985

Django Unit Testing testing views

I am testing my views using Django Unit testing. I am making get and post requests with params to check what status i get back.

But the problem how to check for context variables which are retuned in the response? For example, on the View Cities page, I make a get request, the context dict in the view has the variable cities. So I want to check for context.

         resp = self.client.post(
                path=reverse('upload_video'),
                data={"video_url": video_url, "pro": 1}
            )
            self.assertEqual(resp.status_code, 200)

Condition is True both ways, if the form is invalid or valid it returns 200. If I can check for context, then I can check what has been retuned from the view in response.

What I tried

=> resp.__dict__
 {'templates': [], '_handler_class': None, '_headers': {'vary': ('Vary', 'Cookie'), 'content-type': ('Content-Type', 'application/json')}, '_charset': 'utf-8', '_closable_objects': [], 'cookies': <SimpleCookie: >, 'client': <django.test.client.Client object at 0x112bace10>, '_base_content_is_iter': False, 'context': None, 'request': {u'CONTENT_LENGTH': 202, u'wsgi.input': <django.test.client.FakePayload object at 0x113667990>, u'REQUEST_METHOD': 'POST', u'PATH_INFO': '/upload/video/modal/', u'CONTENT_TYPE': u'multipart/form-data; boundary=BoUnDaRyStRiNg', u'QUERY_STRING': ''}, '_container': ['{"error": {"msg": "Pro: Select a valid choice. That choice is not one of the available choices.", "head": null}}']}

Check _container has that variable. The form is invalidated, and retuned an error in the context. but when I do the following i get None

=> resp.context 
   None

Test

import os

from django.contrib.auth import authenticate

from django.core.urlresolvers import reverse

from django.test import TestCase 

def test_video_upload(self):
    """ Test that video upload is successful  """
    self.create_and_login(username="su", password="su", is_superuser=True)
    video_urls = [
        u"https://www.youtube.com/watch?v=abc",
        u"https://vimeo.com/32222",
        u"http://www.dailymotion.com/video/rer"
    ]
    for video_url in video_urls:
        resp = self.client.post(
            path=reverse('upload_video'),
            data={"video_url": video_url, "pro": 1}
        )

        set_trace() #Breakpoint
        a = resp.context[-1] # <=== Not getting it here.
        self.assertEqual(resp.status_code, 200) #passes

    videos = Video.objects.all()
    self.assertEqual(len(videos), 3)

View

ctx = {}
    if request.method == Enums.Request.POST:
        video_form = UploadVideoEasyForm(data=request.POST)
        if video_form.is_valid():
            video, log = video_form.save(request=request)
            msg = 'Successfully Uploaded, View: <a href="{}">here</a>'.format(video.get_absolute_url())
            ctx[Enums.ResponseAlert.Success] = {'msg': msg}
        else:
            ctx[Enums.ResponseAlert.Error] = make_alert(msg=form_error_to_string(video_form))
        return HttpResponse(json.dumps(ctx), content_type="application/json")

    elif request.method == Enums.Request.GET:
        ctx['upload_video'] = UploadVideoEasyForm()
        if request.user.is_authenticated() and request.user.is_superuser:
            return render_to_response('new/modals/upload_video.html', context_instance=RequestContext(request, ctx))

Cheers.

Upvotes: 3

Views: 1243

Answers (1)

falsetru
falsetru

Reputation: 368894

The resp (An instance of django.test.Response) should have an context attribute.

You can access context value using context[..]:

self.assertEqual(resp.context['cities'], ...)

Upvotes: 2

Related Questions