从请求对象中检索标头时Django测试KeyError

时间:2014-08-15 21:32:09

标签: python django testcase

所以我试图在测试期间确认给定视图的位置。文档说:

  

您还可以在响应对象上使用字典语法来查询   HTTP标头中任何设置的值。例如,你可以   使用确定响应的内容类型   响应[ '内容 - 类型']。

然而,当我使用它时,我收到了一个关键错误。请帮助。

测试:

def test_normal_rewardstore_usage(self):    
    logged_in = self.client.login(username=self.u1.username, password="psst")
    response = self.client.get(reverse('rewards:rewardstore'))
    location = "http://testserver%s" % (reverse('rewards:rewardpage', kwargs={'company':self.r1.company.slug, 'slug':self.r1.slug}))
    self.assertEqual(response.status_code, 200)
    self.assertEqual(response['Location'], location)

错误:

Traceback (most recent call last):
  File "/app/rewards/tests/test_views.py", line 58, in test_normal_rewardstore_usage
    self.assertEqual(response['Location'], location)
  File "/app/.heroku/python/lib/python2.7/site-packages/django/http/response.py", line 189, in __getitem__
    return self._headers[header.lower()][1]
KeyError: 'location'

查看:

def RewardStore_Index(request, template='rewards/reward-store.html', page_template='rewards/rewards_page.html'):
    user = User.objects.get(pk=request.user.pk)
    contact = Contact.objects.get(user__pk=request.user.pk, is_active=True)
    if request.user.is_authenticated():
    a = Member.objects.get(pk=request.user.pk)
    a = a.account_verified
    rewards = Reward.objects.filter(country__iso=contact.get_country)
    else:
    a = False
    g = GeoIP()
    c = g.country(request.user)
    c = c['country_code']
    rewards = Reward.objects.filter(country__iso=c)
    context = {
    'targetuser': request.user,
        'rewards': rewards,
        'page_template': page_template,
        'email_authenticated': True if a else False,
    'notifications': NotificationMap.objects.filter(user__pk=request.user.pk, read=False).prefetch_related('notification', 'notification__users')
    }
    if request.is_ajax():
        template = page_template
    return render_to_response(
        template, context, context_instance=RequestContext(request))

1 个答案:

答案 0 :(得分:0)

响应对象中提供的标题会因使用的服务器(source)而异,所以如果django测试运行器没有发回所有标题,我不会感到惊讶你在生产中看到的。此外,位置通常用于重定向响应,并且您声明您首先收到200。在这种情况下,你确定你应该期待一个Location头吗?