From 3ec90f8b336e4ef1271ea820cd0dbcf54a7fe82e Mon Sep 17 00:00:00 2001 From: rht Date: Fri, 17 Nov 2017 09:47:43 +0000 Subject: [PATCH] zerver/tests: Use python 3 syntax for typing (final). --- zerver/tests/test_auth_backends.py | 441 ++++++++---------------- zerver/tests/test_events.py | 20 +- zerver/tests/test_logging_handlers.py | 43 +-- zerver/tests/test_push_notifications.py | 3 +- zerver/tests/test_signup.py | 6 +- 5 files changed, 176 insertions(+), 337 deletions(-) diff --git a/zerver/tests/test_auth_backends.py b/zerver/tests/test_auth_backends.py index 2aa35c5b9d..21861dc944 100644 --- a/zerver/tests/test_auth_backends.py +++ b/zerver/tests/test_auth_backends.py @@ -134,8 +134,7 @@ class AuthBackendTest(ZulipTestCase): user_profile.realm.authentication_methods.set_bit(index, True) user_profile.realm.save() - def test_dummy_backend(self): - # type: () -> None + def test_dummy_backend(self) -> None: realm = get_realm("zulip") username = self.get_username() self.verify_backend(ZulipDummyBackend(), @@ -151,8 +150,7 @@ class AuthBackendTest(ZulipTestCase): realm.string_id = 'zulip' realm.save() - def test_email_auth_backend(self): - # type: () -> None + def test_email_auth_backend(self) -> None: username = self.get_username() user_profile = self.example_user('hamlet') password = "testpassword" @@ -202,8 +200,7 @@ class AuthBackendTest(ZulipTestCase): realm=get_realm("zulip"))) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipDummyBackend',)) - def test_no_backend_enabled(self): - # type: () -> None + def test_no_backend_enabled(self) -> None: result = self.client_get('/login/') self.assert_in_success_response(["No authentication backends are enabled"], result) @@ -211,8 +208,7 @@ class AuthBackendTest(ZulipTestCase): self.assert_in_success_response(["No authentication backends are enabled"], result) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.GoogleMobileOauth2Backend',)) - def test_any_backend_enabled(self): - # type: () -> None + def test_any_backend_enabled(self) -> None: # testing to avoid false error messages. result = self.client_get('/login/') @@ -222,8 +218,7 @@ class AuthBackendTest(ZulipTestCase): self.assert_not_in_success_response(["No Authentication Backend is enabled."], result) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.GoogleMobileOauth2Backend',)) - def test_google_backend(self): - # type: () -> None + def test_google_backend(self) -> None: user_profile = self.example_user('hamlet') email = user_profile.email backend = GoogleMobileOauth2Backend() @@ -258,8 +253,7 @@ class AuthBackendTest(ZulipTestCase): self.assertIsNone(result) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',)) - def test_ldap_backend(self): - # type: () -> None + def test_ldap_backend(self) -> None: user_profile = self.example_user('hamlet') email = user_profile.email password = "test_password" @@ -295,8 +289,7 @@ class AuthBackendTest(ZulipTestCase): password=password, realm=get_realm('zulip'))) - def test_devauth_backend(self): - # type: () -> None + def test_devauth_backend(self) -> None: self.verify_backend(DevAuthBackend(), good_kwargs=dict(dev_auth_username=self.get_username(), realm=get_realm("zulip")), @@ -304,8 +297,7 @@ class AuthBackendTest(ZulipTestCase): realm=get_realm("invalid"))) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipRemoteUserBackend',)) - def test_remote_user_backend(self): - # type: () -> None + def test_remote_user_backend(self) -> None: username = self.get_username() self.verify_backend(ZulipRemoteUserBackend(), good_kwargs=dict(remote_user=username, @@ -325,8 +317,7 @@ class AuthBackendTest(ZulipTestCase): @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipRemoteUserBackend',)) @override_settings(SSO_APPEND_DOMAIN='zulip.com') - def test_remote_user_backend_sso_append_domain(self): - # type: () -> None + def test_remote_user_backend_sso_append_domain(self) -> None: username = self.get_username(email_to_username) self.verify_backend(ZulipRemoteUserBackend(), good_kwargs=dict(remote_user=username, @@ -335,8 +326,7 @@ class AuthBackendTest(ZulipTestCase): realm=get_realm('zephyr'))) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.GitHubAuthBackend',)) - def test_github_backend(self): - # type: () -> None + def test_github_backend(self) -> None: user = self.example_user('hamlet') email = user.email good_kwargs = dict(response=dict(email=email), return_data=dict(), @@ -352,8 +342,7 @@ class AuthBackendTest(ZulipTestCase): bad_kwargs=bad_kwargs) class SocialAuthMixinTest(ZulipTestCase): - def test_social_auth_mixing(self): - # type: () -> None + def test_social_auth_mixing(self) -> None: mixin = SocialAuthMixin() with self.assertRaises(NotImplementedError): mixin.get_email_address() @@ -361,8 +350,7 @@ class SocialAuthMixinTest(ZulipTestCase): mixin.get_full_name() class GitHubAuthBackendTest(ZulipTestCase): - def setUp(self): - # type: () -> None + def setUp(self) -> None: self.user_profile = self.example_user('hamlet') self.email = self.user_profile.email self.name = 'Hamlet' @@ -381,22 +369,18 @@ class GitHubAuthBackendTest(ZulipTestCase): with self.settings(AUTHENTICATION_BACKENDS=('zproject.backends.GitHubAuthBackend',)): return authenticate(**kwargs) - def test_github_auth_enabled(self): - # type: () -> None + def test_github_auth_enabled(self) -> None: with self.settings(AUTHENTICATION_BACKENDS=('zproject.backends.GitHubAuthBackend',)): self.assertTrue(github_auth_enabled()) - def test_full_name_with_missing_key(self): - # type: () -> None + def test_full_name_with_missing_key(self) -> None: self.assertEqual(self.backend.get_full_name(), '') self.assertEqual(self.backend.get_full_name(response={'name': None}), '') - def test_full_name_with_none(self): - # type: () -> None + def test_full_name_with_none(self) -> None: self.assertEqual(self.backend.get_full_name(response={'email': None}), '') - def test_github_backend_do_auth_with_non_existing_subdomain(self): - # type: () -> None + def test_github_backend_do_auth_with_non_existing_subdomain(self) -> None: with mock.patch('social_core.backends.github.GithubOAuth2.do_auth', side_effect=self.do_auth): self.backend.strategy.session_set('subdomain', 'test') @@ -405,8 +389,7 @@ class GitHubAuthBackendTest(ZulipTestCase): assert(result is not None) self.assertIn('subdomain=1', result.url) - def test_github_backend_do_auth_with_subdomains(self): - # type: () -> None + def test_github_backend_do_auth_with_subdomains(self) -> None: with mock.patch('social_core.backends.github.GithubOAuth2.do_auth', side_effect=self.do_auth): self.backend.strategy.session_set('subdomain', 'zulip') @@ -415,8 +398,7 @@ class GitHubAuthBackendTest(ZulipTestCase): assert(result is not None) self.assertTrue(result.url.startswith('http://zulip.testserver/accounts/login/subdomain/')) - def test_github_backend_do_auth_for_default(self): - # type: () -> None + def test_github_backend_do_auth_for_default(self) -> None: with mock.patch('social_core.backends.github.GithubOAuth2.do_auth', side_effect=self.do_auth), \ mock.patch('zproject.backends.SocialAuthMixin.process_do_auth') as result: @@ -429,8 +411,7 @@ class GitHubAuthBackendTest(ZulipTestCase): 'return_data': {'valid_attestation': True}} result.assert_called_with(self.user_profile, 'fake-access-token', **kwargs) - def test_github_backend_do_auth_for_default_auth_failed(self): - # type: () -> None + def test_github_backend_do_auth_for_default_auth_failed(self) -> None: with mock.patch('social_core.backends.github.GithubOAuth2.do_auth', side_effect=AuthFailed('Not found')), \ mock.patch('logging.info'), \ @@ -444,8 +425,7 @@ class GitHubAuthBackendTest(ZulipTestCase): 'return_data': {}} result.assert_called_with(None, 'fake-access-token', **kwargs) - def test_github_backend_do_auth_for_team(self): - # type: () -> None + def test_github_backend_do_auth_for_team(self) -> None: with mock.patch('social_core.backends.github.GithubTeamOAuth2.do_auth', side_effect=self.do_auth), \ mock.patch('zproject.backends.SocialAuthMixin.process_do_auth') as result: @@ -459,8 +439,7 @@ class GitHubAuthBackendTest(ZulipTestCase): 'return_data': {'valid_attestation': True}} result.assert_called_with(self.user_profile, 'fake-access-token', **kwargs) - def test_github_backend_do_auth_for_team_auth_failed(self): - # type: () -> None + def test_github_backend_do_auth_for_team_auth_failed(self) -> None: with mock.patch('social_core.backends.github.GithubTeamOAuth2.do_auth', side_effect=AuthFailed('Not found')), \ mock.patch('logging.info'), \ @@ -474,8 +453,7 @@ class GitHubAuthBackendTest(ZulipTestCase): 'return_data': {}} result.assert_called_with(None, 'fake-access-token', **kwargs) - def test_github_backend_do_auth_for_org(self): - # type: () -> None + def test_github_backend_do_auth_for_org(self) -> None: with mock.patch('social_core.backends.github.GithubOrganizationOAuth2.do_auth', side_effect=self.do_auth), \ mock.patch('zproject.backends.SocialAuthMixin.process_do_auth') as result: @@ -489,8 +467,7 @@ class GitHubAuthBackendTest(ZulipTestCase): 'return_data': {'valid_attestation': True}} result.assert_called_with(self.user_profile, 'fake-access-token', **kwargs) - def test_github_backend_do_auth_for_org_auth_failed(self): - # type: () -> None + def test_github_backend_do_auth_for_org_auth_failed(self) -> None: with mock.patch('social_core.backends.github.GithubOrganizationOAuth2.do_auth', side_effect=AuthFailed('Not found')), \ mock.patch('logging.info'), \ @@ -504,8 +481,7 @@ class GitHubAuthBackendTest(ZulipTestCase): 'return_data': {}} result.assert_called_with(None, 'fake-access-token', **kwargs) - def test_github_backend_authenticate_nonexisting_user(self): - # type: () -> None + def test_github_backend_authenticate_nonexisting_user(self) -> None: self.backend.strategy.session_set('subdomain', 'zulip') response = dict(email="invalid@zulip.com", name=self.name) return_data = dict() # type: Dict[str, Any] @@ -514,8 +490,7 @@ class GitHubAuthBackendTest(ZulipTestCase): self.assertIs(user, None) self.assertTrue(return_data['valid_attestation']) - def test_github_backend_authenticate_invalid_email(self): - # type: () -> None + def test_github_backend_authenticate_invalid_email(self) -> None: response = dict(email=None, name=self.name) return_data = dict() # type: Dict[str, Any] user = self.backend.authenticate(return_data=return_data, response=response, @@ -539,8 +514,7 @@ class GitHubAuthBackendTest(ZulipTestCase): result.assert_not_called() self.assertIs(user, None) - def test_github_backend_new_user_wrong_domain(self): - # type: () -> None + def test_github_backend_new_user_wrong_domain(self) -> None: rf = RequestFactory() request = rf.get('/complete') request.session = {} @@ -564,8 +538,7 @@ class GitHubAuthBackendTest(ZulipTestCase): 'in one of the domains that are allowed to register ' 'for accounts in this organization.'.format(email), result) - def test_github_backend_new_user(self): - # type: () -> None + def test_github_backend_new_user(self) -> None: rf = RequestFactory() request = rf.get('/complete') request.session = {} @@ -609,8 +582,7 @@ class GitHubAuthBackendTest(ZulipTestCase): user_profile = self.nonreg_user('newuser') self.assertEqual(get_session_dict_user(self.client.session), user_profile.id) - def test_github_backend_existing_user(self): - # type: () -> None + def test_github_backend_existing_user(self) -> None: rf = RequestFactory() request = rf.get('/complete') request.session = {} @@ -633,8 +605,7 @@ class GitHubAuthBackendTest(ZulipTestCase): self.assert_in_response('hamlet@zulip.com already has an account', result) - def test_github_backend_new_user_when_is_signup_is_false(self): - # type: () -> None + def test_github_backend_new_user_when_is_signup_is_false(self) -> None: rf = RequestFactory() request = rf.get('/complete') request.session = {} @@ -660,20 +631,17 @@ class GitHubAuthBackendTest(ZulipTestCase): self.assert_in_response('nonexisting@phantom.com. Would you like to register instead?', result) - def test_login_url(self): - # type: () -> None + def test_login_url(self) -> None: result = self.client_get('/accounts/login/social/github') self.assertIn(reverse('social:begin', args=['github']), result.url) self.assertIn('is_signup=0', result.url) - def test_signup_url(self): - # type: () -> None + def test_signup_url(self) -> None: result = self.client_get('/accounts/register/social/github') self.assertIn(reverse('social:begin', args=['github']), result.url) self.assertIn('is_signup=1', result.url) - def test_github_complete(self): - # type: () -> None + def test_github_complete(self) -> None: from social_django import utils utils.BACKENDS = ('zproject.backends.GitHubAuthBackend',) with mock.patch('social_core.backends.oauth.BaseOAuth2.process_error', @@ -684,8 +652,7 @@ class GitHubAuthBackendTest(ZulipTestCase): utils.BACKENDS = settings.AUTHENTICATION_BACKENDS - def test_github_complete_when_base_exc_is_raised(self): - # type: () -> None + def test_github_complete_when_base_exc_is_raised(self) -> None: from social_django import utils utils.BACKENDS = ('zproject.backends.GitHubAuthBackend',) with mock.patch('social_core.backends.oauth.BaseOAuth2.auth_complete', @@ -749,16 +716,14 @@ class GoogleOAuthTest(ZulipTestCase): return result class GoogleSubdomainLoginTest(GoogleOAuthTest): - def test_google_oauth2_start(self): - # type: () -> None + def test_google_oauth2_start(self) -> None: result = self.client_get('/accounts/login/google/', subdomain="zulip") self.assertEqual(result.status_code, 302) parsed_url = urllib.parse.urlparse(result.url) subdomain = urllib.parse.parse_qs(parsed_url.query)['subdomain'] self.assertEqual(subdomain, ['zulip']) - def test_google_oauth2_success(self): - # type: () -> None + def test_google_oauth2_success(self) -> None: token_response = ResponseMock(200, {'access_token': "unique_token"}) account_data = dict(name=dict(formatted="Full Name"), emails=[dict(type="account", @@ -776,8 +741,7 @@ class GoogleSubdomainLoginTest(GoogleOAuthTest): parsed_url.path) self.assertTrue(uri.startswith('http://zulip.testserver/accounts/login/subdomain/')) - def test_google_oauth2_no_fullname(self): - # type: () -> None + def test_google_oauth2_no_fullname(self) -> None: token_response = ResponseMock(200, {'access_token': "unique_token"}) account_data = dict(name=dict(givenName="Test", familyName="User"), emails=[dict(type="account", @@ -795,8 +759,7 @@ class GoogleSubdomainLoginTest(GoogleOAuthTest): parsed_url.path) self.assertTrue(uri.startswith('http://zulip.testserver/accounts/login/subdomain/')) - def test_google_oauth2_mobile_success(self): - # type: () -> None + def test_google_oauth2_mobile_success(self) -> None: mobile_flow_otp = '1234abcd' * 8 token_response = ResponseMock(200, {'access_token': "unique_token"}) account_data = dict(name=dict(formatted="Full Name"), @@ -834,8 +797,7 @@ class GoogleSubdomainLoginTest(GoogleOAuthTest): url_path = reverse('zerver.views.auth.log_into_subdomain', args=[token]) return self.client_get(url_path, subdomain=subdomain) - def test_log_into_subdomain(self): - # type: () -> None + def test_log_into_subdomain(self) -> None: data = {'name': 'Full Name', 'email': self.example_email("hamlet"), 'subdomain': 'zulip', @@ -854,8 +816,7 @@ class GoogleSubdomainLoginTest(GoogleOAuthTest): self.assertEqual(result.status_code, 302) self.assertTrue(result['Location'].endswith, '?subdomain=1') - def test_log_into_subdomain_when_signature_is_bad(self): - # type: () -> None + def test_log_into_subdomain_when_signature_is_bad(self) -> None: data = {'name': 'Full Name', 'email': self.example_email("hamlet"), 'subdomain': 'zulip', @@ -865,8 +826,7 @@ class GoogleSubdomainLoginTest(GoogleOAuthTest): mock_warning.assert_called_with("Subdomain cookie: Bad signature.") self.assertEqual(result.status_code, 400) - def test_log_into_subdomain_when_signature_is_expired(self): - # type: () -> None + def test_log_into_subdomain_when_signature_is_expired(self) -> None: data = {'name': 'Full Name', 'email': self.example_email("hamlet"), 'subdomain': 'zulip', @@ -879,8 +839,7 @@ class GoogleSubdomainLoginTest(GoogleOAuthTest): mock_warning.assert_called_once() self.assertEqual(result.status_code, 400) - def test_log_into_subdomain_when_is_signup_is_true(self): - # type: () -> None + def test_log_into_subdomain_when_is_signup_is_true(self) -> None: data = {'name': 'Full Name', 'email': self.example_email("hamlet"), 'subdomain': 'zulip', @@ -889,8 +848,8 @@ class GoogleSubdomainLoginTest(GoogleOAuthTest): self.assertEqual(result.status_code, 200) self.assert_in_response('hamlet@zulip.com already has an account', result) - def test_log_into_subdomain_when_is_signup_is_true_and_new_user(self): - # type: () -> None + def test_log_into_subdomain_when_is_signup_is_true_and_new_user( + self) -> None: data = {'name': 'New User Name', 'email': 'new@zulip.com', 'subdomain': 'zulip', @@ -912,8 +871,7 @@ class GoogleSubdomainLoginTest(GoogleOAuthTest): self.assert_not_in_success_response(['id_password'], result) self.assert_in_success_response(['id_full_name'], result) - def test_log_into_subdomain_when_using_invite_link(self): - # type: () -> None + def test_log_into_subdomain_when_using_invite_link(self) -> None: data = {'name': 'New User Name', 'email': 'new@zulip.com', 'subdomain': 'zulip', @@ -972,8 +930,7 @@ class GoogleSubdomainLoginTest(GoogleOAuthTest): self.assertEqual(result.status_code, 302) self.assertEqual(sorted(self.get_streams('new@zulip.com', realm)), stream_names) - def test_log_into_subdomain_when_email_is_none(self): - # type: () -> None + def test_log_into_subdomain_when_email_is_none(self) -> None: data = {'name': None, 'email': None, 'subdomain': 'zulip', @@ -985,8 +942,7 @@ class GoogleSubdomainLoginTest(GoogleOAuthTest): self.assert_in_response("Please click the following button if you " "wish to register", result) - def test_user_cannot_log_into_nonexisting_realm(self): - # type: () -> None + def test_user_cannot_log_into_nonexisting_realm(self) -> None: token_response = ResponseMock(200, {'access_token': "unique_token"}) account_data = dict(name=dict(formatted="Full Name"), emails=[dict(type="account", @@ -997,8 +953,7 @@ class GoogleSubdomainLoginTest(GoogleOAuthTest): self.assert_in_success_response(["There is no Zulip organization hosted at this subdomain."], result) - def test_user_cannot_log_into_wrong_subdomain(self): - # type: () -> None + def test_user_cannot_log_into_wrong_subdomain(self) -> None: token_response = ResponseMock(200, {'access_token': "unique_token"}) account_data = dict(name=dict(formatted="Full Name"), emails=[dict(type="account", @@ -1015,8 +970,7 @@ class GoogleSubdomainLoginTest(GoogleOAuthTest): self.assert_in_success_response(["Your Zulip account is not a member of the organization associated with this subdomain."], result) - def test_user_cannot_log_into_wrong_subdomain_with_cookie(self): - # type: () -> None + def test_user_cannot_log_into_wrong_subdomain_with_cookie(self) -> None: data = {'name': 'Full Name', 'email': self.example_email("hamlet"), 'subdomain': 'zephyr'} @@ -1025,8 +979,7 @@ class GoogleSubdomainLoginTest(GoogleOAuthTest): mock_warning.assert_called_with("Login attempt on invalid subdomain") self.assertEqual(result.status_code, 400) - def test_google_oauth2_registration(self): - # type: () -> None + def test_google_oauth2_registration(self) -> None: """If the user doesn't exist yet, Google auth can be used to register an account""" email = "newuser@zulip.com" realm = get_realm("zulip") @@ -1079,8 +1032,7 @@ class GoogleSubdomainLoginTest(GoogleOAuthTest): class GoogleLoginTest(GoogleOAuthTest): @override_settings(ROOT_DOMAIN_LANDING_PAGE=True) - def test_google_oauth2_subdomains_homepage(self): - # type: () -> None + def test_google_oauth2_subdomains_homepage(self) -> None: token_response = ResponseMock(200, {'access_token': "unique_token"}) account_data = dict(name=dict(formatted="Full Name"), emails=[dict(type="account", @@ -1090,8 +1042,7 @@ class GoogleLoginTest(GoogleOAuthTest): self.assertEqual(result.status_code, 302) self.assertIn('subdomain=1', result.url) - def test_google_oauth2_400_token_response(self): - # type: () -> None + def test_google_oauth2_400_token_response(self) -> None: token_response = ResponseMock(400, {}) with mock.patch("logging.warning") as m: result = self.google_oauth2_test(token_response, ResponseMock(500, {})) @@ -1099,8 +1050,7 @@ class GoogleLoginTest(GoogleOAuthTest): self.assertEqual(m.call_args_list[0][0][0], "User error converting Google oauth2 login to token: Response text") - def test_google_oauth2_500_token_response(self): - # type: () -> None + def test_google_oauth2_500_token_response(self) -> None: token_response = ResponseMock(500, {}) with mock.patch("logging.error") as m: result = self.google_oauth2_test(token_response, ResponseMock(500, {})) @@ -1108,8 +1058,7 @@ class GoogleLoginTest(GoogleOAuthTest): self.assertEqual(m.call_args_list[0][0][0], "Could not convert google oauth2 code to access_token: Response text") - def test_google_oauth2_400_account_response(self): - # type: () -> None + def test_google_oauth2_400_account_response(self) -> None: token_response = ResponseMock(200, {'access_token': "unique_token"}) account_response = ResponseMock(400, {}) with mock.patch("logging.warning") as m: @@ -1118,8 +1067,7 @@ class GoogleLoginTest(GoogleOAuthTest): self.assertEqual(m.call_args_list[0][0][0], "Google login failed making info API call: Response text") - def test_google_oauth2_500_account_response(self): - # type: () -> None + def test_google_oauth2_500_account_response(self) -> None: token_response = ResponseMock(200, {'access_token': "unique_token"}) account_response = ResponseMock(500, {}) with mock.patch("logging.error") as m: @@ -1128,8 +1076,7 @@ class GoogleLoginTest(GoogleOAuthTest): self.assertEqual(m.call_args_list[0][0][0], "Google login failed making API call: Response text") - def test_google_oauth2_account_response_no_email(self): - # type: () -> None + def test_google_oauth2_account_response_no_email(self) -> None: token_response = ResponseMock(200, {'access_token': "unique_token"}) account_data = dict(name=dict(formatted="Full Name"), emails=[]) @@ -1140,39 +1087,34 @@ class GoogleLoginTest(GoogleOAuthTest): self.assertEqual(result.status_code, 400) self.assertIn("Google oauth2 account email not found:", m.call_args_list[0][0][0]) - def test_google_oauth2_error_access_denied(self): - # type: () -> None + def test_google_oauth2_error_access_denied(self) -> None: result = self.client_get("/accounts/login/google/done/?error=access_denied") self.assertEqual(result.status_code, 302) path = urllib.parse.urlparse(result.url).path self.assertEqual(path, "/") - def test_google_oauth2_error_other(self): - # type: () -> None + def test_google_oauth2_error_other(self) -> None: with mock.patch("logging.warning") as m: result = self.client_get("/accounts/login/google/done/?error=some_other_error") self.assertEqual(result.status_code, 400) self.assertEqual(m.call_args_list[0][0][0], "Error from google oauth2 login: some_other_error") - def test_google_oauth2_missing_csrf(self): - # type: () -> None + def test_google_oauth2_missing_csrf(self) -> None: with mock.patch("logging.warning") as m: result = self.client_get("/accounts/login/google/done/") self.assertEqual(result.status_code, 400) self.assertEqual(m.call_args_list[0][0][0], 'Missing Google oauth2 CSRF state') - def test_google_oauth2_csrf_malformed(self): - # type: () -> None + def test_google_oauth2_csrf_malformed(self) -> None: with mock.patch("logging.warning") as m: result = self.client_get("/accounts/login/google/done/?state=badstate") self.assertEqual(result.status_code, 400) self.assertEqual(m.call_args_list[0][0][0], 'Missing Google oauth2 CSRF state') - def test_google_oauth2_csrf_badstate(self): - # type: () -> None + def test_google_oauth2_csrf_badstate(self) -> None: with mock.patch("logging.warning") as m: result = self.client_get("/accounts/login/google/done/?state=badstate:otherbadstate:more::") self.assertEqual(result.status_code, 400) @@ -1180,27 +1122,23 @@ class GoogleLoginTest(GoogleOAuthTest): 'Google oauth2 CSRF error') class FetchAPIKeyTest(ZulipTestCase): - def setUp(self): - # type: () -> None + def setUp(self) -> None: self.user_profile = self.example_user('hamlet') self.email = self.user_profile.email - def test_success(self): - # type: () -> None + def test_success(self) -> None: result = self.client_post("/api/v1/fetch_api_key", dict(username=self.email, password=initial_password(self.email))) self.assert_json_success(result) - def test_invalid_email(self): - # type: () -> None + def test_invalid_email(self) -> None: result = self.client_post("/api/v1/fetch_api_key", dict(username='hamlet', password=initial_password(self.email))) self.assert_json_error(result, "Enter a valid email address.", 400) - def test_wrong_password(self): - # type: () -> None + def test_wrong_password(self) -> None: result = self.client_post("/api/v1/fetch_api_key", dict(username=self.email, password="wrong")) @@ -1208,8 +1146,7 @@ class FetchAPIKeyTest(ZulipTestCase): @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.GoogleMobileOauth2Backend',), SEND_LOGIN_EMAILS=True) - def test_google_oauth2_token_success(self): - # type: () -> None + def test_google_oauth2_token_success(self) -> None: self.assertEqual(len(mail.outbox), 0) with mock.patch( 'apiclient.sample_tools.client.verify_id_token', @@ -1224,8 +1161,7 @@ class FetchAPIKeyTest(ZulipTestCase): self.assertEqual(len(mail.outbox), 1) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.GoogleMobileOauth2Backend',)) - def test_google_oauth2_token_failure(self): - # type: () -> None + def test_google_oauth2_token_failure(self) -> None: payload = dict(email_verified=False) with mock.patch('apiclient.sample_tools.client.verify_id_token', return_value=payload): result = self.client_post("/api/v1/fetch_api_key", @@ -1234,8 +1170,7 @@ class FetchAPIKeyTest(ZulipTestCase): self.assert_json_error(result, "Your username or password is incorrect.", 403) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.GoogleMobileOauth2Backend',)) - def test_google_oauth2_token_unregistered(self): - # type: () -> None + def test_google_oauth2_token_unregistered(self) -> None: with mock.patch( 'apiclient.sample_tools.client.verify_id_token', return_value={ @@ -1250,8 +1185,7 @@ class FetchAPIKeyTest(ZulipTestCase): "This user is not registered; do so from a browser.", 403) - def test_password_auth_disabled(self): - # type: () -> None + def test_password_auth_disabled(self) -> None: with mock.patch('zproject.backends.password_auth_enabled', return_value=False): result = self.client_post("/api/v1/fetch_api_key", dict(username=self.email, @@ -1259,8 +1193,7 @@ class FetchAPIKeyTest(ZulipTestCase): self.assert_json_error_contains(result, "Password auth is disabled", 403) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',)) - def test_ldap_auth_email_auth_disabled_success(self): - # type: () -> None + def test_ldap_auth_email_auth_disabled_success(self) -> None: ldap_patcher = mock.patch('django_auth_ldap.config.ldap.initialize') self.mock_initialize = ldap_patcher.start() self.mock_ldap = MockLDAP() @@ -1283,16 +1216,14 @@ class FetchAPIKeyTest(ZulipTestCase): self.mock_ldap.reset() self.mock_initialize.stop() - def test_inactive_user(self): - # type: () -> None + def test_inactive_user(self) -> None: do_deactivate_user(self.user_profile) result = self.client_post("/api/v1/fetch_api_key", dict(username=self.email, password=initial_password(self.email))) self.assert_json_error_contains(result, "Your account has been disabled", 403) - def test_deactivated_realm(self): - # type: () -> None + def test_deactivated_realm(self) -> None: do_deactivate_realm(self.user_profile.realm) result = self.client_post("/api/v1/fetch_api_key", dict(username=self.email, @@ -1300,13 +1231,11 @@ class FetchAPIKeyTest(ZulipTestCase): self.assert_json_error_contains(result, "Your realm has been deactivated", 403) class DevFetchAPIKeyTest(ZulipTestCase): - def setUp(self): - # type: () -> None + def setUp(self) -> None: self.user_profile = self.example_user('hamlet') self.email = self.user_profile.email - def test_success(self): - # type: () -> None + def test_success(self) -> None: result = self.client_post("/api/v1/dev_fetch_api_key", dict(username=self.email)) self.assert_json_success(result) @@ -1314,51 +1243,44 @@ class DevFetchAPIKeyTest(ZulipTestCase): self.assertEqual(data["email"], self.email) self.assertEqual(data['api_key'], self.user_profile.api_key) - def test_invalid_email(self): - # type: () -> None + def test_invalid_email(self) -> None: email = 'hamlet' result = self.client_post("/api/v1/dev_fetch_api_key", dict(username=email)) self.assert_json_error_contains(result, "Enter a valid email address.", 400) - def test_unregistered_user(self): - # type: () -> None + def test_unregistered_user(self) -> None: email = 'foo@zulip.com' result = self.client_post("/api/v1/dev_fetch_api_key", dict(username=email)) self.assert_json_error_contains(result, "This user is not registered.", 403) - def test_inactive_user(self): - # type: () -> None + def test_inactive_user(self) -> None: do_deactivate_user(self.user_profile) result = self.client_post("/api/v1/dev_fetch_api_key", dict(username=self.email)) self.assert_json_error_contains(result, "Your account has been disabled", 403) - def test_deactivated_realm(self): - # type: () -> None + def test_deactivated_realm(self) -> None: do_deactivate_realm(self.user_profile.realm) result = self.client_post("/api/v1/dev_fetch_api_key", dict(username=self.email)) self.assert_json_error_contains(result, "Your realm has been deactivated", 403) - def test_dev_auth_disabled(self): - # type: () -> None + def test_dev_auth_disabled(self) -> None: with mock.patch('zerver.views.auth.dev_auth_enabled', return_value=False): result = self.client_post("/api/v1/dev_fetch_api_key", dict(username=self.email)) self.assert_json_error_contains(result, "Dev environment not enabled.", 400) class DevGetEmailsTest(ZulipTestCase): - def test_success(self): - # type: () -> None + def test_success(self) -> None: result = self.client_get("/api/v1/dev_get_emails") self.assert_json_success(result) self.assert_in_response("direct_admins", result) self.assert_in_response("direct_users", result) - def test_dev_auth_disabled(self): - # type: () -> None + def test_dev_auth_disabled(self) -> None: with mock.patch('zerver.views.auth.dev_auth_enabled', return_value=False): result = self.client_get("/api/v1/dev_get_emails") self.assert_json_error_contains(result, "Dev environment not enabled.", 400) @@ -1368,8 +1290,7 @@ class FetchAuthBackends(ZulipTestCase): if error: raise AssertionError(error) - def test_get_server_settings(self): - # type: () -> None + def test_get_server_settings(self) -> None: result = self.client_get("/api/v1/server_settings", subdomain="") self.assert_json_success(result) @@ -1441,8 +1362,7 @@ class FetchAuthBackends(ZulipTestCase): ]) self.assert_on_error(with_realm_schema_checker("data", data)) - def test_fetch_auth_backend_format(self): - # type: () -> None + def test_fetch_auth_backend_format(self) -> None: result = self.client_get("/api/v1/get_auth_backends") self.assert_json_success(result) data = result.json() @@ -1452,8 +1372,7 @@ class FetchAuthBackends(ZulipTestCase): for backend in set(data.keys()) - {'msg', 'result', 'zulip_version'}: self.assertTrue(isinstance(data[backend], bool)) - def test_fetch_auth_backend(self): - # type: () -> None + def test_fetch_auth_backend(self) -> None: backends = [GoogleMobileOauth2Backend(), DevAuthBackend()] with mock.patch('django.contrib.auth.get_backends', return_value=backends): result = self.client_get("/api/v1/get_auth_backends") @@ -1536,8 +1455,7 @@ class FetchAuthBackends(ZulipTestCase): }) class TestDevAuthBackend(ZulipTestCase): - def test_login_success(self): - # type: () -> None + def test_login_success(self) -> None: user_profile = self.example_user('hamlet') email = user_profile.email data = {'direct_email': email} @@ -1545,8 +1463,7 @@ class TestDevAuthBackend(ZulipTestCase): self.assertEqual(result.status_code, 302) self.assertEqual(get_session_dict_user(self.client.session), user_profile.id) - def test_login_with_subdomain(self): - # type: () -> None + def test_login_with_subdomain(self) -> None: user_profile = self.example_user('hamlet') email = user_profile.email data = {'direct_email': email} @@ -1555,8 +1472,7 @@ class TestDevAuthBackend(ZulipTestCase): self.assertEqual(result.status_code, 302) self.assertEqual(get_session_dict_user(self.client.session), user_profile.id) - def test_choose_realm(self): - # type: () -> None + def test_choose_realm(self) -> None: result = self.client_post('/devlogin/', subdomain="zulip") self.assert_in_success_response(["Click on a user to log in to Zulip Dev!"], result) self.assert_in_success_response(["iago@zulip.com", "hamlet@zulip.com"], result) @@ -1575,8 +1491,7 @@ class TestDevAuthBackend(ZulipTestCase): self.assert_in_success_response(["Click on a user to log in to MIT!"], result) self.assert_not_in_success_response(["iago@zulip.com", "hamlet@zulip.com"], result) - def test_choose_realm_with_subdomains_enabled(self): - # type: () -> None + def test_choose_realm_with_subdomains_enabled(self) -> None: with mock.patch('zerver.views.auth.is_subdomain_root_or_alias', return_value=False): with mock.patch('zerver.views.auth.get_realm_from_request', return_value=get_realm('zulip')): result = self.client_get("http://zulip.testserver/devlogin/") @@ -1593,8 +1508,7 @@ class TestDevAuthBackend(ZulipTestCase): self.assert_in_success_response(["starnine@mit.edu", "espuser@mit.edu"], result) self.assert_in_success_response(["Click on a user to log in to MIT!"], result) - def test_login_failure(self): - # type: () -> None + def test_login_failure(self) -> None: email = self.example_email("hamlet") data = {'direct_email': email} with self.settings(AUTHENTICATION_BACKENDS=('zproject.backends.EmailAuthBackend',)): @@ -1602,8 +1516,7 @@ class TestDevAuthBackend(ZulipTestCase): with mock.patch('django.core.handlers.exception.logger'): self.client_post('/accounts/login/local/', data) - def test_login_failure_due_to_nonexistent_user(self): - # type: () -> None + def test_login_failure_due_to_nonexistent_user(self) -> None: email = 'nonexisting@zulip.com' data = {'direct_email': email} with self.assertRaisesRegex(Exception, 'User cannot login'): @@ -1611,8 +1524,7 @@ class TestDevAuthBackend(ZulipTestCase): self.client_post('/accounts/login/local/', data) class TestZulipRemoteUserBackend(ZulipTestCase): - def test_login_success(self): - # type: () -> None + def test_login_success(self) -> None: user_profile = self.example_user('hamlet') email = user_profile.email with self.settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipRemoteUserBackend',)): @@ -1620,8 +1532,7 @@ class TestZulipRemoteUserBackend(ZulipTestCase): self.assertEqual(result.status_code, 302) self.assertEqual(get_session_dict_user(self.client.session), user_profile.id) - def test_login_success_with_sso_append_domain(self): - # type: () -> None + def test_login_success_with_sso_append_domain(self) -> None: username = 'hamlet' user_profile = self.example_user('hamlet') with self.settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipRemoteUserBackend',), @@ -1630,15 +1541,13 @@ class TestZulipRemoteUserBackend(ZulipTestCase): self.assertEqual(result.status_code, 302) self.assertEqual(get_session_dict_user(self.client.session), user_profile.id) - def test_login_failure(self): - # type: () -> None + def test_login_failure(self) -> None: email = self.example_email("hamlet") result = self.client_post('/accounts/login/sso/', REMOTE_USER=email) self.assertEqual(result.status_code, 200) # This should ideally be not 200. self.assertIs(get_session_dict_user(self.client.session), None) - def test_login_failure_due_to_nonexisting_user(self): - # type: () -> None + def test_login_failure_due_to_nonexisting_user(self) -> None: email = 'nonexisting@zulip.com' with self.settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipRemoteUserBackend',)): result = self.client_post('/accounts/login/sso/', REMOTE_USER=email) @@ -1646,21 +1555,18 @@ class TestZulipRemoteUserBackend(ZulipTestCase): self.assertIs(get_session_dict_user(self.client.session), None) self.assert_in_response("No account found for", result) - def test_login_failure_due_to_invalid_email(self): - # type: () -> None + def test_login_failure_due_to_invalid_email(self) -> None: email = 'hamlet' with self.settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipRemoteUserBackend',)): result = self.client_post('/accounts/login/sso/', REMOTE_USER=email) self.assert_json_error_contains(result, "Enter a valid email address.", 400) - def test_login_failure_due_to_missing_field(self): - # type: () -> None + def test_login_failure_due_to_missing_field(self) -> None: with self.settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipRemoteUserBackend',)): result = self.client_post('/accounts/login/sso/') self.assert_json_error_contains(result, "No REMOTE_USER set.", 400) - def test_login_failure_due_to_wrong_subdomain(self): - # type: () -> None + def test_login_failure_due_to_wrong_subdomain(self) -> None: email = self.example_email("hamlet") with self.settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipRemoteUserBackend',)): with mock.patch('zerver.views.auth.get_subdomain', return_value='acme'): @@ -1670,8 +1576,7 @@ class TestZulipRemoteUserBackend(ZulipTestCase): self.assertIs(get_session_dict_user(self.client.session), None) self.assert_in_response("No account found for", result) - def test_login_failure_due_to_empty_subdomain(self): - # type: () -> None + def test_login_failure_due_to_empty_subdomain(self) -> None: email = self.example_email("hamlet") with self.settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipRemoteUserBackend',)): with mock.patch('zerver.views.auth.get_subdomain', return_value=''): @@ -1681,8 +1586,7 @@ class TestZulipRemoteUserBackend(ZulipTestCase): self.assertIs(get_session_dict_user(self.client.session), None) self.assert_in_response("No account found for", result) - def test_login_success_under_subdomains(self): - # type: () -> None + def test_login_success_under_subdomains(self) -> None: user_profile = self.example_user('hamlet') email = user_profile.email with mock.patch('zerver.views.auth.get_subdomain', return_value='zulip'): @@ -1697,8 +1601,7 @@ class TestJWTLogin(ZulipTestCase): JWT uses ZulipDummyBackend. """ - def test_login_success(self): - # type: () -> None + def test_login_success(self) -> None: payload = {'user': 'hamlet', 'realm': 'zulip.com'} with self.settings(JWT_AUTH_KEYS={'zulip': 'key'}): email = self.example_email("hamlet") @@ -1712,8 +1615,7 @@ class TestJWTLogin(ZulipTestCase): self.assertEqual(result.status_code, 302) self.assertEqual(get_session_dict_user(self.client.session), user_profile.id) - def test_login_failure_when_user_is_missing(self): - # type: () -> None + def test_login_failure_when_user_is_missing(self) -> None: payload = {'realm': 'zulip.com'} with self.settings(JWT_AUTH_KEYS={'zulip': 'key'}): auth_key = settings.JWT_AUTH_KEYS['zulip'] @@ -1722,8 +1624,7 @@ class TestJWTLogin(ZulipTestCase): result = self.client_post('/accounts/login/jwt/', data) self.assert_json_error_contains(result, "No user specified in JSON web token claims", 400) - def test_login_failure_when_realm_is_missing(self): - # type: () -> None + def test_login_failure_when_realm_is_missing(self) -> None: payload = {'user': 'hamlet'} with self.settings(JWT_AUTH_KEYS={'zulip': 'key'}): auth_key = settings.JWT_AUTH_KEYS['zulip'] @@ -1732,20 +1633,17 @@ class TestJWTLogin(ZulipTestCase): result = self.client_post('/accounts/login/jwt/', data) self.assert_json_error_contains(result, "No realm specified in JSON web token claims", 400) - def test_login_failure_when_key_does_not_exist(self): - # type: () -> None + def test_login_failure_when_key_does_not_exist(self) -> None: data = {'json_web_token': 'not relevant'} result = self.client_post('/accounts/login/jwt/', data) self.assert_json_error_contains(result, "Auth key for this subdomain not found.", 400) - def test_login_failure_when_key_is_missing(self): - # type: () -> None + def test_login_failure_when_key_is_missing(self) -> None: with self.settings(JWT_AUTH_KEYS={'zulip': 'key'}): result = self.client_post('/accounts/login/jwt/') self.assert_json_error_contains(result, "No JSON web token passed in request", 400) - def test_login_failure_when_bad_token_is_passed(self): - # type: () -> None + def test_login_failure_when_bad_token_is_passed(self) -> None: with self.settings(JWT_AUTH_KEYS={'zulip': 'key'}): result = self.client_post('/accounts/login/jwt/') self.assert_json_error_contains(result, "No JSON web token passed in request", 400) @@ -1753,8 +1651,7 @@ class TestJWTLogin(ZulipTestCase): result = self.client_post('/accounts/login/jwt/', data) self.assert_json_error_contains(result, "Bad JSON web token", 400) - def test_login_failure_when_user_does_not_exist(self): - # type: () -> None + def test_login_failure_when_user_does_not_exist(self) -> None: payload = {'user': 'nonexisting', 'realm': 'zulip.com'} with self.settings(JWT_AUTH_KEYS={'zulip': 'key'}): auth_key = settings.JWT_AUTH_KEYS['zulip'] @@ -1773,8 +1670,7 @@ class TestJWTLogin(ZulipTestCase): self.assertEqual(result.status_code, 200) # This should ideally be not 200. self.assertIs(get_session_dict_user(self.client.session), None) - def test_login_failure_due_to_wrong_subdomain(self): - # type: () -> None + def test_login_failure_due_to_wrong_subdomain(self) -> None: payload = {'user': 'hamlet', 'realm': 'zulip.com'} with self.settings(JWT_AUTH_KEYS={'acme': 'key'}): with mock.patch('zerver.views.auth.get_subdomain', return_value='acme'), \ @@ -1787,8 +1683,7 @@ class TestJWTLogin(ZulipTestCase): self.assert_json_error_contains(result, "Wrong subdomain", 400) self.assertEqual(get_session_dict_user(self.client.session), None) - def test_login_failure_due_to_empty_subdomain(self): - # type: () -> None + def test_login_failure_due_to_empty_subdomain(self) -> None: payload = {'user': 'hamlet', 'realm': 'zulip.com'} with self.settings(JWT_AUTH_KEYS={'': 'key'}): with mock.patch('zerver.views.auth.get_subdomain', return_value=''), \ @@ -1801,8 +1696,7 @@ class TestJWTLogin(ZulipTestCase): self.assert_json_error_contains(result, "Wrong subdomain", 400) self.assertEqual(get_session_dict_user(self.client.session), None) - def test_login_success_under_subdomains(self): - # type: () -> None + def test_login_success_under_subdomains(self) -> None: payload = {'user': 'hamlet', 'realm': 'zulip.com'} with self.settings(JWT_AUTH_KEYS={'zulip': 'key'}): with mock.patch('zerver.views.auth.get_subdomain', return_value='zulip'): @@ -1816,8 +1710,7 @@ class TestJWTLogin(ZulipTestCase): self.assertEqual(get_session_dict_user(self.client.session), user_profile.id) class TestLDAP(ZulipTestCase): - def setUp(self): - # type: () -> None + def setUp(self) -> None: user_profile = self.example_user('hamlet') self.setup_subdomain(user_profile) @@ -1831,8 +1724,7 @@ class TestLDAP(ZulipTestCase): # method separately, we need to set it manually. self.backend._realm = get_realm('zulip') - def tearDown(self): - # type: () -> None + def tearDown(self) -> None: self.mock_ldap.reset() self.mock_initialize.stop() @@ -1842,8 +1734,7 @@ class TestLDAP(ZulipTestCase): realm.save() @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',)) - def test_login_success(self): - # type: () -> None + def test_login_success(self) -> None: self.mock_ldap.directory = { 'uid=hamlet,ou=users,dc=zulip,dc=com': { 'userPassword': 'testing' @@ -1860,8 +1751,7 @@ class TestLDAP(ZulipTestCase): self.assertEqual(user_profile.email, self.example_email("hamlet")) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',)) - def test_login_success_with_email_attr(self): - # type: () -> None + def test_login_success_with_email_attr(self) -> None: self.mock_ldap.directory = { 'uid=letham,ou=users,dc=zulip,dc=com': { 'userPassword': 'testing', @@ -1878,8 +1768,7 @@ class TestLDAP(ZulipTestCase): self.assertEqual(user_profile.email, self.example_email("hamlet")) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',)) - def test_login_failure_due_to_wrong_password(self): - # type: () -> None + def test_login_failure_due_to_wrong_password(self) -> None: self.mock_ldap.directory = { 'uid=hamlet,ou=users,dc=zulip,dc=com': { 'userPassword': 'testing' @@ -1893,8 +1782,7 @@ class TestLDAP(ZulipTestCase): self.assertIs(user, None) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',)) - def test_login_failure_due_to_nonexistent_user(self): - # type: () -> None + def test_login_failure_due_to_nonexistent_user(self) -> None: self.mock_ldap.directory = { 'uid=hamlet,ou=users,dc=zulip,dc=com': { 'userPassword': 'testing' @@ -1908,8 +1796,7 @@ class TestLDAP(ZulipTestCase): self.assertIs(user, None) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',)) - def test_ldap_permissions(self): - # type: () -> None + def test_ldap_permissions(self) -> None: backend = self.backend self.assertFalse(backend.has_perm(None, None)) self.assertFalse(backend.has_module_perms(None, None)) @@ -1917,24 +1804,21 @@ class TestLDAP(ZulipTestCase): self.assertTrue(backend.get_group_permissions(None, None) == set()) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',)) - def test_django_to_ldap_username(self): - # type: () -> None + def test_django_to_ldap_username(self) -> None: backend = self.backend with self.settings(LDAP_APPEND_DOMAIN='zulip.com'): username = backend.django_to_ldap_username('"hamlet@test"@zulip.com') self.assertEqual(username, '"hamlet@test"') @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',)) - def test_ldap_to_django_username(self): - # type: () -> None + def test_ldap_to_django_username(self) -> None: backend = self.backend with self.settings(LDAP_APPEND_DOMAIN='zulip.com'): username = backend.ldap_to_django_username('"hamlet@test"') self.assertEqual(username, '"hamlet@test"@zulip.com') @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',)) - def test_get_or_create_user_when_user_exists(self): - # type: () -> None + def test_get_or_create_user_when_user_exists(self) -> None: class _LDAPUser: attrs = {'fn': ['Full Name'], 'sn': ['Short Name']} @@ -1945,8 +1829,7 @@ class TestLDAP(ZulipTestCase): self.assertEqual(user_profile.email, email) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',)) - def test_get_or_create_user_when_user_does_not_exist(self): - # type: () -> None + def test_get_or_create_user_when_user_does_not_exist(self) -> None: class _LDAPUser: attrs = {'fn': ['Full Name'], 'sn': ['Short Name']} @@ -1961,8 +1844,7 @@ class TestLDAP(ZulipTestCase): self.assertEqual(user_profile.full_name, 'Full Name') @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',)) - def test_get_or_create_user_when_user_has_invalid_name(self): - # type: () -> None + def test_get_or_create_user_when_user_has_invalid_name(self) -> None: class _LDAPUser: attrs = {'fn': [''], 'sn': ['Short Name']} @@ -1975,8 +1857,7 @@ class TestLDAP(ZulipTestCase): backend.get_or_create_user(email, _LDAPUser()) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',)) - def test_get_or_create_user_when_realm_is_deactivated(self): - # type: () -> None + def test_get_or_create_user_when_realm_is_deactivated(self) -> None: class _LDAPUser: attrs = {'fn': ['Full Name'], 'sn': ['Short Name']} @@ -1990,8 +1871,7 @@ class TestLDAP(ZulipTestCase): backend.get_or_create_user(email, _LDAPUser()) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',)) - def test_get_or_create_user_when_ldap_has_no_email_attr(self): - # type: () -> None + def test_get_or_create_user_when_ldap_has_no_email_attr(self) -> None: class _LDAPUser: attrs = {'fn': ['Full Name'], 'sn': ['Short Name']} @@ -2003,8 +1883,7 @@ class TestLDAP(ZulipTestCase): backend.get_or_create_user(email, _LDAPUser()) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',)) - def test_django_to_ldap_username_when_domain_does_not_match(self): - # type: () -> None + def test_django_to_ldap_username_when_domain_does_not_match(self) -> None: backend = self.backend email = self.example_email("hamlet") with self.assertRaisesRegex(Exception, 'Username does not match LDAP domain.'): @@ -2012,15 +1891,13 @@ class TestLDAP(ZulipTestCase): backend.django_to_ldap_username(email) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',)) - def test_login_failure_when_domain_does_not_match(self): - # type: () -> None + def test_login_failure_when_domain_does_not_match(self) -> None: with self.settings(LDAP_APPEND_DOMAIN='acme.com'): user_profile = self.backend.authenticate(self.example_email("hamlet"), 'pass') self.assertIs(user_profile, None) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',)) - def test_login_failure_due_to_wrong_subdomain(self): - # type: () -> None + def test_login_failure_due_to_wrong_subdomain(self) -> None: self.mock_ldap.directory = { 'uid=hamlet,ou=users,dc=zulip,dc=com': { 'userPassword': 'testing' @@ -2035,8 +1912,7 @@ class TestLDAP(ZulipTestCase): self.assertIs(user_profile, None) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',)) - def test_login_failure_due_to_invalid_subdomain(self): - # type: () -> None + def test_login_failure_due_to_invalid_subdomain(self) -> None: self.mock_ldap.directory = { 'uid=hamlet,ou=users,dc=zulip,dc=com': { 'userPassword': 'testing' @@ -2051,8 +1927,7 @@ class TestLDAP(ZulipTestCase): self.assertIs(user_profile, None) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',)) - def test_login_success_with_valid_subdomain(self): - # type: () -> None + def test_login_success_with_valid_subdomain(self) -> None: self.mock_ldap.directory = { 'uid=hamlet,ou=users,dc=zulip,dc=com': { 'userPassword': 'testing' @@ -2068,8 +1943,7 @@ class TestLDAP(ZulipTestCase): self.assertEqual(user_profile.email, self.example_email("hamlet")) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',)) - def test_login_failure_due_to_deactivated_user(self): - # type: () -> None + def test_login_failure_due_to_deactivated_user(self) -> None: self.mock_ldap.directory = { 'uid=hamlet,ou=users,dc=zulip,dc=com': { 'userPassword': 'testing' @@ -2086,8 +1960,8 @@ class TestLDAP(ZulipTestCase): self.assertIs(user_profile, None) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',)) - def test_login_success_when_user_does_not_exist_with_valid_subdomain(self): - # type: () -> None + def test_login_success_when_user_does_not_exist_with_valid_subdomain( + self) -> None: self.mock_ldap.directory = { 'uid=nonexisting,ou=users,dc=acme,dc=com': { 'cn': ['NonExisting', ], @@ -2106,57 +1980,53 @@ class TestLDAP(ZulipTestCase): self.assertEqual(user_profile.realm.string_id, 'zulip') class TestZulipLDAPUserPopulator(ZulipTestCase): - def test_authenticate(self): - # type: () -> None + def test_authenticate(self) -> None: backend = ZulipLDAPUserPopulator() result = backend.authenticate(self.example_email("hamlet"), 'testing') # type: ignore # complains that the function does not return any value! self.assertIs(result, None) class TestZulipAuthMixin(ZulipTestCase): - def test_get_user(self): - # type: () -> None + def test_get_user(self) -> None: backend = ZulipAuthMixin() result = backend.get_user(11111) self.assertIs(result, None) class TestPasswordAuthEnabled(ZulipTestCase): - def test_password_auth_enabled_for_ldap(self): - # type: () -> None + def test_password_auth_enabled_for_ldap(self) -> None: with self.settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',)): realm = Realm.objects.get(string_id='zulip') self.assertTrue(password_auth_enabled(realm)) class TestRequireEmailFormatUsernames(ZulipTestCase): - def test_require_email_format_usernames_for_ldap_with_append_domain(self): - # type: () -> None + def test_require_email_format_usernames_for_ldap_with_append_domain( + self) -> None: with self.settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',), LDAP_APPEND_DOMAIN="zulip.com"): realm = Realm.objects.get(string_id='zulip') self.assertFalse(require_email_format_usernames(realm)) - def test_require_email_format_usernames_for_ldap_with_email_attr(self): - # type: () -> None + def test_require_email_format_usernames_for_ldap_with_email_attr( + self) -> None: with self.settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',), LDAP_EMAIL_ATTR="email"): realm = Realm.objects.get(string_id='zulip') self.assertFalse(require_email_format_usernames(realm)) - def test_require_email_format_usernames_for_email_only(self): - # type: () -> None + def test_require_email_format_usernames_for_email_only(self) -> None: with self.settings(AUTHENTICATION_BACKENDS=('zproject.backends.EmailAuthBackend',)): realm = Realm.objects.get(string_id='zulip') self.assertTrue(require_email_format_usernames(realm)) - def test_require_email_format_usernames_for_email_and_ldap_with_email_attr(self): - # type: () -> None + def test_require_email_format_usernames_for_email_and_ldap_with_email_attr( + self) -> None: with self.settings(AUTHENTICATION_BACKENDS=('zproject.backends.EmailAuthBackend', 'zproject.backends.ZulipLDAPAuthBackend'), LDAP_EMAIL_ATTR="email"): realm = Realm.objects.get(string_id='zulip') self.assertFalse(require_email_format_usernames(realm)) - def test_require_email_format_usernames_for_email_and_ldap_with_append_email(self): - # type: () -> None + def test_require_email_format_usernames_for_email_and_ldap_with_append_email( + self) -> None: with self.settings(AUTHENTICATION_BACKENDS=('zproject.backends.EmailAuthBackend', 'zproject.backends.ZulipLDAPAuthBackend'), LDAP_APPEND_DOMAIN="zulip.com"): @@ -2164,8 +2034,7 @@ class TestRequireEmailFormatUsernames(ZulipTestCase): self.assertFalse(require_email_format_usernames(realm)) class TestMaybeSendToRegistration(ZulipTestCase): - def test_sso_only_when_preregistration_user_does_not_exist(self): - # type: () -> None + def test_sso_only_when_preregistration_user_does_not_exist(self) -> None: rf = RequestFactory() request = rf.get('/') request.session = {} @@ -2193,8 +2062,7 @@ class TestMaybeSendToRegistration(ZulipTestCase): self.assert_in_response('action="/accounts/register/"', result) self.assert_in_response('value="{0}" name="key"'.format(confirmation_key), result) - def test_sso_only_when_preregistration_user_exists(self): - # type: () -> None + def test_sso_only_when_preregistration_user_exists(self) -> None: rf = RequestFactory() request = rf.get('/') request.session = {} @@ -2224,8 +2092,7 @@ class TestMaybeSendToRegistration(ZulipTestCase): class TestAdminSetBackends(ZulipTestCase): - def test_change_enabled_backends(self): - # type: () -> None + def test_change_enabled_backends(self) -> None: # Log in as admin self.login(self.example_email("iago")) result = self.client_patch("/json/realm", { @@ -2235,8 +2102,7 @@ class TestAdminSetBackends(ZulipTestCase): self.assertFalse(password_auth_enabled(realm)) self.assertTrue(dev_auth_enabled(realm)) - def test_disable_all_backends(self): - # type: () -> None + def test_disable_all_backends(self) -> None: # Log in as admin self.login(self.example_email("iago")) result = self.client_patch("/json/realm", { @@ -2246,8 +2112,7 @@ class TestAdminSetBackends(ZulipTestCase): self.assertTrue(password_auth_enabled(realm)) self.assertTrue(dev_auth_enabled(realm)) - def test_supported_backends_only_updated(self): - # type: () -> None + def test_supported_backends_only_updated(self) -> None: # Log in as admin self.login(self.example_email("iago")) # Set some supported and unsupported backends @@ -2261,18 +2126,15 @@ class TestAdminSetBackends(ZulipTestCase): self.assertFalse(password_auth_enabled(realm)) class LoginEmailValidatorTestCase(ZulipTestCase): - def test_valid_email(self): - # type: () -> None + def test_valid_email(self) -> None: validate_login_email(self.example_email("hamlet")) - def test_invalid_email(self): - # type: () -> None + def test_invalid_email(self) -> None: with self.assertRaises(JsonableError): validate_login_email(u'hamlet') class LoginOrRegisterRemoteUserTestCase(ZulipTestCase): - def test_invalid_subdomain(self): - # type: () -> None + def test_invalid_subdomain(self) -> None: full_name = 'Hamlet' invalid_subdomain = True user_profile = self.example_user('hamlet') @@ -2287,8 +2149,7 @@ class LoginOrRegisterRemoteUserTestCase(ZulipTestCase): class LDAPBackendTest(ZulipTestCase): @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',)) - def test_non_existing_realm(self): - # type: () -> None + def test_non_existing_realm(self) -> None: email = self.example_email('hamlet') data = {'username': email, 'password': initial_password(email)} error_type = ZulipLDAPAuthBackend.REALM_IS_NONE_ERROR diff --git a/zerver/tests/test_events.py b/zerver/tests/test_events.py index 0bddc5b4b0..bedef8ab2e 100644 --- a/zerver/tests/test_events.py +++ b/zerver/tests/test_events.py @@ -378,8 +378,7 @@ class GetEventsTest(ZulipTestCase): email = user_profile.email self.login(email) - def get_message(apply_markdown, client_gravatar): - # type: (bool, bool) -> Dict[str, Any] + def get_message(apply_markdown: bool, client_gravatar: bool) -> Dict[str, Any]: result = self.tornado_call( get_events_backend, user_profile, @@ -463,11 +462,9 @@ class EventsRegisterTest(ZulipTestCase): ])), ]) - def do_test(self, action, event_types=None, - include_subscribers=True, state_change_expected=True, - client_gravatar=False, num_events=1): - # type: (Callable[[], Any], Optional[List[str]], bool, bool, bool, int) -> List[Dict[str, Any]] - + def do_test(self, action: Callable[[], Any], event_types: Optional[List[str]]=None, + include_subscribers: bool=True, state_change_expected: bool=True, + client_gravatar: bool=False, num_events: int=1) -> List[Dict[str, Any]]: ''' Make sure we have a clean slate of client descriptors for these tests. If we don't do this, then certain failures will only manifest when you @@ -2078,8 +2075,7 @@ class GetUnreadMsgsTest(ZulipTestCase): dict(user_ids_string=huddle_string), ) - def test_raw_unread_personal(self): - # type: () -> None + def test_raw_unread_personal(self) -> None: cordelia = self.example_user('cordelia') othello = self.example_user('othello') hamlet = self.example_user('hamlet') @@ -2110,8 +2106,7 @@ class GetUnreadMsgsTest(ZulipTestCase): dict(sender_id=cordelia.id), ) - def test_unread_msgs(self): - # type: () -> None + def test_unread_msgs(self) -> None: cordelia = self.example_user('cordelia') sender_id = cordelia.id sender_email = cordelia.email @@ -2385,8 +2380,7 @@ class ClientDescriptorsTest(ZulipTestCase): cordelia = self.example_user('cordelia') realm = hamlet.realm - def test_get_info(apply_markdown, client_gravatar): - # type: (bool, bool) -> None + def test_get_info(apply_markdown: bool, client_gravatar: bool) -> None: clear_client_event_queues_for_testing() queue_data = dict( diff --git a/zerver/tests/test_logging_handlers.py b/zerver/tests/test_logging_handlers.py index 8e0f9de925..9a74c80688 100644 --- a/zerver/tests/test_logging_handlers.py +++ b/zerver/tests/test_logging_handlers.py @@ -10,8 +10,7 @@ from django.test import RequestFactory, TestCase from django.utils.log import AdminEmailHandler from functools import wraps from mock import patch -if False: - from mypy_extensions import NoReturn +from mypy_extensions import NoReturn from typing import Any, Callable, Dict, Mapping, Optional, Text, Iterator from zerver.lib.request import JsonableError @@ -23,13 +22,11 @@ from zerver.worker.queue_processors import QueueProcessingWorker captured_request = None # type: Optional[HttpRequest] captured_exc_info = None -def capture_and_throw(domain=None): - # type: (Optional[Text]) -> Callable[[Callable[..., HttpResponse]], Callable[..., HttpResponse]] - def wrapper(view_func): - # type: (Callable[..., HttpResponse]) -> Callable[..., HttpResponse] +def capture_and_throw( + domain: Optional[Text]=None) -> Callable[[Callable[..., HttpResponse]], Callable[..., HttpResponse]]: + def wrapper(view_func: Callable[..., HttpResponse]) -> Callable[..., HttpResponse]: @wraps(view_func) - def wrapped_view(request, *args, **kwargs): - # type: (HttpRequest, *Any, **Any) -> NoReturn + def wrapped_view(request: HttpRequest, *args: Any, **kwargs: Any) -> NoReturn: global captured_request captured_request = request try: @@ -44,8 +41,7 @@ def capture_and_throw(domain=None): class AdminZulipHandlerTest(ZulipTestCase): logger = logging.getLogger('django') - def setUp(self): - # type: () -> None + def setUp(self) -> None: self.handler = AdminZulipHandler() # Prevent the exceptions we're going to raise from being printed # You may want to disable this when debugging tests @@ -56,19 +52,16 @@ class AdminZulipHandlerTest(ZulipTestCase): captured_request = None captured_exc_info = None - def tearDown(self): - # type: () -> None + def tearDown(self) -> None: settings.LOGGING_NOT_DISABLED = True - def get_admin_zulip_handler(self): - # type: () -> AdminZulipHandler + def get_admin_zulip_handler(self) -> AdminZulipHandler: return [ h for h in logging.getLogger('').handlers if isinstance(h, AdminZulipHandler) ][0] - def test_basic(self): - # type: () -> None + def test_basic(self) -> None: """A random exception passes happily through AdminZulipHandler""" handler = self.get_admin_zulip_handler() try: @@ -79,8 +72,7 @@ class AdminZulipHandlerTest(ZulipTestCase): 'message', {}, exc_info) handler.emit(record) - def run_handler(self, record): - # type: (logging.LogRecord) -> Dict[str, Any] + def run_handler(self, record: logging.LogRecord) -> Dict[str, Any]: with patch('zerver.logging_handlers.queue_json_publish') as patched_publish: self.handler.emit(record) patched_publish.assert_called_once() @@ -88,8 +80,7 @@ class AdminZulipHandlerTest(ZulipTestCase): self.assertIn("report", event) return event["report"] - def test_long_exception_request(self): - # type: () -> None + def test_long_exception_request(self) -> None: """A request with with no stack where report.getMessage() has newlines in it is handled properly""" email = self.example_email('hamlet') @@ -114,8 +105,7 @@ class AdminZulipHandlerTest(ZulipTestCase): self.assertEqual(report['stack_trace'], 'message\nmoremesssage\nmore') self.assertEqual(report['message'], 'message') - def test_request(self): - # type: () -> None + def test_request(self) -> None: """A normal request is handled properly""" email = self.example_email('hamlet') self.login(email) @@ -154,8 +144,7 @@ class AdminZulipHandlerTest(ZulipTestCase): self.assertIn("stack_trace", report) # Now simulate a DisallowedHost exception - def get_host_error(): - # type: () -> None + def get_host_error() -> None: raise Exception("Get Host Failure!") orig_get_host = record.request.get_host # type: ignore # this field is dynamically added record.request.get_host = get_host_error # type: ignore # this field is dynamically added @@ -207,8 +196,7 @@ class AdminZulipHandlerTest(ZulipTestCase): class LoggingConfigTest(TestCase): @staticmethod - def all_loggers(): - # type: () -> Iterator[logging.Logger] + def all_loggers() -> Iterator[logging.Logger]: # There is no documented API for enumerating the loggers; but the # internals of `logging` haven't changed in ages, so just use them. loggerDict = logging.Logger.manager.loggerDict # type: ignore @@ -217,8 +205,7 @@ class LoggingConfigTest(TestCase): continue yield logger - def test_django_emails_disabled(self): - # type: () -> None + def test_django_emails_disabled(self) -> None: for logger in self.all_loggers(): # The `handlers` attribute is undocumented, but see comment on # `all_loggers`. diff --git a/zerver/tests/test_push_notifications.py b/zerver/tests/test_push_notifications.py index 6efd5ba4fd..7575065747 100644 --- a/zerver/tests/test_push_notifications.py +++ b/zerver/tests/test_push_notifications.py @@ -510,8 +510,7 @@ class HandlePushNotificationTest(PushNotificationTest): "message_id %s and user_id %s" % (message_id, self.user_profile.id,)) - def test_user_message_soft_deactivated(self): - # type: () -> None + def test_user_message_soft_deactivated(self) -> None: """This simulates a condition that should only be an error if the user is not long-term idle; we fake it, though, in the sense that the user should not have received the message in the first place""" diff --git a/zerver/tests/test_signup.py b/zerver/tests/test_signup.py index de6bc1b999..599dc2eab2 100644 --- a/zerver/tests/test_signup.py +++ b/zerver/tests/test_signup.py @@ -321,8 +321,7 @@ class LoginTest(ZulipTestCase): self.assert_in_response("Please enter a correct email and password", result) self.assertIsNone(get_session_dict_user(self.client.session)) - def test_login_wrong_subdomain(self): - # type: () -> None + def test_login_wrong_subdomain(self) -> None: with patch("logging.warning") as mock_warning: result = self.login_with_return(self.mit_email("sipbtest"), "xxx") mock_warning.assert_called_once() @@ -331,8 +330,7 @@ class LoginTest(ZulipTestCase): "organization associated with this subdomain.", result) self.assertIsNone(get_session_dict_user(self.client.session)) - def test_login_invalid_subdomain(self): - # type: () -> None + def test_login_invalid_subdomain(self) -> None: result = self.login_with_return(self.example_email("hamlet"), "xxx", subdomain="invalid") self.assertEqual(result.status_code, 200)