Querying Datastore Entities in Google App Engine Tests
When testing code that leverages the Datastore's query capabilities, developers may encounter failures despite functional implementations within the application. This discrepancy arises from the eventually consistent nature of most Datastore queries.
In the provided code, an entity is inserted into the Datastore using the Put() method, followed by a query to retrieve it using GetAll(). However, the query returns no results due to the latency simulation imposed by the Datastore. To resolve this, two approaches can be taken:
Example (Strongly Consistent Datastore):
import ( "context" "cloud.google.com/go/datastore" "github.com/GoogleCloudPlatform/go-cloud-testing-gce" ) func TestEntityQueryStronglyConsistent(t *testing.T) { ctx := context.Background() c, err := aetest.NewContext(ctx, aetest.Options{ StronglyConsistentDatastore: true, }) if err != nil { t.Fatal(err) } defer c.Close() key := datastore.NewIncompleteKey(c, "Entity", nil) key, err = datastore.Put(c, key, &Entity{Value: "test"}) if err != nil { t.Fatal(err) } q := datastore.NewQuery("Entity").Filter("Value =", "test") var entities []Entity keys, err := q.GetAll(c, &entities) if err != nil { t.Fatal(err) } if len(keys) == 0 { t.Error("No keys found in query") } if len(entities) == 0 { t.Error("No entities found in query") } }
By using either approach, tests can accurately reflect the behavior of queries in the production environment.
The above is the detailed content of How to Reliably Query Datastore Entities in Google App Engine Tests?. For more information, please follow other related articles on the PHP Chinese website!