如何使用数据测试Django中的get请求?

时间:2017-09-21 08:42:09

标签: python django httpclient django-testing django-unittest

我现在正在为Django中的Web应用程序编写测试。我有一个网址127.0.0.1/home/device/(?P<item>[^/]+)。我正在测试无效的URL路径。 这里item是数据库中的设备名称。考虑一个无效的设备,在测试时我给出了以下代码:

response=self.client.get("/health/errorfiles/",{'item':'testdevice_R'})

这给了我404回复。我尝试过同样的事情:

response=self.client.get("/health/errorfiles/testdevice_R/")

但是这一次,测试运行器执行我的视图函数并给出一个TypeError,因为它不是一个无效的设备。

在这两种方法中,哪一种方法正确用于获取请求?

views.py

def showfiles(request,item):

if request.user.is_anonymous():                                                             ## check if the user is valid
    return HttpResponseRedirect("/")

db = MySQLdb.connect(host='localhost',user=root,passwd='123mcvis',db='test_db')

s = db.cursor()                                                                      
username=request.user                                                                     
s.execute("Select tzone,type from device where user='%s' and device='%s'"%(username,item)                     
tz=s.fetchone()
timezone.activate(tz[0])
s.close()
return render(request,"Home/showdevices.html")

这是我的查看功能,由于设备无效,因此显示典型错误。

class showfile_test(TestCase):
     def test_invalid(self):

           response=self.client.get("/health/errorfiles/testdevice_R/")
           self.assertEqual(response.status_code,404)

回溯

   ERROR: test_invalid (HealthApp.tests2.showfile_test)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/vishnumc/vishnu/project/django/official/version6.2.3/HealthApp/tests2.py", line 162, in test_showfiles_with_invalid_deviceid
    response=self.client.get("/health/errorfiles/invaliddevice/")
  File "/home/vishnumc/vishnu/project/env/local/lib/python2.7/site-packages/django/test/client.py", line 529, in get
    **extra)
  File "/home/vishnumc/vishnu/project/env/local/lib/python2.7/site-packages/django/test/client.py", line 333, in get
    return self.generic('GET', path, secure=secure, **r)
  File "/home/vishnumc/vishnu/project/env/local/lib/python2.7/site-packages/django/test/client.py", line 409, in generic
    return self.request(**r)
  File "/home/vishnumc/vishnu/project/env/local/lib/python2.7/site-packages/django/test/client.py", line 494, in request
    six.reraise(*exc_info)
  File "/home/vishnumc/vishnu/project/env/local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 39, in inner
    response = get_response(request)
  File "/home/vishnumc/vishnu/project/env/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response
    response = self._get_response(request)
  File "/home/vishnumc/vishnu/project/env/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/vishnumc/vishnu/project/env/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/vishnumc/vishnu/project/django/official/version6.2.3/HealthApp/views.py", line 118, in showfiles
    timezone.activate(tz[0])                                                                        ##setting current timezone to user's time zone for display timestamps
TypeError: 'NoneType' object has no attribute '__getitem__'

1 个答案:

答案 0 :(得分:1)

第一个例子是对/health/errorfiles/?item=testdevice_R的GET请求。在视图中,您会在item中找到request.GET

第二个例子是对/health/errorfiles/testdevice_R/的GET请求。 request.GET中没有数据,Django会将item传递给您的视图,因为您的网址格式中有一个命名组(?P<item>[^/]+)

您应该使用第二个版本,因为您要测试网址格式r'/home/device/(?P<item>[^/]+)'

您的测试的第二个版本在您的视图中发现了问题。您需要修复视图,以便它不会引发TypeError

理想情况下,您不应该像这样编写原始SQL。 Django允许您执行以下操作:

from .models import Device

from django.shortcuts import get_object_or_404, render

def showhome(request, item):
    device = get_object_or_404(Device, user=request.user, item=item)
    if device is not None:
        timezone.activate(device.tzone)
    return render(request,"Home/showdevices.html", {'device': device})

如果必须使用原始SQL,则不要使用字符串替换%(username,item)。您当前的代码会向您显示SQL注入帐户。你应该把它改成:

s.execute("Select tzone,type from device where user=%s" and device=%s, (username, item))

然后,您的代码已处理tzNone的情况,以避免TypeError

tz = s.fetchone()
if tz is not None:
    timezone.activate(tz[0])
else:
    # Decide what to do if no items returned