简体   繁体   English

django-rest-framework APITestCase + assert等于时间戳

[英]django-rest-framework APITestCase + assertEqual of timestamp

I have an "auto_now_add" timestamp in my model, as such: 我的模型中有一个“ auto_now_add”时间戳,例如:

created_on = models.DateTimeField(auto_now_add = True)

I developed a REST API with the wonderful DRF3.0, and in my unit tests I would like to have something like: 我使用出色的DRF3.0开发了REST API,并且在我的单元测试中,我希望具有以下内容:

self.assertEqual(response.data, data)

My question is simple: how can I know in advance the value of this timestamp, so that I can test it (assertEqual) with the actual value? 我的问题很简单:我如何提前知道此时间戳的值,以便可以使用实际值对其进行测试(assertEqual)?

What are you expecting to test with that? 您希望对此进行测试吗? That Django sets created_on correctly? Django正确设置了created_on吗? That's a job for Django's tests. 这是Django测试的工作。 You should test your own code. 您应该测试自己的代码。

For unit test you should test only your methods without even saving your models. 对于单元测试,您应该只测试方法,甚至不保存模型。 That's much faster and generally sufficient. 这样快得多,通常就足够了。 You need save model and check saved data only when you check queries, as it's hard to test without saving. 您仅需要在检查查询时才需要保存模型并检查保存的数据,因为不保存就很难测试。

The other use case when you need to save data to database is when you do functional/integration testing. 您需要将数据保存到数据库的另一个用例是进行功能/集成测试。 But then you'll probably won't test single fields but the overall effect. 但是,您可能将不会测试单个字段,而是测试整体效果。

Saying that if you really what to set exact value you can try mocking it directly in Django code (which I'm afraid will bring you problems quickly): 说的是,如果您确实要设置确切的值,则可以尝试直接在Django代码中对其进行模拟(恐怕会很快给您带来问题):

from mock import patch

with patch('django.db.models.fields.datetime') as datetime:
  datetime.date.today.return_value = fixed_date
  # your testing code

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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