【问题标题】:How to override a timestamp field for unit test purposes?如何覆盖时间戳字段以进行单元测试?
【发布时间】:2013-10-23 03:13:06
【问题描述】:
class Record(ndb.Model):
    notes = ndb.TextProperty()
    last_updated = ndb.DateTimeProperty(auto_now=True)

部分单元测试设置:

record2 = Record()    
# trying to set the last_updated timestamp to a previous date
record2.last_updated = previous_date

record2.put()
#after saving it, the timestamp is back to today's date

因此,我无法为单元测试模拟旧记录。如何在不更改模型的情况下覆盖该字段?

【问题讨论】:

  • 来自文档 - It is possible to override the value for a property with auto_now_add=True, but not for one with auto_now=True. The automatic value is not generated until the entity is written; that is, these options don't provide dynamic defaults. (These details differ from the old db API.) 在设置测试时您可能不得不摆弄模型。
  • @TimHoffman 为什么不将其作为答案而不是评论?
  • 当我对它作为答案不满意时,我经常这样做:-)
  • @TimHoffman 但它实际上回答了这个问题.. 这是不可能的:)
  • 是的,我做了进一步的研究,这似乎是不可能的。我将模型更改为普通的last_updated = ndb.DateTimeProperty(required=True),这迫使我设置字段,并且我相应地更改了对代码的所有引用。这样我至少可以对它进行单元测试。蒂姆,你可以把它作为答案,我把它打勾。 ;)

标签: python google-app-engine unit-testing


【解决方案1】:

来自docs

可以用auto_now_add=True 覆盖属性的值,但不能用auto_now=True 覆盖属性值。在实体写入之前不会生成自动值;也就是说,这些选项不提供动态默认值。 (这些细节与旧的 db API 不同。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-14
    • 1970-01-01
    • 2013-07-08
    • 1970-01-01
    • 1970-01-01
    • 2016-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多