单元测试Django时区感知日期时间

时间:2016-04-09 07:46:05

标签: python django datetime django-unittest

我尝试比较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的正确方法是什么?

2 个答案:

答案 0 :(得分:4)

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

例如

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

答案 1 :(得分:0)

您可以将 var animation // just declare it for now, assign below // The following function will load the animation to the specified container function setAnimation (containerId) { console.log ("Loading animation into " + containerId) animation = bodymovin.loadAnimation({ container: document.getElementById(containerId), renderer: 'svg', loop: false, autoplay: false, path: "https://assets10.lottiefiles.com/packages/lf20_rd4wrn81.json" }); } // Load it in 'anim1' first setAnimation ('anim1') function playanim() { animation.goToAndPlay(0); } $('div').on('click', function() { var id = $(this).attr('id') console.log(id + ' was just clicked'); $('#text').text(id + ' was just clicked'); setAnimation (id); // re-initialize the animation animation.addEventListener('data_ready',playanim); }) 类的 to_representation(...) 方法用作

DateTimeField