如何从数据存储刷新 NDB 实体?
我希望能够在测试中断言我的代码为被修改的实体调用了 Model.put()
.不幸的是,似乎有一些缓存正在进行,这样这段代码:
I'd like to be able to assert in tests that my code called Model.put()
for the entities that were modified. Unfortunately, there seems to be some caching going on, such that this code:
from google.appengine.ext import ndb
class MyModel(ndb.Model):
name = StringProperty(indexed=True)
text = StringProperty()
def update_entity(id, text):
entity = MyModel.get_by_id(id)
entity.text = text
# This is where entity.put() should happen but doesn't
通过此测试:
def test_updates_entity_in_datastore(unittest.TestCase):
name = 'Beartato'
entity = MyModel(id=12345L, name=name, text=None)
text = 'foo bar baz'
update_entity(entity.key.id(), text)
new_entity = entity.key.get() # Doesn't do anything, apparently
# new_entity = entity.query(MyModel.name == name).fetch()[0] # Same
assert new_entity.text == text
当我真的不想这样做时,因为在现实世界中,update_entity
实际上不会更改数据存储中的任何内容.
When I would really rather it didn't, since in the real world, update_entity
won't actually change anything in the datastore.
使用 Nose、datastore_v3_stub 和 memcache_stub.
Using Nose, datastore_v3_stub, and memcache_stub.
你可以像这样绕过缓存:
You can bypass the caching like this:
entity = key.get(use_cache=False, use_memcache=False)
这些选项来自 ndb 的上下文选项.它们可以应用于 Model.get_by_id()
、Model.query().fetch()
和 Model.query().get()
> 也是
These options are from ndb's context options. They can be applied to Model.get_by_id()
, Model.query().fetch()
and Model.query().get()
too