我正在尝试测试在 App Engine 上运行的应用程序。我正在使用 the Testbed framework ,到目前为止,除了以下意外行为外,它就像一个魅力:
像这样的测试将工作得很好(没有框架的简化版本):
from google.appengine.ext import db, testbed
testbed = testbed.Testbed()
testbed.activate()
testbed.init_datastore_v3_stub()
class Foo(db.Model):
pass
# now for the tests:
key = Foo().put()
assert key == db.Key.from_path('Foo', key.id())
assert Foo.all(keys_only=True).get() == db.Key.from_path('Foo', key.id())
assert db.get(db.Key.from_path('Foo', key.id())) # fails!
testbed.deactivate()
但是,以下将失败(同样是简化版):
from google.appengine.ext import db, testbed
testbed = testbed.Testbed()
testbed.activate()
testbed.init_datastore_v3_stub()
from myapp.models import Foo
# now for the tests:
key = Foo().put()
assert key == db.Key.from_path('Foo', key.id()) # fails!
assert Foo.all(keys_only=True).get() == db.Key.from_path('Foo', key.id()) # fails!
assert db.get(db.Key.from_path('Foo', key.id())) # fails!
# however, the following will succeed:
assert key == db.Key.from_path('Model', key.id())
assert Foo.all(keys_only=True).get() == db.Key.from_path('Model', key.id())
assert db.get(key)
testbed.deactivate()
模型名称在测试过程中在哪里消失了?为什么它只发生在导入的模块上?
编辑:
谢谢 proppy , 拼写错误已修复。
Nick Johnson ,让我尝试更好地解释它。
当我从 testbed
查询结果时数据存储 stub ,我得到一个实体,就像我期望的那样。但是当我调用 .key()
该实体上的方法,我得到类似 datastore_types.Key.from_path(u'Model', 1L, _app=u'testbed-test')
的东西, 而 Model
显然不是我的实体的正确类型。
当我尝试获取该键 ( datastore_types.Key.from_path(u'Model', 1L, _app=u'testbed-test')
) 的实体时,它工作正常。
问题是,当我只知道 id
一个数据存储实体,我尝试使用 db.Key.from_path(...)
手动构建 key .
比如kind应该是User
,所以我可以使用 db.Key.from_path('User', 1)
构造 key .但是我无法使用该 key 从数据存储中获取实体。但是,我可以使用 db.Key.from_path('Model', 1)
,但是,正如我所说,Model
不是正确的数据存储类型。
换句话说:
from myapp.models import User
User(email='dont@write.us').kind() # returns 'Model', not 'User'!
请注意,这种意外行为不会发生在生产或开发服务器中,仅在使用 testbed
时才会发生。 , 且仅当 db.Model
子类在我的应用程序代码中定义(即不在测试用例本身中)。
我没有使用 Django,我正在使用 Pyramid 进行遍历,但是我在这里运行的单元测试没有调用任何特定于框架的代码。
注意我还没有用 ndb
试过这个然而ndb
也发生了同样的事情还有..
编辑 2:
显然我没有注意到我所有的类都是 google.appengine.ext.db.polymodel.PolyModel
的子类子类,所以键实际上被正确设置为 Model
, 因为种类是 Model
在所有PolyModel
子类。
最佳答案
为了回答我自己的问题,这个问题是由我的项目中名为 migrations.py
的文件引起的,该文件使用具有不同属性的类重新定义了我的模型。当我运行测试时,nose
试图导入所有可用文件以发布覆盖率结果,这导致模块定义冲突,从而造成所有困惑。
关于python - Testbed 中的数据存储 key 不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8888427/