[Answered ]-How to write Unit Test in Django

2πŸ‘

βœ…

I think I would write at least two unit tests for the function (one checking whether for given input, the expected output is generated.

Then additionally I would write few tests for the view itself, e.g. does it generate expected output? is 404 returned when expected?

I would also think about testing this ReservationProspect class in case it’s yours.

Quite a bunch of tests, but I usually follow test-driven development and write tests in advance when possible. It works for me really well.

… and by they way, if your question about testing Django/Python is more general – Django has some good stuff on their webpage
https://docs.djangoproject.com/en/1.8/topics/testing/overview/
and in the tutorial:
https://docs.djangoproject.com/en/1.8/intro/tutorial05/

from django.test import TestCase
class ViewTest(TestCase):

    def test_view_returns_OK(self):
        response = self.client.get('/')
        self.assertEqual(response.status_code,200)

class FunctionTest(TestCase):

    def test_function_returns_expected_result(self):
        response = time_encode(10)
        expected = "XYZ"
        self.assertEqual(response, expected)

Regarding your comment about imports:

from utils import time_encode 

– after above import you can use it as time_encode

import utils 

– after above import you have to use it as utils.time_encode

πŸ‘€wisnia

Leave a comment