英文:
Why do I get "invalid entity type" with datastore.Put using a datastore.PropertyList in a Go AppEngine aetest?
问题
这个测试在partnermerge_test.go:22
行失败,错误信息是datastore: invalid entity type
。
package bigdipper
import (
"testing"
"appengine/aetest"
"appengine/datastore"
)
func TestCreateMigrationProposal(t *testing.T) {
c, err := aetest.NewContext(nil)
if err != nil {
t.Fatal(err)
}
defer c.Close()
if _, err := datastore.Put(
c,
datastore.NewKey(c, "ORDER", "order-id-1", 0, nil),
datastore.PropertyList{}); err != nil {
t.Fatal(err)
}
}
这段代码创建了一个名为TestCreateMigrationProposal
的测试函数,它使用appengine/aetest
和appengine/datastore
包进行测试。在测试函数中,它首先创建一个新的上下文c
,然后使用datastore.Put
函数将一个空的datastore.PropertyList
放入名为ORDER
、ID为order-id-1
的实体中。如果出现错误,测试函数将会失败并打印错误信息。
英文:
This test fails with partnermerge_test.go:22: datastore: invalid entity type
package bigdipper
import (
"testing"
"appengine/aetest"
"appengine/datastore"
)
func TestCreateMigrationProposal(t *testing.T) {
c, err := aetest.NewContext(nil)
if err != nil {
t.Fatal(err)
}
defer c.Close()
if _, err := datastore.Put(
c,
datastore.NewKey(c, "ORDER", "order-id-1", 0, nil),
datastore.PropertyList{}); err != nil {
t.Fatal(err)
}
}
答案1
得分: 1
> Put函数将实体src保存到具有键k的数据存储中。src必须是一个结构体指针或实现PropertyLoadSaver接口;如果是结构体指针,则会跳过该结构体中的任何未导出字段。如果k是不完整的键,则返回的键将是数据存储生成的唯一键。
当尝试将PropertyList作为src
使用时,这有点令人困惑。PropertyList并没有实现PropertyLoadSaver接口,但*PropertyList实现了该接口。在PropertyList之前添加一个&符号以获取指向它的指针可以修复这个问题。
package bigdipper
import (
"testing"
"appengine/aetest"
"appengine/datastore"
)
func TestCreateMigrationProposal(t *testing.T) {
c, err := aetest.NewContext(nil)
if err != nil {
t.Fatal(err)
}
defer c.Close()
if _, err := datastore.Put(
c,
datastore.NewKey(c, "ORDER", "order-id-1", 0, nil),
&datastore.PropertyList{}); err != nil {
t.Fatal(err)
}
}
英文:
The docs for the datastore.Put function say:
> Put saves the entity src into the datastore with key k. src must be a
> struct pointer or implement PropertyLoadSaver; if a struct pointer
> then any unexported fields of that struct will be skipped. If k is an
> incomplete key, the returned key will be a unique key generated by the
> datastore.
This was somewhat confusing when trying to use this with a PropertyList as the src
. A PropertyList does not implement PropertyLoadSaver, but a *PropertyList does. Adding an & before PropertyList to get a pointer to it fixes this test.
package bigdipper
import (
"testing"
"appengine/aetest"
"appengine/datastore"
)
func TestCreateMigrationProposal(t *testing.T) {
c, err := aetest.NewContext(nil)
if err != nil {
t.Fatal(err)
}
defer c.Close()
if _, err := datastore.Put(
c,
datastore.NewKey(c, "ORDER", "order-id-1", 0, nil),
&datastore.PropertyList{}); err != nil {
t.Fatal(err)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论