我有一个带有实例属性的简单NDB模型,它不是NDB property。我想测试在从数据存储区保存和检索实体时属性值是否丢失。
现在,当检索实体时,它与放入数据存储区的实例相同。
有没有办法以编程方式清除/无效 memcache和 NDB内存缓存?
示例是pytest测试,对不起。
from google.appengine.ext import testbed, ndb
class User(ndb.Model):
name = ndb.TextProperty()
foo = None
class TestNDBModel(object):
def setup(self):
self.testbed = testbed.Testbed()
self.testbed.activate()
self.testbed.init_datastore_v3_stub()
self.testbed.init_memcache_stub()
def teardown(self):
self.testbed.deactivate()
def test_foo(self):
user = User(name='Andy')
assert user.name == 'Andy'
assert user.foo is None
user.foo = 123
assert user.foo == 123
user_key = user.put()
# Here I need to clear the cache somehow,
# so that the entity must be retrieved from datastore
retrieved_user = user_key.get()
# These two will now fail
assert retrieved_user is not user
assert retrieved_user.foo is None
答案 0 :(得分:1)
您显然使用错误的方法为retrieved_user
分配值。请改用以下内容:
retrieved_user = user_key.delete(use_datastore=False)
有关详细信息,请参阅以下链接:
https://developers.google.com/appengine/docs/python/ndb/functions#context_options
答案 1 :(得分:1)
解决方案是防止实体在使用entity.put(use_cache=False, use_memcache=False)
放入数据库时进行缓存。
from google.appengine.ext import testbed, ndb
class User(ndb.Model):
name = ndb.TextProperty()
foo = None
class TestNDBModel(object):
def setup(self):
self.testbed = testbed.Testbed()
self.testbed.activate()
self.testbed.init_datastore_v3_stub()
self.testbed.init_memcache_stub()
def teardown(self):
self.testbed.deactivate()
def test_foo(self):
user = User(name='Andy')
assert user.name == 'Andy'
assert user.foo is None
user.foo = 123
assert user.foo == 123
# This prevents the entity to be cached
user_key = user.put(use_cache=False, use_memcache=False)
# The entity is now retrieved from DB
retrieved_user = user_key.get()
# These two will now pass
assert retrieved_user is not user
assert retrieved_user.foo is None
答案 2 :(得分:1)
我遇到了同样的问题,正在寻找解决方案。这就是诀窍:
ndb.get_context().clear_cache()