简体   繁体   中英

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', '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 ?

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')})

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):
        
        response = self.client.get("/api/notes/1/")
        self.assertEqual(
            response.json(),
            {
                "content": "test content",
                "id": 1,
                "tag": 1,
                ,
            },
        )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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