test_decorators: Refactor mock.patch to assertLogs.

Replaced mock.patch with assertLogs for testing log outputs
in file zerver/tests/test_decorators.py
This commit is contained in:
palash 2020-07-15 16:16:41 +05:30 committed by Tim Abbott
parent c3fee5059f
commit 4e2769c31c
1 changed files with 44 additions and 48 deletions

View File

@ -287,25 +287,23 @@ class DecoratorTestCase(ZulipTestCase):
# Start a valid request here # Start a valid request here
request.POST['api_key'] = webhook_bot_api_key request.POST['api_key'] = webhook_bot_api_key
with mock.patch('logging.warning') as mock_warning: with self.assertLogs(level="WARNING") as m:
with self.assertRaisesRegex(JsonableError, with self.assertRaisesRegex(JsonableError,
"Account is not associated with this subdomain"): "Account is not associated with this subdomain"):
api_result = my_webhook(request) api_result = my_webhook(request)
self.assertEqual(
mock_warning.assert_called_with( m.output,
"User %s (%s) attempted to access API on wrong subdomain (%s)", ["WARNING:root:User {} ({}) attempted to access API on wrong subdomain ({})".format(webhook_bot_email, "zulip", "")]
webhook_bot_email, 'zulip', '',
) )
with mock.patch('logging.warning') as mock_warning: with self.assertLogs(level="WARNING") as m:
with self.assertRaisesRegex(JsonableError, with self.assertRaisesRegex(JsonableError,
"Account is not associated with this subdomain"): "Account is not associated with this subdomain"):
request.host = "acme." + settings.EXTERNAL_HOST request.host = "acme." + settings.EXTERNAL_HOST
api_result = my_webhook(request) api_result = my_webhook(request)
self.assertEqual(
mock_warning.assert_called_with( m.output,
"User %s (%s) attempted to access API on wrong subdomain (%s)", ["WARNING:root:User {} ({}) attempted to access API on wrong subdomain ({})".format(webhook_bot_email, "zulip", "acme")]
webhook_bot_email, 'zulip', 'acme',
) )
request.host = "zulip.testserver" request.host = "zulip.testserver"
@ -1327,26 +1325,24 @@ class TestValidateApiKey(ZulipTestCase):
def test_valid_api_key_if_user_is_on_wrong_subdomain(self) -> None: def test_valid_api_key_if_user_is_on_wrong_subdomain(self) -> None:
with self.settings(RUNNING_INSIDE_TORNADO=False): with self.settings(RUNNING_INSIDE_TORNADO=False):
api_key = get_api_key(self.default_bot) api_key = get_api_key(self.default_bot)
with mock.patch('logging.warning') as mock_warning: with self.assertLogs(level="WARNING") as m:
with self.assertRaisesRegex(JsonableError, with self.assertRaisesRegex(JsonableError,
"Account is not associated with this subdomain"): "Account is not associated with this subdomain"):
validate_api_key(HostRequestMock(host=settings.EXTERNAL_HOST), validate_api_key(HostRequestMock(host=settings.EXTERNAL_HOST),
self.default_bot.email, api_key) self.default_bot.email, api_key)
self.assertEqual(
mock_warning.assert_called_with( m.output,
"User %s (%s) attempted to access API on wrong subdomain (%s)", ["WARNING:root:User {} ({}) attempted to access API on wrong subdomain ({})".format(self.default_bot.email, "zulip", "")]
self.default_bot.email, 'zulip', '',
) )
with mock.patch('logging.warning') as mock_warning: with self.assertLogs(level="WARNING") as m:
with self.assertRaisesRegex(JsonableError, with self.assertRaisesRegex(JsonableError,
"Account is not associated with this subdomain"): "Account is not associated with this subdomain"):
validate_api_key(HostRequestMock(host='acme.' + settings.EXTERNAL_HOST), validate_api_key(HostRequestMock(host='acme.' + settings.EXTERNAL_HOST),
self.default_bot.email, api_key) self.default_bot.email, api_key)
self.assertEqual(
mock_warning.assert_called_with( m.output,
"User %s (%s) attempted to access API on wrong subdomain (%s)", ["WARNING:root:User {} ({}) attempted to access API on wrong subdomain ({})".format(self.default_bot.email, "zulip", "acme")]
self.default_bot.email, 'zulip', 'acme',
) )
def _change_is_active_field(self, profile: UserProfile, value: bool) -> None: def _change_is_active_field(self, profile: UserProfile, value: bool) -> None:
@ -1494,35 +1490,35 @@ class TestAuthenticatedJsonPostViewDecorator(ZulipTestCase):
def test_authenticated_json_post_view_with_get_request(self) -> None: def test_authenticated_json_post_view_with_get_request(self) -> None:
self.login('hamlet') self.login('hamlet')
with mock.patch('logging.warning') as mock_warning: with self.assertLogs(level="WARNING") as m:
result = self.client_get(r'/json/subscriptions/exists', {'stream': 'Verona'}) result = self.client_get(r'/json/subscriptions/exists', {'stream': 'Verona'})
self.assertEqual(result.status_code, 405) self.assertEqual(result.status_code, 405)
mock_warning.assert_called_once() # Check we logged the Mock Not Allowed self.assertEqual(m.output, ["WARNING:root:Method Not Allowed ({}): {}".format("GET", "/json/subscriptions/exists")])
self.assertEqual(mock_warning.call_args_list[0][0],
('Method Not Allowed (%s): %s', 'GET', '/json/subscriptions/exists'))
def test_authenticated_json_post_view_if_subdomain_is_invalid(self) -> None: def test_authenticated_json_post_view_if_subdomain_is_invalid(self) -> None:
user = self.example_user('hamlet') user = self.example_user('hamlet')
email = user.delivery_email email = user.delivery_email
self.login_user(user) self.login_user(user)
with mock.patch('logging.warning') as mock_warning, \ with self.assertLogs(level="WARNING") as m, \
mock.patch('zerver.decorator.get_subdomain', return_value=''): mock.patch('zerver.decorator.get_subdomain', return_value=''):
self.assert_json_error_contains(self._do_test(user), self.assert_json_error_contains(self._do_test(user),
"Account is not associated with this " "Account is not associated with this "
"subdomain") "subdomain")
mock_warning.assert_called_with( self.assertEqual(
"User %s (%s) attempted to access API on wrong subdomain (%s)", m.output,
email, 'zulip', '', ["WARNING:root:User {} ({}) attempted to access API on wrong subdomain ({})".format(email, 'zulip', ''),
"WARNING:root:User {} ({}) attempted to access API on wrong subdomain ({})".format(email, 'zulip', '')]
) )
with mock.patch('logging.warning') as mock_warning, \ with self.assertLogs(level="WARNING") as m, \
mock.patch('zerver.decorator.get_subdomain', return_value='acme'): mock.patch('zerver.decorator.get_subdomain', return_value='acme'):
self.assert_json_error_contains(self._do_test(user), self.assert_json_error_contains(self._do_test(user),
"Account is not associated with this " "Account is not associated with this "
"subdomain") "subdomain")
mock_warning.assert_called_with( self.assertEqual(
"User %s (%s) attempted to access API on wrong subdomain (%s)", m.output,
email, 'zulip', 'acme', ["WARNING:root:User {} ({}) attempted to access API on wrong subdomain ({})".format(email, 'zulip', 'acme'),
"WARNING:root:User {} ({}) attempted to access API on wrong subdomain ({})".format(email, 'zulip', 'acme')]
) )
def test_authenticated_json_post_view_if_user_is_incoming_webhook(self) -> None: def test_authenticated_json_post_view_if_user_is_incoming_webhook(self) -> None:
@ -1562,24 +1558,24 @@ class TestAuthenticatedJsonViewDecorator(ZulipTestCase):
email = user.delivery_email email = user.delivery_email
self.login_user(user) self.login_user(user)
with mock.patch('logging.warning') as mock_warning, \ with self.assertLogs(level="WARNING") as m, \
mock.patch('zerver.decorator.get_subdomain', return_value=''): mock.patch('zerver.decorator.get_subdomain', return_value=''):
self.assert_json_error_contains(self._do_test(email), self.assert_json_error_contains(self._do_test(email),
"Account is not associated with this " "Account is not associated with this "
"subdomain") "subdomain")
mock_warning.assert_called_with( self.assertEqual(
"User %s (%s) attempted to access API on wrong subdomain (%s)", m.output,
email, 'zulip', '', ["WARNING:root:User {} ({}) attempted to access API on wrong subdomain ({})".format(email, "zulip", "")]
) )
with mock.patch('logging.warning') as mock_warning, \ with self.assertLogs(level="WARNING") as m, \
mock.patch('zerver.decorator.get_subdomain', return_value='acme'): mock.patch('zerver.decorator.get_subdomain', return_value='acme'):
self.assert_json_error_contains(self._do_test(email), self.assert_json_error_contains(self._do_test(email),
"Account is not associated with this " "Account is not associated with this "
"subdomain") "subdomain")
mock_warning.assert_called_with( self.assertEqual(
"User %s (%s) attempted to access API on wrong subdomain (%s)", m.output,
email, 'zulip', 'acme', ["WARNING:root:User {} ({}) attempted to access API on wrong subdomain ({})".format(email, "zulip", "acme")]
) )
def _do_test(self, user_email: str) -> HttpResponse: def _do_test(self, user_email: str) -> HttpResponse: