简体   繁体   English

如何在Django中编写单元测试

[英]How to write Unit Test in Django

I am trying to write a unit test but I am new to django and not sure how to test this function. 我正在尝试编写单元测试,但是我是django的新手,并且不确定如何测试此功能。 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. 我觉得我不应该在视图中测试东西,但是我应该在几个测试用例中测试time_encode函数,因为它的目的是在将来最接近的15分钟间隔返回timeFrom,而timeTo则是“ hours”参数远离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, eg does it generate expected output? 然后,另外,我将为视图本身编写一些测试,例如,它会生成预期的输出吗? is 404 returned when expected? 预期会返回404吗?

I would also think about testing this ReservationProspect class in case it's yours. 我也考虑考虑测试这个ReservationProspect类,以防它属于您。

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/ ...顺便说一下,如果您有关测试Django / Python的问题更笼统-Django的网页https://docs.djangoproject.com/en/1.8/topics/testing/overview/以及教程: 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 -在上述导入之后,您可以将其用作time_encode

import utils 

- after above import you have to use it as utils.time_encode -在上述导入之后,您必须将其用作utils.time_encode

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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