質問

I'm using the latest version of mock and python 2.7.3

I'm building my first flask app and I'm testing some basic middleware to see if flask.abort() happens (and when it does, I assert a method was called with the Unauthorized exception)

    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) 

Here is my production code

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

The issue I'm having is that mock fails the assert because the 401 raised is not the same as the one I'm expecting in the assertion itself.

If I only care about the type, not the actual instance how could i rewrite the assertion?

役に立ちましたか?

解決

You're probably not going to like it, but this is how I've done the same thing in the past:

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

Here is some explanation

>>> 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'>
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top