亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何獲取上下文來測試我的視圖頁面?

如何獲取上下文來測試我的視圖頁面?

楊__羊羊 2024-01-16 15:20:52
我正在嘗試測試我的搜索結果,以檢查沒有結果時的響應。這是我認為的功能:def get_context_data(self, *args, **kwargs):         result = super().get_context_data(**kwargs)         query = self.request.GET.get('q')         result['book'] = get_object_or_404(books,ISBN = query)         return result這是我的測試類和函數class Test_Search_results_view(TestCase):    def test_no_results(self):        response1 = self.client.get('/TextSearch/results1/?books=new&q=9780815345244')        response2 = self.client.get('/TextSearch/results2/?books=new&author=Bruce+Alberts&Book+Name=Molecular+Biology+of+the+Cell&edition=6')        self.assertEqual(response1.status_code, 404)        self.assertEqual(response2.status_code, 404)        self.assertQuerysetEqual(response2.context['book'],[])但我不斷收到此錯誤self.assertQuerysetEqual(response2.context['book'],[])  File "C:----\context.py", line 83, in __getitem__    raise KeyError(key)KeyError: 'book'如何檢查我的圖書查詢是否得到空結果?
查看完整描述

1 回答

?
PIPIONE

TA貢獻1829條經驗 獲得超9個贊

如果這一行:result['book'] = get_object_or_404(books,ISBN = query)導致404被提出,那么,你將在 中什么都沒有result['book']。因為404is 和引發的異常。get_object_or_404不返回您可以在測試中斷言的空值。



查看完整回答
反對 回復 2024-01-16
  • 1 回答
  • 0 關注
  • 144 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號