I am trying to write a unit test but I am new to django and not sure how to test this function. Everything as far as I can tell is working when testing it manually but was recommended to write a unit test for it.
I have this function:
def time_encode(hours):
now = timezone.now().replace(second=0, microsecond=0)
remainder = now.minute % 15
delta = (15 - remainder)
timeFrom = now + timedelta(minutes=delta)
timeTo = timeFrom + timedelta(hours=hours)
return (timeFrom, timeTo)
That gets called in this view:
@csrf_exempt
def emulate_create(request):
args = json.loads(request.body, object_hook=utils._datetime_decoder)
resourceId, count, hours = args['resourceId'], args['count'], args['hours']
print resourceId
timeFrom, timeTo = utils.time_encode(hours)
print timeFrom
reservation = ReservationProspect(
byUser=request.user,
forUser=request.user,
resource=get_object_or_404(Resource, uuid=resourceId),
modality=get_object_or_404(Modality, name="online"),
timeFrom=timeFrom,
timeTo=timeTo,
count=count
)
return HttpResponse(
json.dumps(
[reservation.toDict()],
default=utils._datetime_encoder
)
)
I feel like I shouldn't test the stuff in the view but I should test the function time_encode for a few test cases since its purpose is to return a timeFrom on the closest 15 minute interval in the future and a timeTo that is 'hours' parameter away from timeFrom. Also it is important that the datetime is always returned with the seconds and milliseconds at zero. What would be your suggestions for how to go about testing this code?
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