pyprism
pyprism

Reputation: 3008

Unit testing Django timezone aware datetime

I tried to compare DRF response and input value.

class ViewTest(TransactionTestCase):
    reset_sequences = True
    current_date_time = timezone.now()

    def setUp(self):
        self.client = APIClient()
        self.user = User.objects.create_user('hiren', '[email protected]', 'password')
        self.client.force_authenticate(user=self.user)
        self.tag = Tag.objects.create(name="Test tag")
        Notes.objects.create(tag=self.tag, content="test content", date=self.current_date_time)

    def test_return_correct_note(self):
        response = self.client.get('/api/notes/1/')
        self.assertEqual(response.json(), {'content': 'test content', 'id': 1,
                                           'tag': 1, 'date': self.current_date_time})

Then I got this error :

AssertionError: {'date': '2016-04-09T07:35:28.039393Z', 'co[37 chars]': 1} != {'tag': 1, 'content': 'test content', 'id':[69 chars]TC>)}
  {'content': 'test content',
-  'date': '2016-04-09T07:35:28.039393Z',
+  'date': datetime.datetime(2016, 4, 9, 7, 35, 28, 39393, tzinfo=<UTC>),
   'id': 1,
   'tag': 1}

What is the correct way to compare django datetime ?

Upvotes: 4

Views: 1976

Answers (2)

JPG
JPG

Reputation: 88509

You can make use of the to_representation(...) method of the DateTimeField class as

from django.test import TransactionTestCase


class ViewTest(TransactionTestCase):
    reset_sequences = True
    current_date_time = timezone.now()

    def setUp(self):
        self.client = APIClient()
        self.user = User.objects.create_user("hiren", "[email protected]", "password")
        self.client.force_authenticate(user=self.user)
        self.tag = Tag.objects.create(name="Test tag")
        Notes.objects.create(
            tag=self.tag, content="test content", date=self.current_date_time
        )

    def test_return_correct_note(self):
        from rest_framework.fields import DateTimeField
        response = self.client.get("/api/notes/1/")
        self.assertEqual(
            response.json(),
            {
                "content": "test content",
                "id": 1,
                "tag": 1,
                "date": DateTimeField().to_representation(self.current_date_time),
            },
        )

Upvotes: 0

C14L
C14L

Reputation: 12558

You could either convert the Python datetime object into a ISO time string, or parse the ISO time string into a python datetime object.

For example

...
'tag': 1, 'date': self.current_date_time.strftime('%Y-%m-%dT%H:%M:%S.%fZ')})

Upvotes: 6

Related Questions