【问题标题】:Testing Django View Functions测试 Django 视图函数
【发布时间】:2020-04-24 08:10:36
【问题描述】:

我目前正在尝试为我在 views.py 中编写的函数创建单元测试。但是,我一直无法找到正确的方法来做到这一点。以下是我目前所拥有的示例:

views.py:

class SalesListView(LoginRequiredMixin, TemplateView):
    def get_month(self):
        if self.request.GET.get('month'):
            d = datetime.strptime(self.request.GET.get('month'), '%Y-%m')
        else:
            d = datetime.today()
        return d

我正在尝试像这样测试它:

tests.py:

class ViewFunctionsTests(TestCase):
    def test_saleslistview(self):
        self.request = Mock(session={'month': '2019-11'}, method='GET')
        view = SalesListView()
        self.assertEqual(view.get_month(), '2019-11')

但是这会返回一个 AttributeError 声明:AttributeError: 'SalesListView' object has no attribute 'request'

有人对测试上述视图功能的正确方法有任何建议吗?提前谢谢你。

【问题讨论】:

    标签: python django unit-testing django-views


    【解决方案1】:

    来自 Django 文档:

    from django.test import Client
    c = Client()
    response = c.post('/login/', {'username': 'john', 'password': 'smith'})
    response.status_code
    200
    response = c.get('/customer/details/')
    response.content
    

    更多详情:https://docs.djangoproject.com/en/3.0/topics/testing/tools/

    【讨论】:

      【解决方案2】:

      我通过使用 RequestFactory 库找到了我正在寻找的解决方案。

      class ViewFunctionsTests(TestCase):
          def test_saleslistview(self):
              request = RequestFactory().get('/sales/sales_dashboard/?month=2019-11')
              view = SalesListView()
              view.setup(request)
              self.assertEqual(view.get_month(), datetime.datetime(2019, 11, 1, 0, 0))
      

      请求需要模板的路径。如果您遇到与我相同的问题,希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 2021-08-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-15
        • 1970-01-01
        • 2018-11-11
        相关资源
        最近更新 更多