【问题标题】:put() throwing error while unit testing NDB based Flask app in GAE在 GAE 中对基于 NDB 的 Flask 应用程序进行单元测试时 put() 抛出错误
【发布时间】:2013-05-30 19:15:07
【问题描述】:

我正在单元测试用例中创建用户配置文件并尝试保存它。代码如下:

def create_user(self, email, user_id, is_admin=False):

    self.testbed.setup_env(
        USER_EMAIL = email,
        USER_ID = user_id,
        USER_IS_ADMIN = '1' if is_admin else '0',
        overwrite = True)
    user = users.get_current_user()
    print "user:", user
    u = UserProf( id=str(user.user_id()),
                  nickname = "Test",
                  email_address = user.email() )
    u.put()

我在执行测试用例时调用这个函数:

def test_users(self):

    self.create_user('test@example.com', '123', True)
    result = self.app('/users/')
    self.assertTrue("Test" in result)

u.put() 导致问题。错误:

BadKeyError:实体键与数据存储返回的不同。期望密钥('UserProf', '123'),得到密钥('UserProf', '123')

完整的堆栈跟踪,它的大:

https://gist.github.com/rajendrakrp/5705313

我没有在 net.xml 中找到与此错误相关的任何内容。除了一个,他也报告了同样的问题:https://gist.github.com/sivy/3364880

谢谢。

更新:添加了 UserProf 的模型类。

class UserProf(ndb.Model):

    nickname = ndb.StringProperty(required=True)
    email_address = ndb.StringProperty(required=True)
    is_admin = ndb.BooleanProperty()
    teams = ndb.KeyProperty(repeated=True)
    is_manager = ndb.BooleanProperty()

【问题讨论】:

  • 您可以发布您的型号代码吗?
  • @codegeek:用模型代码更新了问题。
  • 您的模型中的用户标识在哪里?我没看到。我猜你正在创建一个用户名作为字符串的 UserProf,而它应该是一个整数?
  • id 是 user_id。在 NDB 中,我们可以 'id' 可以存储字符串或整数。
  • 我刚刚在本地开发服务器的交互式控制台中进行了测试,它工作正常。通过单元测试用例完成时它不起作用。

标签: python google-app-engine google-cloud-datastore flask nose


【解决方案1】:

您必须为要在单元测试中使用的服务启用存根,包括数据存储。

class DemoTestCase(unittest.TestCase):

  def setUp(self):
    # First, create an instance of the Testbed class.
    self.testbed = testbed.Testbed()
    # Then activate the testbed, which prepares the service stubs for use.
    self.testbed.activate()
    # Next, declare which service stubs you want to use.
    self.testbed.init_datastore_v3_stub()
    self.testbed.init_memcache_stub()

【讨论】:

    【解决方案2】:

    在过去的几个小时里我也遇到了同样的问题,我最终使用nose-gae 和标志“--without-sandbox”运行了我的测试,正如这个错误问题https://code.google.com/p/nose-gae/issues/detail?id=60中所指出的那样

    我意识到这是一个老问题,但我想我会发布这个,以防它可以帮助其他人测试 ndb 并解决此错误。

    【讨论】:

      猜你喜欢
      • 2010-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-18
      • 1970-01-01
      • 2012-03-21
      相关资源
      最近更新 更多