Reject non existent mock assert calls

assert_called and assert_not_called are not asserting the state
of the mock object but considered as mocked calls so mock
will never raise exception but always executed successfully

This change patches the Mock class during unit test
to raise an exception if a function called on a mock object
that's name starts with 'assert' and does not one
of the supported Mock assert calls.

This change also fix the unit test to call only the supported
assert function on mock object.

Change-Id: I036587f355e42e362ac2b70fb6755cca81d30b75
This commit is contained in:
Balazs Gibizer 2014-12-12 15:09:12 +01:00
parent d485d755ec
commit ab2f1a742d
2 changed files with 27 additions and 3 deletions

View File

@ -14,6 +14,7 @@
import os
import fixtures
import mock
from oslo.serialization import jsonutils
import requests
from requests_mock.contrib import fixture as requests_mock_fixture
@ -26,6 +27,29 @@ AUTH_URL_V1 = "http://localhost:5002/auth_url/v1.0"
AUTH_URL_V2 = "http://localhost:5002/auth_url/v2.0"
def _patch_mock_to_raise_for_invalid_assert_calls():
def raise_for_invalid_assert_calls(wrapped):
def wrapper(_self, name):
valid_asserts = [
'assert_called_with',
'assert_called_once_with',
'assert_has_calls',
'assert_any_calls']
if name.startswith('assert') and name not in valid_asserts:
raise AttributeError('%s is not a valid mock assert method'
% name)
return wrapped(_self, name)
return wrapper
mock.Mock.__getattr__ = raise_for_invalid_assert_calls(
mock.Mock.__getattr__)
# NOTE(gibi): needs to be called only once at import time
# to patch the mock lib
_patch_mock_to_raise_for_invalid_assert_calls()
class TestCase(testtools.TestCase):
TEST_REQUEST_BASE = {
'verify': True,

View File

@ -369,8 +369,8 @@ class AuthenticationTests(utils.TestCase):
@mock.patch.object(http_client, 'authenticate')
def test_auth_call(m):
http_client.get('/')
m.assert_called()
mock_request.assert_called()
self.assertTrue(m.called)
self.assertTrue(mock_request.called)
test_auth_call()
@ -381,6 +381,6 @@ class AuthenticationTests(utils.TestCase):
@mock.patch.object(cs.client, 'authenticate')
def test_auth_call(m):
cs.authenticate()
m.assert_called()
self.assertTrue(m.called)
test_auth_call()