4

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', 'a@b.com', '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 ?

pyprism
  • 2,928
  • 10
  • 46
  • 85

2 Answers2

6

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')})
C14L
  • 12,153
  • 4
  • 39
  • 52
0

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", "a@b.com", "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),
            },
        )
JPG
  • 82,442
  • 19
  • 127
  • 206