vendredi 8 juillet 2016

Django 1.9 testing timezone.now()

TL;DR: Get only current date and current hour and current minute from timezone.now() and not seconds and miliseconds.

Django version: 1.9 Python version: 3.5.1

While testing my app's model, I encountered a strange (to me) error.

I have this model:

import datetime

from django.core.urlresolvers   import reverse
from django.utils               import timezone
from django.db                  import models

class Muayene(models.Model):
    ...
    muayene_tarihi = models.DateField(
        default = timezone.now
    )
    ...

and this unit test:

import datetime

from django.test                    import TestCase
from django.utils                   import timezone

from hasta.models                   import Hasta
from muayene.models                 import Muayene

class MuayeneModelTest(TestCase):

    fixtures = ['muayene_testdata', 'hasta_testdata']

    def setUp(self):
        Hasta.objects.create(ad="foo",soyad="bar",tc_kimlik_no="1234")
    def test_default_muayene_tarihi(self):
        hasta = Hasta.objects.get(ad="foo")
        muayene = Muayene.objects.create(hasta=hasta)
        self.assertEqual(muayene.muayene_tarihi, timezone.now())

Output of test:

FAIL: test_default_muayene_tarihi (muayene.tests.test_models.MuayeneModelTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/egegunes/Dropbox/Programs/hastatakip/muayene/tests/test_models.py", line 21, in test_default_muayene_tarihi
      self.assertEqual(muayene.muayene_tarihi, timezone.now())
      AssertionError: datetime.datetime(2016, 7, 8, 14, 38, 54, 780069, tzinfo=<UTC>) != datetime.datetime(2016, 7, 8, 14, 38, 54, 780539, tzinfo=<UTC>)

As you can notice, the problem is difference between outputs of timezone.now which called from models.py and timezone.now() which called form test_models.py.

I found this question for a workaround. But storing the exact milisecond or second is not my real intent. I want only current date and time (hour and minute). Also I don't want to set default = datetime.date.today() or something like that because django gives warnings about using only timezone.now.

So my question is, how can I get only and only current date, hour and minute with timezone.now()?

Aucun commentaire:

Enregistrer un commentaire