2

我正在使用最新版本的 mock 和 python 2.7.3

我正在构建我的第一个烧瓶应用程序,并且正在测试一些基本的中间件以查看 flask.abort() 是否发生(当它发生时,我断言调用了一个带有未授权异常的方法)

    def test_invokes_raise_http_exception_when_apply_blows_up(self):
        start_response = mock.Mock()
        self.sut = BrokenMiddleware(self.app)
        with mock.patch.object(self.sut, 'raise_http_exception') as raise_up:
            self.sut.__call__({}, start_response)
        raise_up.assert_called_once_with(Unauthorized(), start_response)

class BrokenMiddleware(Middleware):

    def apply_middleware(self, environ):
        flask.abort(401) 

这是我的生产代码

class Middleware(object):
    def __call__(self, environ, start_response):                                                                               
        try:
            self.apply_middleware(environ)
        except Exception as e:
            return self.raise_http_exception(e, start_response)

    def raise_http_exception(self, exception, start_response):
        pass

我遇到的问题是模拟失败了断言,因为引发的 401 与我在断言本身中所期望的不同。

如果我只关心类型,而不关心实际实例,我该如何重写断言?

4

1 回答 1

1

你可能不会喜欢它,但这就是我过去做同样事情的方式:

self.assertIsInstance(raise_up.mock_calls[0][1][0], Unauthorized)

这里有一些解释

>>> print raise_up.mock_calls
[call(Unauthorized())]
>>> print raise_up.mock_calls[0]
call(Unauthorized())
>>> print raise_up.mock_calls[0][1]
(Unauthorized(),)
>>> print type(raise_up.mock_calls[0][1][0])
<type 'Unauthorized'>
于 2012-10-10T14:27:41.283 回答