3

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

Passes this test:

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

When I would really rather it didn't, since in the real world, update_entity won't actually change anything in the datastore.

Using Nose, datastore_v3_stub, and memcache_stub.

Dan McGrath
  • 41,220
  • 11
  • 99
  • 130
brandones
  • 1,847
  • 2
  • 18
  • 36

2 Answers2

4

You can bypass the caching like this:

entity = key.get(use_cache=False, use_memcache=False)

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

snakecharmerb
  • 47,570
  • 11
  • 100
  • 153
0

Your current test validates the "local", in-memory version of your entity (independent of what's in the datastore). You should re-fetch the entity from NDB before your checks:

new_entity = entity.key.get()
assert [...]
Nabla
  • 612
  • 5
  • 8
  • Edited the question to clarify -- tried that, it doesn't change anything. – brandones Apr 04 '16 at 18:23
  • I think it might be because you are explicitly setting an ID and the stub somehow puts the entity in the cache? If you don't set the ID, the Key should be None. – Nabla Apr 04 '16 at 18:34