【问题标题】:Django - Writing Tests: Unit testing extra variables passed to generic viewsDjango - 编写测试:单元测试传递给通用视图的额外变量
【发布时间】:2015-06-08 09:21:16
【问题描述】:

我想知道是否有办法使用 Django 的测试客户端来验证从通用视图传递的额外变量是否正确。

例如,给定下面的代码,我将如何为 list_year() 编写测试以确保模板从视图接收当前年份,或为 purchase_yrs() 编写测试以确保从模型经理?

我似乎找不到从response.context 属性中提取它的方法。

class PurchaseIndex(generic.ListView):

    def get_queryset(self):
        current_date = datetime.now().year
        return Purchase.objects.filter(purchase_date__year=current_date).reverse()

    def purchase_yrs(self):
        return Purchase.purchase_years.purchase_years_list()

    def list_year(self):
        return datetime.now().year

【问题讨论】:

  • 我应该注意,我已经通过了测试:self.assertInHTML("<h1> Purchase Index - 2015 </h1>", str(response.content)),但我希望找到一种不会强迫我提交任何特定模板格式的方法。

标签: django-class-based-views django-testing


【解决方案1】:

好吧,我终于想通了。很简单:

from django.test import TestCase
from views import PurchaseIndex

class IndexPageTest(TestCase):

    def test_current_purchase_index_displays_year(self):
        context = PurchaseIndex.list_year(self)
        self.assertEqual(2015, context)

    def test_current_shipments_included_in_current_purchase_index(self):
        context = PurchaseIndex.purchase_yrs(self)
        self.assertIn(2015, context)
        self.assertIn(2014, context)

【讨论】:

    猜你喜欢
    • 2014-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-11
    • 1970-01-01
    • 2015-01-16
    • 2017-04-20
    • 1970-01-01
    相关资源
    最近更新 更多