我已经编写了一个单元测试来测试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
答案 0 :(得分:0)
如果要使用自己的请求对象测试视图,则应直接调用视图。您应该使用RequestFactory来创建请求。
正如丹尼尔罗斯曼指出你的请求对象有一个城市属性仍然破坏,除非你有一些中间件可以设置它。您显然有一些中间件需要在saul/context_processors.py
中设置它。
使用RequestFactory
并直接调用视图会完全绕过中间件,因此您可以专注于测试视图(如果视图支持缺少的中间件)。
如果您的视图要求middelware可以运行,您可能只需要使用测试客户端登录。它有一个会话pr测试方法。
答案 1 :(得分:-1)
我不知道你在这里要做什么。您实例化一个请求对象,分配一个城市属性,然后继续忽略该对象,只使用标准测试客户端。我不知道为什么你会认为该请求将用于客户端获取。
老实说,虽然我认为你的整个设计都被打破了。您没有在正常的非测试场景中显示您希望如何将参数放入请求中,但通常您会通过POST或GET参数传递它,而不是以某种方式将其注释到请求中。这当然会使测试更容易,因为你可以将字典传递给客户端调用。