简体   繁体   中英

Testing Django View Functions

I am currently trying to create unittests for the functions that I have written inside views.py. However, I have not been able to find the proper way to do so. Here is what I have so far for example:

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

and I am attempting to test it like so:

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')

However this returns an AttributeError stating: AttributeError: 'SalesListView' object has no attribute 'request'

Would anybody have any suggestions on the correct way to test view functions such as the one above? Thank you ahead of time.

From Django doc:

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

for more details: https://docs.djangoproject.com/en/3.0/topics/testing/tools/

I found the solution that I was looking for by using the RequestFactory library.

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))

The request requires the path to your template. Hopefully this helps, should you encounter the same problem that I did.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM