如何在测试中清除/使 NDB 缓存无效 [英] How to Clear/Invalidate NDB Cache in Tests

查看:27
本文介绍了如何在测试中清除/使 NDB 缓存无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有实例属性的简单 NDB 模型,它是不是 NDB 属性.我想测试当实体被保存并从数据存储中检索时属性值是否丢失.

I have a simple NDB Model with an instance attribute, which is not an NDB property. I want to test that the property value gets lost when the entity is saved and retrieved from the datastore.

现在检索实体时,它与已放入数据存储的实例相同.

Now when the entity is retrieved it is the same instance as the one that has been put to the datastore.

有没有办法以编程方式清除/无效memcacheNDB 内存缓存?

Is there a way to programatically clear/invalidate the memcache and the NDB in-memory cache?

示例是 pytest 测试,抱歉.

The example is a pytest test, sorry for that.

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

推荐答案

解决方案是使用 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

这篇关于如何在测试中清除/使 NDB 缓存无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆