繁体   English   中英

如何使用unittest捕获CapabilityDisabledError异常?

[英]How do I use unittest to catch CapabilityDisabledError exceptions?

我在GAE上有一个Flask项目,我想开始在数据库写操作周围添加try / except块,以防数据存储出现问题,这肯定会在发生真正错误时触发,但我想在单元测试,这样我就可以确定中断期间实际发生的情况。

例如,我的User模型:

class User(ndb.Model):
    guser = ndb.UserProperty()
    user_handle = ndb.StringProperty()

和其他视图/控制器代码:

def do_something():
    try:
        User(guser=users.get_current_user(), user_handle='barney').put()
    except CapabilityDisabledError:
        flash('Oops, database is down, try again later', 'danger')
    return redirect(url_for('registration_done'))

这是我的测试代码的要点: https : //gist.github.com/iandouglas/10441406

简而言之,GAE允许我们使用功能来临时禁用memcache,datastore_v3等的存根,并在主要测试方法中:

def test_stuff(self):
    # this test ALWAYS passes, making me believe the datastore is temporarily down
    self.assertFalse(capabilities.CapabilitySet('datastore_v3').is_enabled())

    # but this write to the datastore always SUCCEEDS, so the exception never gets
    # thrown, therefore this "assertRaises" always fails
    self.assertRaises(CapabilityDisabledError,
        lambda: User(guser=self.guser, pilot_handle='foo').put())

我读了其他一些文章,建议将User.put()作为lambda调用,这会导致此回溯:

Traceback (most recent call last):
  File "/home/id/src/project/tests/integration/views/test_datastore_offline.py", line 28, in test_stuff
    self.assertRaises(CapabilityDisabledError, lambda: User(
AssertionError: CapabilityDisabledError not raised

如果删除lambda:部分,则会得到此回溯:

Traceback (most recent call last):
  File "/home/id/src/project/tests/integration/views/test_datastore_offline.py", line 31, in test_stuff
    pilot_handle_lower='foo'
  File "/usr/lib/python2.7/unittest/case.py", line 475, in assertRaises
    callableObj(*args, **kwargs)
TypeError: 'Key' object is not callable

Google的教程向您展示了如何打开和关闭这些功能以进行单元测试,在其他教程中,它们向您展示了如果其服务脱机或遇到间歇性问题,则可能引发哪些异常,但是它们没有教程来说明它们如何协同工作。单元测试。

感谢您的任何想法。

数据存储区存根不支持返回CapabilityDisabledError,因此启用功能存根中的错误不会影响对数据存储区的调用。

单独说明一下,如果您正在使用High Replication数据存储,则永远不会遇到CapabilityDisabledError,因为它没有计划的停机时间

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM