2015-08-14 14 views
1

我正在嘗試編寫單元測試,但我對django很陌生,不知道如何測試這個函數。據我所知,所有的東西都是在手動測試時工作,但建議爲它編寫一個單元測試。如何在Django中編寫單元測試

我有這樣的功能:

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) 

被調用在這樣的觀點:

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

我覺得我不應該測試的東西的看法,但我應該測試功能time_encode對於一些測試用例,因爲它的目的是在將來最近15分鐘的時間間隔內返回一個timeFrom,並將timeTo作爲距離timeFrom的「小時」參數。同樣重要的是,日期時間始終以秒和毫秒爲零返回。對於如何去測試這些代碼,你有什麼建議?

+0

,你應該添加一個文檔字符串解釋功能的目的。 –

回答

1

我想我會寫的功能的至少兩個單元測試(一個檢查是否爲給定的輸入時,產生預期的輸出。

然後另外我會寫視圖本身,例如做它幾個測試產生預期的輸出?是404預期時返回?

我也想在情況下,它是你的測試這個ReservationProspect類。

相當一系列測試,但我通常遵循測試驅動開發和寫入測試在可能的情況下前進,這對我的工作非常有益

...並通過他們的方式,如果你對測試的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) 

關於你提到的有關進口評論:

from utils import time_encode 

- 後上面導入您可以使用它作爲time_encode

import utils 

- 上述進口後必須在添加一個測試,用它作爲utils.time_encode

+0

是的,你有一個函數/視圖測試語法的例子嗎? – james

+0

如果你想獲得更高級的書籍,這本好書是: http://chimera.labs.oreilly.com/books/1234000000754 你可以在這裏免費試用。 – wisnia

+0

用簡單的例子編輯。記住開始測試功能與測試,沒有它,他們是相當幫助功能,將不會啓動「manage.py測試應用程序」 – wisnia

相關問題