【问题标题】:Django Unit Testing testing viewsDjango 单元测试测试视图
【发布时间】:2015-11-05 06:02:27
【问题描述】:

我正在使用 Django 单元测试来测试我的视图。我正在使用参数发出 getpost 请求以检查我返回的状态。

但是问题是如何检查响应中重新调整的上下文变量? 比如在View Cities页面,我做了一个get请求,视图中的context dict有变量cities。所以我想检查上下文。

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

条件是True 两种方式,如果表单无效或有效,则返回 200。如果我可以检查上下文,那么我可以检查从视图中重新调整的内容作为响应。

我尝试了什么

=> 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}}']}

检查_container 是否有该变量。表单无效,并在上下文中重新调整错误。但是当我执行以下操作时,我得到None

=> resp.context 
   None

测试

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)

查看

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))

干杯。

【问题讨论】:

    标签: python django unit-testing


    【解决方案1】:

    respdjango.test.Response 的一个实例)应该有一个context 属性。

    您可以使用context[..] 访问上下文值:

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

    【讨论】:

    • @Clayton,如果你这样做,你会得到什么? resp.context[Enums.ResponseAlert.Success]resp.context[Enums.ResponseAlert.Error]
    • resp.context 是无,所以我肯定会在这个问题上出错。我的想法更抽象?
    • 这是我得到的*** TypeError: 'NoneType' object has no attribute '__getitem__'
    • @Clayton,这个怎么样? resp.context_data
    • 有线。 *** AttributeError: 'HttpResponse' object has no attribute 'context_data'
    猜你喜欢
    • 2011-06-15
    • 2014-07-14
    • 2016-03-12
    • 1970-01-01
    • 1970-01-01
    • 2021-08-26
    • 1970-01-01
    • 2010-11-24
    • 2016-05-29
    相关资源
    最近更新 更多