How to check DateTimeProperty in App Engine NDB?

I am trying to test a filter for DateTimeProperty with the NDB Engine Engine, but I set auto_now?

Is there any way around this for unit testing?

Example:

class MyModel(ndb.Model) timestamp = ndb.DateTimeProperty(auto_now) name = ndb.StringProperty() def testMyModelFilter(self): test1 = MyModel() test1.timestamp = datetime.datetime.now() - datetime.timedelta(hours=2) test1.put() test2 = MyModel() test2.timestamp = datetime.datetime.now() - datetime.timedelta(hours=1) test2.put() hour_ago = datetime.datetime.now() - datetime.timedelta(hours=1) fetched = MyModel.query().filter(MyModel.timestamp < hour_ago).fetch( None, keys_only=True) 

Unfortunately, when I pass it to the data store using test.put (), it uses the time it was placed ().

+6
source share
1 answer

So, one thing you can try (as pointed out by @mjibson) is overriding your model during the test. Since MyModel itself is an object, you can change the _auto_now timestamp property to False for your test. For instance:

 def testMyModelFilter(self): # Change the auto_now parameter to False MyModel.timestamp._auto_now = False # Test as usual... test1 = MyModel() test1.timestamp = datetime.datetime.now() - datetime.timedelta(hours=2) test1.put() test2 = MyModel() test2.timestamp = datetime.datetime.now() - datetime.timedelta(hours=1) test2.put() hour_ago = datetime.datetime.now() - datetime.timedelta(hours=1) fetched = MyModel.query().filter(MyModel.timestamp < hour_ago).fetch( None, keys_only=True) 

I remember this technique somewhere else, so I will contact if I find it (if it works, of course :)).

+9
source

All Articles