Google App Engine Datastore - Testing Queries fails

后端 未结 3 1139
终归单人心
终归单人心 2020-12-11 07:42

I am currently trying to test a piece of my code that runs a query on the datastore before putting in a new entity to ensure that duplicates are not created. The code I wrot

3条回答
  •  南笙
    南笙 (楼主)
    2020-12-11 08:45

    There is nothing wrong with your test code. The issue lies in the Datastore itself. Most queries in the HR Datastore are not "immediately consistent" but eventually consistent. You can read more about this in the Datastore documentation.

    So basically what happens is that you put an entity into the Datastore, and the SDK's Datastore "simulates" the latency that you can observe in production, so if you run a query right after that (which is not an ancestor query), the query result will not include the new entity you just saved.

    If you put a few seconds sleep between the datastore.Put() and q.GetAll(), you will see the test passes. Try it. In my test it was enough to sleep just 100ms, and the test always passed. But when writing tests for such cases, use the StronglyConsistentDatastore: true option as can be seen in JonhGB's answer.

    You would also see the test pass without sleep if you'd use Ancestor queries because they are strongly consistent.

提交回复
热议问题