【问题标题】:Unit testing Django timezone aware datetime单元测试 Django 时区感知日期时间
【发布时间】:2016-04-09 07:46:05
【问题描述】:

我尝试比较 DRF 响应和输入值。

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

然后我得到了这个错误:

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}

比较 django datetime 的正确方法是什么?

【问题讨论】:

    标签: python django datetime django-unittest


    【解决方案1】:

    您可以将 Python datetime 对象转换为 ISO 时间字符串,或者将 ISO 时间字符串解析为 python datetime 对象。

    例如

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

    【讨论】:

      【解决方案2】:

      您可以将 DateTimeField 类的 to_representation(...) 方法用作

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

      【讨论】:

        猜你喜欢
        • 2013-07-02
        • 1970-01-01
        • 1970-01-01
        • 2019-01-18
        • 2017-06-26
        • 1970-01-01
        • 2021-11-09
        • 2020-12-03
        • 1970-01-01
        相关资源
        最近更新 更多