我目前正在尝试为我在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: 'SalesListView' object has no attribute 'request'的AttributeError
有没有人对测试视图函数的正确方法有什么建议?提前谢谢你。
发布于 2020-01-07 04:04:01
来自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/
发布于 2020-01-08 06:08:11
通过使用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))请求需要您的模板的路径。希望这对你有帮助,如果你遇到和我一样的问题。
https://stackoverflow.com/questions/59617927
复制相似问题