1

我已经编写了一个单元测试来测试一个 api ......它是一个 GET 调用......当我运行它时,我得到这个错误......这是回溯......

Traceback (most recent call last):
  File "/home/arindam31/XXX-Name/mapi/tests.py", line 141, in test_get_cities
    response = self.cl.get('/mapi/latest/cities/')
  File "/usr/local/lib/python2.7/dist-packages/django/test/client.py", line 445, in get
    response = super(Client, self).get(path, data=data, **extra)
  File "/usr/local/lib/python2.7/dist-packages/django/test/client.py", line 229, in get
    return self.request(**r)
  File "/usr/local/lib/python2.7/dist-packages/django/test/client.py", line 387, in request
    response = self.handler(environ)
  File "/usr/local/lib/python2.7/dist-packages/django/test/client.py", line 84, in __call__
    response = self.get_response(request)
  File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 169, in get_response
    response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
  File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 218, in handle_uncaught_exception
    return callback(request, **param_dict)
  File "/home/arindam31/XXX-Name/saul/views.py", line 546, in do_handle_500
    return render_to_response("500.html", context_instance=RequestContext(request))
  File "/usr/local/lib/python2.7/dist-packages/django/template/context.py", line 177, in __init__
    self.update(processor(request))
  File "/home/arindam31/XXX-Name/saul/context_processors.py", line 46, in common_context
    ret_dict['city'] = request.city
AttributeError: 'WSGIRequest' object has no attribute 'city'

这是我的单元测试...

def test_get_cities(self):
    request = HttpRequest()
    request.city = self.c1
    response = self.cl.get('/mapi/latest/cities/')
    content = response.content
    data = json.loads(content)
    for city in City.objects.all():
        assert city.name in data
        assert data[city.name] == city.pk

这里,self.c1是setUp部分中的城市类型对象......HttpRequest来自django.http。

正在测试的视图如下:

def get_cities(request): 
    print "1"
    if ENABLE_HTTPS_CHECK and not request.is_secure():
        return HttpResponseForbidden()
    if request.method != 'GET':
        return HttpResponseNotAllowed('Not allowed')
    city_map = _get_city_map()
    response = HttpResponse(json.dumps(city_map)
    content_type='application/json')
    response['Cache-Control'] = 'no-cache'
    return response
4

2 回答 2

0

如果你想用你自己的请求对象测试你的视图,你应该直接调用视图。您应该使用RequestFactory来创建您的请求。

正如 Daniel Roseman 指出的那样,您的请求对象具有 city 属性仍然损坏,除非您有一些可以设置它的中间件。您显然有一些中间件需要在saul/context_processors.py.

直接使用RequestFactory和调用视图完全绕过了中间件,因此您可以专注于测试您的视图(如果视图支持缺少的中间件)。

如果您的视图需要 middelware 可操作,您可能只需要使用测试客户端登录即可。它有一个会话公关测试方法。

于 2014-08-02T08:45:20.760 回答
-1

我不知道你想在这里做什么。您实例化一个请求对象,分配一个城市属性,然后继续忽略该对象并仅使用标准测试客户端。我不知道您为什么认为该请求将用于客户端获取。

老实说,虽然我认为你的整个设计都被打破了。您不会显示在正常的非测试场景中如何将参数放入请求中,但通常您会通过 POST 或 GET 参数传递它,而不是以某种方式将其注释到请求中。这当然会使测试更容易,因为您可以将字典传递给客户端调用。

于 2013-03-01T09:11:24.070 回答