Datasets:

zip
stringlengths
19
109
filename
stringlengths
4
185
contents
stringlengths
0
30.1M
type_annotations
sequencelengths
0
1.97k
type_annotation_starts
sequencelengths
0
1.97k
type_annotation_ends
sequencelengths
0
1.97k
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_attachments.py
# -*- coding: utf-8 -*- import mock from typing import Any from zerver.lib.attachments import user_attachments from zerver.lib.test_classes import ZulipTestCase from zerver.models import Attachment class AttachmentsTests(ZulipTestCase): def setUp(self) -> None: user_profile = self.example_user('cordelia') self.attachment = Attachment.objects.create( file_name='test.txt', path_id='foo/bar/test.txt', owner=user_profile) def test_list_by_user(self) -> None: user_profile = self.example_user('cordelia') self.login(user_profile.email) result = self.client_get('/json/attachments') self.assert_json_success(result) attachments = user_attachments(user_profile) self.assertEqual(result.json()['attachments'], attachments) def test_remove_attachment_exception(self) -> None: user_profile = self.example_user('cordelia') self.login(user_profile.email) with mock.patch('zerver.lib.attachments.delete_message_image', side_effect=Exception()): result = self.client_delete('/json/attachments/{id}'.format(id=self.attachment.id)) self.assert_json_error(result, "An error occurred while deleting the attachment. Please try again later.") @mock.patch('zerver.lib.attachments.delete_message_image') def test_remove_attachment(self, ignored: Any) -> None: user_profile = self.example_user('cordelia') self.login(user_profile.email) result = self.client_delete('/json/attachments/{id}'.format(id=self.attachment.id)) self.assert_json_success(result) attachments = user_attachments(user_profile) self.assertEqual(attachments, []) def test_list_another_user(self) -> None: user_profile = self.example_user('iago') self.login(user_profile.email) result = self.client_get('/json/attachments') self.assert_json_success(result) self.assertEqual(result.json()['attachments'], []) def test_remove_another_user(self) -> None: user_profile = self.example_user('iago') self.login(user_profile.email) result = self.client_delete('/json/attachments/{id}'.format(id=self.attachment.id)) self.assert_json_error(result, 'Invalid attachment') user_profile_to_remove = self.example_user('cordelia') attachments = user_attachments(user_profile_to_remove) self.assertEqual(attachments, [self.attachment.to_dict()]) def test_list_unauthenticated(self) -> None: result = self.client_get('/json/attachments') self.assert_json_error(result, 'Not logged in: API authentication or user session required', status_code=401) def test_delete_unauthenticated(self) -> None: result = self.client_delete('/json/attachments/{id}'.format(id=self.attachment.id)) self.assert_json_error(result, 'Not logged in: API authentication or user session required', status_code=401)
[ "Any" ]
[ 1376 ]
[ 1379 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_audit_log.py
from django.utils.timezone import now as timezone_now from zerver.lib.actions import do_create_user, do_deactivate_user, \ do_activate_user, do_reactivate_user, do_change_password, \ do_change_user_email, do_change_avatar_fields, do_change_bot_owner, \ do_regenerate_api_key, do_change_full_name, do_change_tos_version, \ bulk_add_subscriptions, bulk_remove_subscriptions, get_streams_traffic from zerver.lib.test_classes import ZulipTestCase from zerver.models import RealmAuditLog, get_client, get_realm from analytics.models import StreamCount from datetime import timedelta from django.contrib.auth.password_validation import validate_password import ujson class TestRealmAuditLog(ZulipTestCase): def test_user_activation(self) -> None: realm = get_realm('zulip') now = timezone_now() user = do_create_user('email', 'password', realm, 'full_name', 'short_name') do_deactivate_user(user) do_activate_user(user) do_deactivate_user(user) do_reactivate_user(user) self.assertEqual(RealmAuditLog.objects.filter(event_time__gte=now).count(), 5) event_types = list(RealmAuditLog.objects.filter( realm=realm, acting_user=None, modified_user=user, modified_stream=None, event_time__gte=now, event_time__lte=now+timedelta(minutes=60)) .order_by('event_time').values_list('event_type', flat=True)) self.assertEqual(event_types, [RealmAuditLog.USER_CREATED, RealmAuditLog.USER_DEACTIVATED, RealmAuditLog.USER_ACTIVATED, RealmAuditLog.USER_DEACTIVATED, RealmAuditLog.USER_REACTIVATED]) def test_change_password(self) -> None: now = timezone_now() user = self.example_user('hamlet') password = 'test1' do_change_password(user, password) self.assertEqual(RealmAuditLog.objects.filter(event_type=RealmAuditLog.USER_PASSWORD_CHANGED, event_time__gte=now).count(), 1) self.assertIsNone(validate_password(password, user)) def test_change_email(self) -> None: now = timezone_now() user = self.example_user('hamlet') email = 'test@example.com' do_change_user_email(user, email) self.assertEqual(RealmAuditLog.objects.filter(event_type=RealmAuditLog.USER_EMAIL_CHANGED, event_time__gte=now).count(), 1) self.assertEqual(email, user.email) # Test the RealmAuditLog stringification audit_entry = RealmAuditLog.objects.get(event_type=RealmAuditLog.USER_EMAIL_CHANGED, event_time__gte=now) self.assertTrue(str(audit_entry).startswith("<RealmAuditLog: <UserProfile: test@example.com <Realm: zulip 1>> user_email_changed ")) def test_change_avatar_source(self) -> None: now = timezone_now() user = self.example_user('hamlet') avatar_source = u'G' do_change_avatar_fields(user, avatar_source) self.assertEqual(RealmAuditLog.objects.filter(event_type=RealmAuditLog.USER_AVATAR_SOURCE_CHANGED, event_time__gte=now).count(), 1) self.assertEqual(avatar_source, user.avatar_source) def test_change_full_name(self) -> None: start = timezone_now() new_name = 'George Hamletovich' self.login(self.example_email("iago")) req = dict(full_name=ujson.dumps(new_name)) result = self.client_patch('/json/users/{}'.format(self.example_user("hamlet").id), req) self.assertTrue(result.status_code == 200) query = RealmAuditLog.objects.filter(event_type=RealmAuditLog.USER_FULL_NAME_CHANGED, event_time__gte=start) self.assertEqual(query.count(), 1) def test_change_tos_version(self) -> None: now = timezone_now() user = self.example_user("hamlet") tos_version = 'android' do_change_tos_version(user, tos_version) self.assertEqual(RealmAuditLog.objects.filter(event_type=RealmAuditLog.USER_TOS_VERSION_CHANGED, event_time__gte=now).count(), 1) self.assertEqual(tos_version, user.tos_version) def test_change_bot_owner(self) -> None: now = timezone_now() admin = self.example_user('iago') bot = self.notification_bot() bot_owner = self.example_user('hamlet') do_change_bot_owner(bot, bot_owner, admin) self.assertEqual(RealmAuditLog.objects.filter(event_type=RealmAuditLog.USER_BOT_OWNER_CHANGED, event_time__gte=now).count(), 1) self.assertEqual(bot_owner, bot.bot_owner) def test_regenerate_api_key(self) -> None: now = timezone_now() user = self.example_user('hamlet') do_regenerate_api_key(user, user) self.assertEqual(RealmAuditLog.objects.filter(event_type=RealmAuditLog.USER_API_KEY_CHANGED, event_time__gte=now).count(), 1) self.assertTrue(user.api_key) def test_get_streams_traffic(self) -> None: realm = get_realm('zulip') stream_name = 'whatever' stream = self.make_stream(stream_name, realm) stream_ids = {stream.id} result = get_streams_traffic(stream_ids) self.assertEqual(result, {}) StreamCount.objects.create( realm=realm, stream=stream, property='messages_in_stream:is_bot:day', end_time=timezone_now(), value=999, ) result = get_streams_traffic(stream_ids) self.assertEqual(result, {stream.id: 999}) def test_subscriptions(self) -> None: now = timezone_now() user = [self.example_user('hamlet')] stream = [self.make_stream('test_stream')] bulk_add_subscriptions(stream, user) subscription_creation_logs = RealmAuditLog.objects.filter(event_type=RealmAuditLog.SUBSCRIPTION_CREATED, event_time__gte=now) self.assertEqual(subscription_creation_logs.count(), 1) self.assertEqual(subscription_creation_logs[0].modified_stream.id, stream[0].id) self.assertEqual(subscription_creation_logs[0].modified_user, user[0]) bulk_remove_subscriptions(user, stream, get_client("website")) subscription_deactivation_logs = RealmAuditLog.objects.filter(event_type=RealmAuditLog.SUBSCRIPTION_DEACTIVATED, event_time__gte=now) self.assertEqual(subscription_deactivation_logs.count(), 1) self.assertEqual(subscription_deactivation_logs[0].modified_stream.id, stream[0].id) self.assertEqual(subscription_deactivation_logs[0].modified_user, user[0])
[]
[]
[]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_auth_backends.py
# -*- coding: utf-8 -*- from django.conf import settings from django.core import mail from django.http import HttpResponse from django.test import override_settings from django_auth_ldap.backend import _LDAPUser from django.contrib.auth import authenticate from django.test.client import RequestFactory from django.utils.timezone import now as timezone_now from typing import Any, Callable, Dict, List, Optional, Tuple from builtins import object from oauth2client.crypt import AppIdentityError from django.core import signing from django.urls import reverse import httpretty import os import sys import jwt import mock import re import time import datetime from zerver.forms import HomepageForm from zerver.lib.actions import ( do_deactivate_realm, do_deactivate_user, do_reactivate_realm, do_reactivate_user, do_set_realm_authentication_methods, ensure_stream, validate_email, ) from zerver.lib.mobile_auth_otp import otp_decrypt_api_key from zerver.lib.validator import validate_login_email, \ check_bool, check_dict_only, check_string, Validator from zerver.lib.request import JsonableError from zerver.lib.users import get_all_api_keys from zerver.lib.initial_password import initial_password from zerver.lib.sessions import get_session_dict_user from zerver.lib.test_classes import ( ZulipTestCase, ) from zerver.lib.test_helpers import POSTRequestMock, HostRequestMock from zerver.models import \ get_realm, email_to_username, UserProfile, \ PreregistrationUser, Realm, get_user, MultiuseInvite from zerver.signals import JUST_CREATED_THRESHOLD from confirmation.models import Confirmation, confirmation_url, create_confirmation_link from zproject.backends import ZulipDummyBackend, EmailAuthBackend, \ GoogleMobileOauth2Backend, ZulipRemoteUserBackend, ZulipLDAPAuthBackend, \ ZulipLDAPUserPopulator, DevAuthBackend, GitHubAuthBackend, ZulipAuthMixin, \ dev_auth_enabled, password_auth_enabled, github_auth_enabled, \ require_email_format_usernames, AUTH_BACKEND_NAME_MAP, \ ZulipLDAPConfigurationError, generate_dev_ldap_dir from zerver.views.auth import (maybe_send_to_registration, login_or_register_remote_user, _subdomain_token_salt) from version import ZULIP_VERSION from social_core.exceptions import AuthFailed, AuthStateForbidden from social_django.strategy import DjangoStrategy from social_django.storage import BaseDjangoStorage from social_core.backends.github import GithubOrganizationOAuth2, GithubTeamOAuth2, \ GithubOAuth2 import json import urllib from http.cookies import SimpleCookie import ujson from zerver.lib.test_helpers import MockLDAP, load_subdomain_token class AuthBackendTest(ZulipTestCase): def get_username(self, email_to_username: Optional[Callable[[str], str]]=None) -> str: username = self.example_email('hamlet') if email_to_username is not None: username = email_to_username(self.example_email('hamlet')) return username def verify_backend(self, backend: Any, good_kwargs: Optional[Dict[str, Any]]=None, bad_kwargs: Optional[Dict[str, Any]]=None) -> None: user_profile = self.example_user('hamlet') assert good_kwargs is not None # If bad_kwargs was specified, verify auth fails in that case if bad_kwargs is not None: self.assertIsNone(backend.authenticate(**bad_kwargs)) # Verify auth works result = backend.authenticate(**good_kwargs) self.assertEqual(user_profile, result) # Verify auth fails with a deactivated user do_deactivate_user(user_profile) self.assertIsNone(backend.authenticate(**good_kwargs)) # Reactivate the user and verify auth works again do_reactivate_user(user_profile) result = backend.authenticate(**good_kwargs) self.assertEqual(user_profile, result) # Verify auth fails with a deactivated realm do_deactivate_realm(user_profile.realm) self.assertIsNone(backend.authenticate(**good_kwargs)) # Verify auth works again after reactivating the realm do_reactivate_realm(user_profile.realm) result = backend.authenticate(**good_kwargs) self.assertEqual(user_profile, result) # ZulipDummyBackend isn't a real backend so the remainder # doesn't make sense for it if isinstance(backend, ZulipDummyBackend): return # Verify auth fails if the auth backend is disabled on server with self.settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipDummyBackend',)): self.assertIsNone(backend.authenticate(**good_kwargs)) # Verify auth fails if the auth backend is disabled for the realm for backend_name in AUTH_BACKEND_NAME_MAP.keys(): if isinstance(backend, AUTH_BACKEND_NAME_MAP[backend_name]): break index = getattr(user_profile.realm.authentication_methods, backend_name).number user_profile.realm.authentication_methods.set_bit(index, False) user_profile.realm.save() if 'realm' in good_kwargs: # Because this test is a little unfaithful to the ordering # (i.e. we fetched the realm object before this function # was called, when in fact it should be fetched after we # changed the allowed authentication methods), we need to # propagate the changes we just made to the actual realm # object in good_kwargs. good_kwargs['realm'] = user_profile.realm self.assertIsNone(backend.authenticate(**good_kwargs)) user_profile.realm.authentication_methods.set_bit(index, True) user_profile.realm.save() def test_dummy_backend(self) -> None: realm = get_realm("zulip") username = self.get_username() self.verify_backend(ZulipDummyBackend(), good_kwargs=dict(username=username, realm=realm, use_dummy_backend=True), bad_kwargs=dict(username=username, realm=realm, use_dummy_backend=False)) def setup_subdomain(self, user_profile: UserProfile) -> None: realm = user_profile.realm realm.string_id = 'zulip' realm.save() def test_email_auth_backend(self) -> None: username = self.get_username() user_profile = self.example_user('hamlet') password = "testpassword" user_profile.set_password(password) user_profile.save() with mock.patch('zproject.backends.email_auth_enabled', return_value=False), \ mock.patch('zproject.backends.password_auth_enabled', return_value=True): return_data = {} # type: Dict[str, bool] user = EmailAuthBackend().authenticate(self.example_email('hamlet'), realm=get_realm("zulip"), password=password, return_data=return_data) self.assertEqual(user, None) self.assertTrue(return_data['email_auth_disabled']) self.verify_backend(EmailAuthBackend(), good_kwargs=dict(password=password, username=username, realm=get_realm('zulip'), return_data=dict()), bad_kwargs=dict(password=password, username=username, realm=get_realm('zephyr'), return_data=dict())) self.verify_backend(EmailAuthBackend(), good_kwargs=dict(password=password, username=username, realm=get_realm('zulip'), return_data=dict()), bad_kwargs=dict(password=password, username=username, realm=None, return_data=dict())) def test_email_auth_backend_disabled_password_auth(self) -> None: user_profile = self.example_user('hamlet') password = "testpassword" user_profile.set_password(password) user_profile.save() # Verify if a realm has password auth disabled, correct password is rejected with mock.patch('zproject.backends.password_auth_enabled', return_value=False): self.assertIsNone(EmailAuthBackend().authenticate(self.example_email('hamlet'), password, realm=get_realm("zulip"))) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipDummyBackend',)) def test_no_backend_enabled(self) -> None: result = self.client_get('/login/') self.assert_in_success_response(["No authentication backends are enabled"], result) result = self.client_get('/register/') self.assert_in_success_response(["No authentication backends are enabled"], result) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.GoogleMobileOauth2Backend',)) def test_any_backend_enabled(self) -> None: # testing to avoid false error messages. result = self.client_get('/login/') self.assert_not_in_success_response(["No authentication backends are enabled"], result) result = self.client_get('/register/') self.assert_not_in_success_response(["No authentication backends are enabled"], result) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.GoogleMobileOauth2Backend',)) def test_google_backend(self) -> None: user_profile = self.example_user('hamlet') email = user_profile.email backend = GoogleMobileOauth2Backend() payload = dict(email_verified=True, email=email) with mock.patch('apiclient.sample_tools.client.verify_id_token', return_value=payload): self.verify_backend(backend, good_kwargs=dict(realm=get_realm("zulip")), bad_kwargs=dict(realm=get_realm('invalid'))) # Verify valid_attestation parameter is set correctly unverified_payload = dict(email_verified=False) with mock.patch('apiclient.sample_tools.client.verify_id_token', return_value=unverified_payload): ret = dict() # type: Dict[str, str] result = backend.authenticate(realm=get_realm("zulip"), return_data=ret) self.assertIsNone(result) self.assertFalse(ret["valid_attestation"]) nonexistent_user_payload = dict(email_verified=True, email="invalid@zulip.com") with mock.patch('apiclient.sample_tools.client.verify_id_token', return_value=nonexistent_user_payload): ret = dict() result = backend.authenticate(realm=get_realm("zulip"), return_data=ret) self.assertIsNone(result) self.assertTrue(ret["valid_attestation"]) with mock.patch('apiclient.sample_tools.client.verify_id_token', side_effect=AppIdentityError): ret = dict() result = backend.authenticate(realm=get_realm("zulip"), return_data=ret) self.assertIsNone(result) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',)) def test_ldap_backend(self) -> None: user_profile = self.example_user('hamlet') email = user_profile.email password = "test_password" self.setup_subdomain(user_profile) username = self.get_username() backend = ZulipLDAPAuthBackend() # Test LDAP auth fails when LDAP server rejects password with mock.patch('django_auth_ldap.backend._LDAPUser._authenticate_user_dn', side_effect=_LDAPUser.AuthenticationFailed("Failed")), ( mock.patch('django_auth_ldap.backend._LDAPUser._check_requirements')), ( mock.patch('django_auth_ldap.backend._LDAPUser.attrs', return_value=dict(full_name=['Hamlet']))): self.assertIsNone(backend.authenticate(email, password, realm=get_realm("zulip"))) with mock.patch('django_auth_ldap.backend._LDAPUser._authenticate_user_dn'), ( mock.patch('django_auth_ldap.backend._LDAPUser._check_requirements')), ( mock.patch('django_auth_ldap.backend._LDAPUser.attrs', return_value=dict(full_name=['Hamlet']))): self.verify_backend(backend, bad_kwargs=dict(username=username, password=password, realm=get_realm('zephyr')), good_kwargs=dict(username=username, password=password, realm=get_realm('zulip'))) self.verify_backend(backend, bad_kwargs=dict(username=username, password=password, realm=get_realm('acme')), good_kwargs=dict(username=username, password=password, realm=get_realm('zulip'))) def test_devauth_backend(self) -> None: self.verify_backend(DevAuthBackend(), good_kwargs=dict(dev_auth_username=self.get_username(), realm=get_realm("zulip")), bad_kwargs=dict(dev_auth_username=self.get_username(), realm=get_realm("invalid"))) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipRemoteUserBackend',)) def test_remote_user_backend(self) -> None: username = self.get_username() self.verify_backend(ZulipRemoteUserBackend(), good_kwargs=dict(remote_user=username, realm=get_realm('zulip')), bad_kwargs=dict(remote_user=username, realm=get_realm('zephyr'))) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipRemoteUserBackend',)) def test_remote_user_backend_invalid_realm(self) -> None: username = self.get_username() self.verify_backend(ZulipRemoteUserBackend(), good_kwargs=dict(remote_user=username, realm=get_realm('zulip')), bad_kwargs=dict(remote_user=username, realm=None)) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipRemoteUserBackend',)) @override_settings(SSO_APPEND_DOMAIN='zulip.com') 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, realm=get_realm("zulip")), bad_kwargs=dict(remote_user=username, realm=get_realm('zephyr'))) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.GitHubAuthBackend',)) def test_github_backend(self) -> None: user = self.example_user('hamlet') token_data_dict = { 'access_token': 'foobar', 'token_type': 'bearer' } account_data_dict = dict(email=user.email, name=user.full_name) email_data = [ dict(email=account_data_dict["email"], verified=True, primary=True), dict(email="nonprimary@example.com", verified=True), dict(email="ignored@example.com", verified=False), ] httpretty.enable() httpretty.register_uri( httpretty.POST, "https://github.com/login/oauth/access_token", match_querystring=False, status=200, body=json.dumps(token_data_dict)) httpretty.register_uri( httpretty.GET, "https://api.github.com/user", status=200, body=json.dumps(account_data_dict) ) httpretty.register_uri( httpretty.GET, "https://api.github.com/user/emails", status=200, body=json.dumps(email_data) ) backend = GitHubAuthBackend() backend.strategy = DjangoStrategy(storage=BaseDjangoStorage()) orig_authenticate = GitHubAuthBackend.authenticate def patched_authenticate(*args: Any, **kwargs: Any) -> Any: if 'subdomain' in kwargs: backend.strategy.session_set("subdomain", kwargs["subdomain"]) del kwargs['subdomain'] result = orig_authenticate(backend, *args, **kwargs) return result backend.authenticate = patched_authenticate good_kwargs = dict(backend=backend, strategy=backend.strategy, storage=backend.strategy.storage, response=token_data_dict, subdomain='zulip') bad_kwargs = dict(subdomain='acme') with mock.patch('zerver.views.auth.redirect_and_log_into_subdomain', return_value=user): self.verify_backend(backend, good_kwargs=good_kwargs, bad_kwargs=bad_kwargs) bad_kwargs['subdomain'] = "zephyr" self.verify_backend(backend, good_kwargs=good_kwargs, bad_kwargs=bad_kwargs) backend.authenticate = orig_authenticate httpretty.disable() class ResponseMock: def __init__(self, status_code: int, data: Any) -> None: self.status_code = status_code self.data = data def json(self) -> str: return self.data @property def text(self) -> str: return "Response text" class GitHubAuthBackendTest(ZulipTestCase): def setUp(self) -> None: self.user_profile = self.example_user('hamlet') self.email = self.user_profile.email self.name = 'Hamlet' self.backend = GitHubAuthBackend() self.backend.strategy = DjangoStrategy(storage=BaseDjangoStorage()) self.user_profile.backend = self.backend # This is a workaround for the fact that Python social auth # caches the set of authentication backends that are enabled # the first time that `social_django.utils` is imported. See # https://github.com/python-social-auth/social-app-django/pull/162 # for details. from social_core.backends.utils import load_backends load_backends(settings.AUTHENTICATION_BACKENDS, force_load=True) def github_oauth2_test(self, account_data_dict: Dict[str, str], *, subdomain: Optional[str]=None, mobile_flow_otp: Optional[str]=None, is_signup: Optional[str]=None, email_data: Optional[List[Dict[str, Any]]]=None, next: str='') -> HttpResponse: url = "/accounts/login/social/github" params = {} headers = {} if subdomain is not None: headers['HTTP_HOST'] = subdomain + ".testserver" if mobile_flow_otp is not None: params['mobile_flow_otp'] = mobile_flow_otp headers['HTTP_USER_AGENT'] = "ZulipAndroid" if is_signup is not None: url = "/accounts/register/social/github" params['next'] = next if len(params) > 0: url += "?%s" % (urllib.parse.urlencode(params)) result = self.client_get(url, **headers) expected_result_url_prefix = 'http://testserver/login/github/' if settings.SOCIAL_AUTH_SUBDOMAIN is not None: expected_result_url_prefix = ('http://%s.testserver/login/github/' % settings.SOCIAL_AUTH_SUBDOMAIN) if result.status_code != 302 or not result.url.startswith(expected_result_url_prefix): return result result = self.client_get(result.url, **headers) self.assertEqual(result.status_code, 302) assert 'https://github.com/login/oauth/authorize' in result.url self.client.cookies = result.cookies # Next, the browser requests result["Location"], and gets # redirected back to /complete/github. token_data_dict = { 'access_token': 'foobar', 'token_type': 'bearer' } if not email_data: # Keeping a verified email before the primary email makes sure # get_verified_emails puts the primary email at the start of the # email list returned as social_associate_user_helper assumes the # first email as the primary email. email_data = [ dict(email="notprimary@example.com", verified=True), dict(email=account_data_dict["email"], verified=True, primary=True), dict(email="ignored@example.com", verified=False), ] # We register callbacks for the key URLs on github.com that # /complete/github will call httpretty.enable() httpretty.register_uri( httpretty.POST, "https://github.com/login/oauth/access_token", match_querystring=False, status=200, body=json.dumps(token_data_dict)) httpretty.register_uri( httpretty.GET, "https://api.github.com/user", status=200, body=json.dumps(account_data_dict) ) httpretty.register_uri( httpretty.GET, "https://api.github.com/user/emails", status=200, body=json.dumps(email_data) ) parsed_url = urllib.parse.urlparse(result.url) csrf_state = urllib.parse.parse_qs(parsed_url.query)['state'] result = self.client_get("/complete/github/", dict(state=csrf_state), **headers) httpretty.disable() return result @override_settings(SOCIAL_AUTH_GITHUB_KEY=None) def test_github_oauth2_no_key(self) -> None: account_data_dict = dict(email=self.email, name=self.name) result = self.github_oauth2_test(account_data_dict, subdomain='zulip', next='/user_uploads/image') self.assertEqual(result.status_code, 302) self.assertEqual(result.url, "/config-error/github") def test_github_oauth2_success(self) -> None: account_data_dict = dict(email=self.email, name=self.name) result = self.github_oauth2_test(account_data_dict, subdomain='zulip', next='/user_uploads/image') data = load_subdomain_token(result) self.assertEqual(data['email'], self.example_email("hamlet")) self.assertEqual(data['name'], 'Hamlet') self.assertEqual(data['subdomain'], 'zulip') self.assertEqual(data['next'], '/user_uploads/image') self.assertEqual(result.status_code, 302) parsed_url = urllib.parse.urlparse(result.url) uri = "{}://{}{}".format(parsed_url.scheme, parsed_url.netloc, parsed_url.path) self.assertTrue(uri.startswith('http://zulip.testserver/accounts/login/subdomain/')) @override_settings(SOCIAL_AUTH_SUBDOMAIN=None) def test_github_when_social_auth_subdomain_is_not_set(self) -> None: account_data_dict = dict(email=self.email, name=self.name) result = self.github_oauth2_test(account_data_dict, subdomain='zulip', next='/user_uploads/image') data = load_subdomain_token(result) self.assertEqual(data['email'], self.example_email("hamlet")) self.assertEqual(data['name'], 'Hamlet') self.assertEqual(data['subdomain'], 'zulip') self.assertEqual(data['next'], '/user_uploads/image') self.assertEqual(result.status_code, 302) parsed_url = urllib.parse.urlparse(result.url) uri = "{}://{}{}".format(parsed_url.scheme, parsed_url.netloc, parsed_url.path) self.assertTrue(uri.startswith('http://zulip.testserver/accounts/login/subdomain/')) def test_github_oauth2_email_not_verified(self) -> None: account_data_dict = dict(email=self.email, name=self.name) email_data = [ dict(email=account_data_dict["email"], verified=False, primary=True), ] with mock.patch('logging.warning') as mock_warning: result = self.github_oauth2_test(account_data_dict, subdomain='zulip', email_data=email_data) self.assertEqual(result.status_code, 302) self.assertEqual(result.url, "/login/") mock_warning.assert_called_once_with("Social auth (GitHub) failed " "because user has no verified emails") @override_settings(SOCIAL_AUTH_GITHUB_TEAM_ID='zulip-webapp') def test_github_oauth2_github_team_not_member_failed(self) -> None: account_data_dict = dict(email=self.email, name=self.name) with mock.patch('social_core.backends.github.GithubTeamOAuth2.user_data', side_effect=AuthFailed('Not found')), \ mock.patch('logging.info') as mock_info: result = self.github_oauth2_test(account_data_dict, subdomain='zulip') self.assertEqual(result.status_code, 302) self.assertEqual(result.url, "/login/") mock_info.assert_called_once_with("GitHub user is not member of required team") @override_settings(SOCIAL_AUTH_GITHUB_TEAM_ID='zulip-webapp') def test_github_oauth2_github_team_member_success(self) -> None: account_data_dict = dict(email=self.email, name=self.name) with mock.patch('social_core.backends.github.GithubTeamOAuth2.user_data', return_value=account_data_dict): result = self.github_oauth2_test(account_data_dict, subdomain='zulip') data = load_subdomain_token(result) self.assertEqual(data['email'], self.example_email("hamlet")) self.assertEqual(data['name'], 'Hamlet') self.assertEqual(data['subdomain'], 'zulip') @override_settings(SOCIAL_AUTH_GITHUB_ORG_NAME='Zulip') def test_github_oauth2_github_organization_not_member_failed(self) -> None: account_data_dict = dict(email=self.email, name=self.name) with mock.patch('social_core.backends.github.GithubOrganizationOAuth2.user_data', side_effect=AuthFailed('Not found')), \ mock.patch('logging.info') as mock_info: result = self.github_oauth2_test(account_data_dict, subdomain='zulip') self.assertEqual(result.status_code, 302) self.assertEqual(result.url, "/login/") mock_info.assert_called_once_with("GitHub user is not member of required organization") @override_settings(SOCIAL_AUTH_GITHUB_ORG_NAME='Zulip') def test_github_oauth2_github_organization_member_success(self) -> None: account_data_dict = dict(email=self.email, name=self.name) with mock.patch('social_core.backends.github.GithubOrganizationOAuth2.user_data', return_value=account_data_dict): result = self.github_oauth2_test(account_data_dict, subdomain='zulip') data = load_subdomain_token(result) self.assertEqual(data['email'], self.example_email("hamlet")) self.assertEqual(data['name'], 'Hamlet') self.assertEqual(data['subdomain'], 'zulip') def test_github_oauth2_deactivated_user(self) -> None: user_profile = self.example_user("hamlet") do_deactivate_user(user_profile) account_data_dict = dict(email=self.email, name=self.name) result = self.github_oauth2_test(account_data_dict, subdomain='zulip') self.assertEqual(result.status_code, 302) self.assertEqual(result.url, "/login/") # TODO: verify whether we provide a clear error message def test_github_oauth2_invalid_realm(self) -> None: account_data_dict = dict(email=self.email, name=self.name) with mock.patch('zerver.middleware.get_realm', return_value=get_realm("zulip")): # This mock.patch case somewhat hackishly arranges it so # that we switch realms halfway through the test result = self.github_oauth2_test(account_data_dict, subdomain='invalid', next='/user_uploads/image') self.assertEqual(result.status_code, 302) self.assertEqual(result.url, "/accounts/login/?subdomain=1") def test_github_oauth2_invalid_email(self) -> None: account_data_dict = dict(email="invalid", name=self.name) result = self.github_oauth2_test(account_data_dict, subdomain='zulip', next='/user_uploads/image') self.assertEqual(result.status_code, 302) self.assertEqual(result.url, "/login/?next=/user_uploads/image") def test_user_cannot_log_into_nonexisting_realm(self) -> None: account_data_dict = dict(email=self.email, name=self.name) result = self.github_oauth2_test(account_data_dict, subdomain='nonexistent') self.assert_in_success_response(["There is no Zulip organization hosted at this subdomain."], result) def test_user_cannot_log_into_wrong_subdomain(self) -> None: account_data_dict = dict(email=self.email, name=self.name) result = self.github_oauth2_test(account_data_dict, subdomain='zephyr') self.assertTrue(result.url.startswith("http://zephyr.testserver/accounts/login/subdomain/")) result = self.client_get(result.url.replace('http://zephyr.testserver', ''), subdomain="zephyr") self.assert_in_success_response(['Your email address, hamlet@zulip.com, is not in one of the domains ', 'that are allowed to register for accounts in this organization.'], result) def test_github_oauth2_mobile_success(self) -> None: mobile_flow_otp = '1234abcd' * 8 account_data_dict = dict(email=self.email, name='Full Name') self.assertEqual(len(mail.outbox), 0) self.user_profile.date_joined = timezone_now() - datetime.timedelta(seconds=JUST_CREATED_THRESHOLD + 1) self.user_profile.save() with self.settings(SEND_LOGIN_EMAILS=True): # Verify that the right thing happens with an invalid-format OTP result = self.github_oauth2_test(account_data_dict, subdomain='zulip', mobile_flow_otp="1234") self.assert_json_error(result, "Invalid OTP") result = self.github_oauth2_test(account_data_dict, subdomain='zulip', mobile_flow_otp="invalido" * 8) self.assert_json_error(result, "Invalid OTP") # Now do it correctly result = self.github_oauth2_test(account_data_dict, subdomain='zulip', mobile_flow_otp=mobile_flow_otp) self.assertEqual(result.status_code, 302) redirect_url = result['Location'] parsed_url = urllib.parse.urlparse(redirect_url) query_params = urllib.parse.parse_qs(parsed_url.query) self.assertEqual(parsed_url.scheme, 'zulip') self.assertEqual(query_params["realm"], ['http://zulip.testserver']) self.assertEqual(query_params["email"], [self.example_email("hamlet")]) encrypted_api_key = query_params["otp_encrypted_api_key"][0] hamlet_api_keys = get_all_api_keys(self.example_user('hamlet')) self.assertIn(otp_decrypt_api_key(encrypted_api_key, mobile_flow_otp), hamlet_api_keys) self.assertEqual(len(mail.outbox), 1) self.assertIn('Zulip on Android', mail.outbox[0].body) def test_github_oauth2_registration_existing_account(self) -> None: """If the user already exists, signup flow just logs them in""" email = "hamlet@zulip.com" name = 'Full Name' account_data_dict = dict(email=email, name=name) result = self.github_oauth2_test(account_data_dict, subdomain='zulip', is_signup='1') data = load_subdomain_token(result) self.assertEqual(data['email'], self.example_email("hamlet")) self.assertEqual(data['name'], 'Full Name') self.assertEqual(data['subdomain'], 'zulip') self.assertEqual(result.status_code, 302) parsed_url = urllib.parse.urlparse(result.url) uri = "{}://{}{}".format(parsed_url.scheme, parsed_url.netloc, parsed_url.path) self.assertTrue(uri.startswith('http://zulip.testserver/accounts/login/subdomain/')) hamlet = self.example_user("hamlet") # Name wasn't changed at all self.assertEqual(hamlet.full_name, "King Hamlet") def test_github_oauth2_registration(self) -> None: """If the user doesn't exist yet, GitHub auth can be used to register an account""" email = "newuser@zulip.com" name = 'Full Name' realm = get_realm("zulip") account_data_dict = dict(email=email, name=name) result = self.github_oauth2_test(account_data_dict, subdomain='zulip', is_signup='1') data = load_subdomain_token(result) self.assertEqual(data['email'], email) self.assertEqual(data['name'], name) self.assertEqual(data['subdomain'], 'zulip') self.assertEqual(result.status_code, 302) parsed_url = urllib.parse.urlparse(result.url) uri = "{}://{}{}".format(parsed_url.scheme, parsed_url.netloc, parsed_url.path) self.assertTrue(uri.startswith('http://zulip.testserver/accounts/login/subdomain/')) result = self.client_get(result.url) self.assertEqual(result.status_code, 302) confirmation = Confirmation.objects.all().first() confirmation_key = confirmation.confirmation_key self.assertIn('do_confirm/' + confirmation_key, result.url) result = self.client_get(result.url) self.assert_in_response('action="/accounts/register/"', result) data = {"from_confirmation": "1", "full_name": name, "key": confirmation_key} result = self.client_post('/accounts/register/', data) self.assert_in_response("You're almost there", result) # Verify that the user is asked for name but not password self.assert_not_in_success_response(['id_password'], result) self.assert_in_success_response(['id_full_name'], result) # Click confirm registration button. result = self.client_post( '/accounts/register/', {'full_name': name, 'key': confirmation_key, 'terms': True}) self.assertEqual(result.status_code, 302) user_profile = get_user(email, realm) self.assertEqual(get_session_dict_user(self.client.session), user_profile.id) def test_github_oauth2_registration_without_is_signup(self) -> None: """If the user doesn't exist yet, GitHub auth can be used to register an account""" email = "newuser@zulip.com" name = 'Full Name' account_data_dict = dict(email=email, name=name) result = self.github_oauth2_test(account_data_dict, subdomain='zulip') self.assertEqual(result.status_code, 302) data = load_subdomain_token(result) self.assertEqual(data['email'], email) self.assertEqual(data['name'], name) self.assertEqual(data['subdomain'], 'zulip') self.assertEqual(result.status_code, 302) parsed_url = urllib.parse.urlparse(result.url) uri = "{}://{}{}".format(parsed_url.scheme, parsed_url.netloc, parsed_url.path) self.assertTrue(uri.startswith('http://zulip.testserver/accounts/login/subdomain/')) result = self.client_get(result.url) self.assertEqual(result.status_code, 200) self.assert_in_response("No account found for newuser@zulip.com.", result) def test_github_oauth2_registration_without_is_signup_closed_realm(self) -> None: """If the user doesn't exist yet in closed realm, give an error""" email = "nonexisting@phantom.com" name = 'Full Name' account_data_dict = dict(email=email, name=name) result = self.github_oauth2_test(account_data_dict, subdomain='zulip') self.assertEqual(result.status_code, 302) data = load_subdomain_token(result) self.assertEqual(data['email'], email) self.assertEqual(data['name'], name) self.assertEqual(data['subdomain'], 'zulip') self.assertEqual(result.status_code, 302) parsed_url = urllib.parse.urlparse(result.url) uri = "{}://{}{}".format(parsed_url.scheme, parsed_url.netloc, parsed_url.path) self.assertTrue(uri.startswith('http://zulip.testserver/accounts/login/subdomain/')) result = self.client_get(result.url) self.assertEqual(result.status_code, 200) self.assert_in_response('action="/register/"', result) self.assert_in_response('Your email address, {}, is not ' 'in one of the domains that are allowed to register ' 'for accounts in this organization.'.format(email), result) def test_github_complete(self) -> None: with mock.patch('social_core.backends.oauth.BaseOAuth2.process_error', side_effect=AuthFailed('Not found')): result = self.client_get(reverse('social:complete', args=['github'])) self.assertEqual(result.status_code, 302) self.assertIn('login', result.url) def test_github_complete_when_base_exc_is_raised(self) -> None: with mock.patch('social_core.backends.oauth.BaseOAuth2.auth_complete', side_effect=AuthStateForbidden('State forbidden')), \ mock.patch('zproject.backends.logging.warning'): result = self.client_get(reverse('social:complete', args=['github'])) self.assertEqual(result.status_code, 302) self.assertIn('login', result.url) def test_github_auth_enabled(self) -> None: with self.settings(AUTHENTICATION_BACKENDS=('zproject.backends.GitHubAuthBackend',)): self.assertTrue(github_auth_enabled()) class GoogleOAuthTest(ZulipTestCase): def google_oauth2_test(self, token_response: ResponseMock, account_response: ResponseMock, *, subdomain: Optional[str]=None, mobile_flow_otp: Optional[str]=None, is_signup: Optional[str]=None, next: str='') -> HttpResponse: url = "/accounts/login/google/" params = {} headers = {} if subdomain is not None: headers['HTTP_HOST'] = subdomain + ".testserver" if mobile_flow_otp is not None: params['mobile_flow_otp'] = mobile_flow_otp headers['HTTP_USER_AGENT'] = "ZulipAndroid" if is_signup is not None: params['is_signup'] = is_signup params['next'] = next if len(params) > 0: url += "?%s" % (urllib.parse.urlencode(params)) result = self.client_get(url, **headers) if result.status_code != 302 or '/accounts/login/google/send/' not in result.url: return result # Now do the /google/send/ request result = self.client_get(result.url, **headers) self.assertEqual(result.status_code, 302) if 'google' not in result.url: return result self.client.cookies = result.cookies # Now extract the CSRF token from the redirect URL parsed_url = urllib.parse.urlparse(result.url) csrf_state = urllib.parse.parse_qs(parsed_url.query)['state'] with mock.patch("requests.post", return_value=token_response), ( mock.patch("requests.get", return_value=account_response)): result = self.client_get("/accounts/login/google/done/", dict(state=csrf_state), **headers) return result class GoogleSubdomainLoginTest(GoogleOAuthTest): 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) -> None: token_response = ResponseMock(200, {'access_token': "unique_token"}) account_data = dict(name=dict(formatted="Full Name"), emails=[dict(type="account", value=self.example_email("hamlet"))]) account_response = ResponseMock(200, account_data) result = self.google_oauth2_test(token_response, account_response, subdomain='zulip', next='/user_uploads/image') data = load_subdomain_token(result) self.assertEqual(data['email'], self.example_email("hamlet")) self.assertEqual(data['name'], 'Full Name') self.assertEqual(data['subdomain'], 'zulip') self.assertEqual(data['next'], '/user_uploads/image') self.assertEqual(result.status_code, 302) parsed_url = urllib.parse.urlparse(result.url) uri = "{}://{}{}".format(parsed_url.scheme, parsed_url.netloc, parsed_url.path) self.assertTrue(uri.startswith('http://zulip.testserver/accounts/login/subdomain/')) 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", value=self.example_email("hamlet"))]) account_response = ResponseMock(200, account_data) result = self.google_oauth2_test(token_response, account_response, subdomain='zulip') data = load_subdomain_token(result) self.assertEqual(data['email'], self.example_email("hamlet")) self.assertEqual(data['name'], 'Test User') self.assertEqual(data['subdomain'], 'zulip') self.assertEqual(data['next'], '') self.assertEqual(result.status_code, 302) parsed_url = urllib.parse.urlparse(result.url) uri = "{}://{}{}".format(parsed_url.scheme, parsed_url.netloc, parsed_url.path) self.assertTrue(uri.startswith('http://zulip.testserver/accounts/login/subdomain/')) def test_google_oauth2_mobile_success(self) -> None: self.user_profile = self.example_user('hamlet') self.user_profile.date_joined = timezone_now() - datetime.timedelta(seconds=JUST_CREATED_THRESHOLD + 1) self.user_profile.save() mobile_flow_otp = '1234abcd' * 8 token_response = ResponseMock(200, {'access_token': "unique_token"}) account_data = dict(name=dict(formatted="Full Name"), emails=[dict(type="account", value=self.user_profile.email)]) account_response = ResponseMock(200, account_data) self.assertEqual(len(mail.outbox), 0) with self.settings(SEND_LOGIN_EMAILS=True): # Verify that the right thing happens with an invalid-format OTP result = self.google_oauth2_test(token_response, account_response, subdomain='zulip', mobile_flow_otp="1234") self.assert_json_error(result, "Invalid OTP") result = self.google_oauth2_test(token_response, account_response, subdomain='zulip', mobile_flow_otp="invalido" * 8) self.assert_json_error(result, "Invalid OTP") # Now do it correctly result = self.google_oauth2_test(token_response, account_response, subdomain='zulip', mobile_flow_otp=mobile_flow_otp) self.assertEqual(result.status_code, 302) redirect_url = result['Location'] parsed_url = urllib.parse.urlparse(redirect_url) query_params = urllib.parse.parse_qs(parsed_url.query) self.assertEqual(parsed_url.scheme, 'zulip') self.assertEqual(query_params["realm"], ['http://zulip.testserver']) self.assertEqual(query_params["email"], [self.user_profile.email]) encrypted_api_key = query_params["otp_encrypted_api_key"][0] hamlet_api_keys = get_all_api_keys(self.user_profile) self.assertIn(otp_decrypt_api_key(encrypted_api_key, mobile_flow_otp), hamlet_api_keys) self.assertEqual(len(mail.outbox), 1) self.assertIn('Zulip on Android', mail.outbox[0].body) def get_log_into_subdomain(self, data: Dict[str, Any], *, key: Optional[str]=None, subdomain: str='zulip') -> HttpResponse: token = signing.dumps(data, salt=_subdomain_token_salt, key=key) url_path = reverse('zerver.views.auth.log_into_subdomain', args=[token]) return self.client_get(url_path, subdomain=subdomain) def test_redirect_to_next_url_for_log_into_subdomain(self) -> None: def test_redirect_to_next_url(next: str='') -> HttpResponse: data = {'name': 'Hamlet', 'email': self.example_email("hamlet"), 'subdomain': 'zulip', 'is_signup': False, 'next': next} user_profile = self.example_user('hamlet') with mock.patch( 'zerver.views.auth.authenticate_remote_user', return_value=(user_profile, {'invalid_subdomain': False})): with mock.patch('zerver.views.auth.do_login'): result = self.get_log_into_subdomain(data) return result res = test_redirect_to_next_url() self.assertEqual(res.status_code, 302) self.assertEqual(res.url, 'http://zulip.testserver') res = test_redirect_to_next_url('/user_uploads/path_to_image') self.assertEqual(res.status_code, 302) self.assertEqual(res.url, 'http://zulip.testserver/user_uploads/path_to_image') res = test_redirect_to_next_url('/#narrow/stream/7-test-here') self.assertEqual(res.status_code, 302) self.assertEqual(res.url, 'http://zulip.testserver/#narrow/stream/7-test-here') def test_log_into_subdomain_when_signature_is_bad(self) -> None: data = {'name': 'Full Name', 'email': self.example_email("hamlet"), 'subdomain': 'zulip', 'is_signup': False, 'next': ''} with mock.patch('logging.warning') as mock_warning: result = self.get_log_into_subdomain(data, key='nonsense') 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) -> None: data = {'name': 'Full Name', 'email': self.example_email("hamlet"), 'subdomain': 'zulip', 'is_signup': False, 'next': ''} with mock.patch('django.core.signing.time.time', return_value=time.time() - 45): token = signing.dumps(data, salt=_subdomain_token_salt) url_path = reverse('zerver.views.auth.log_into_subdomain', args=[token]) with mock.patch('logging.warning') as mock_warning: result = self.client_get(url_path, subdomain='zulip') mock_warning.assert_called_once() self.assertEqual(result.status_code, 400) def test_log_into_subdomain_when_is_signup_is_true(self) -> None: data = {'name': 'Full Name', 'email': self.example_email("hamlet"), 'subdomain': 'zulip', 'is_signup': True, 'next': ''} result = self.get_log_into_subdomain(data) 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) -> None: data = {'name': 'New User Name', 'email': 'new@zulip.com', 'subdomain': 'zulip', 'is_signup': True, 'next': ''} result = self.get_log_into_subdomain(data) self.assertEqual(result.status_code, 302) confirmation = Confirmation.objects.all().first() confirmation_key = confirmation.confirmation_key self.assertIn('do_confirm/' + confirmation_key, result.url) result = self.client_get(result.url) self.assert_in_response('action="/accounts/register/"', result) data = {"from_confirmation": "1", "full_name": data['name'], "key": confirmation_key} result = self.client_post('/accounts/register/', data, subdomain="zulip") self.assert_in_response("You're almost there", result) # Verify that the user is asked for name but not password self.assert_not_in_success_response(['id_password'], result) self.assert_in_success_response(['id_full_name'], result) def test_log_into_subdomain_when_is_signup_is_false_and_new_user(self) -> None: data = {'name': 'New User Name', 'email': 'new@zulip.com', 'subdomain': 'zulip', 'is_signup': False, 'next': ''} result = self.get_log_into_subdomain(data) self.assertEqual(result.status_code, 200) self.assert_in_response('No account found for', result) self.assert_in_response('new@zulip.com.', result) self.assert_in_response('action="http://zulip.testserver/accounts/do_confirm/', result) url = re.findall('action="(http://zulip.testserver/accounts/do_confirm[^"]*)"', result.content.decode('utf-8'))[0] confirmation = Confirmation.objects.all().first() confirmation_key = confirmation.confirmation_key self.assertIn('do_confirm/' + confirmation_key, url) result = self.client_get(url) self.assert_in_response('action="/accounts/register/"', result) data = {"from_confirmation": "1", "full_name": data['name'], "key": confirmation_key} result = self.client_post('/accounts/register/', data, subdomain="zulip") self.assert_in_response("You're almost there", result) # Verify that the user is asked for name but not password 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) -> None: data = {'name': 'New User Name', 'email': 'new@zulip.com', 'subdomain': 'zulip', 'is_signup': True, 'next': ''} realm = get_realm("zulip") realm.invite_required = True realm.save() stream_names = ["new_stream_1", "new_stream_2"] streams = [] for stream_name in set(stream_names): stream = ensure_stream(realm, stream_name) streams.append(stream) # Without the invite link, we can't create an account due to invite_required result = self.get_log_into_subdomain(data) self.assertEqual(result.status_code, 200) self.assert_in_success_response(['Sign up for Zulip'], result) # Now confirm an invitation link works referrer = self.example_user("hamlet") multiuse_obj = MultiuseInvite.objects.create(realm=realm, referred_by=referrer) multiuse_obj.streams.set(streams) invite_link = create_confirmation_link(multiuse_obj, realm.host, Confirmation.MULTIUSE_INVITE) result = self.client_get(invite_link, subdomain="zulip") self.assert_in_success_response(['Sign up for Zulip'], result) result = self.get_log_into_subdomain(data) self.assertEqual(result.status_code, 302) confirmation = Confirmation.objects.all().last() confirmation_key = confirmation.confirmation_key self.assertIn('do_confirm/' + confirmation_key, result.url) result = self.client_get(result.url) self.assert_in_response('action="/accounts/register/"', result) data2 = {"from_confirmation": "1", "full_name": data['name'], "key": confirmation_key} result = self.client_post('/accounts/register/', data2, subdomain="zulip") self.assert_in_response("You're almost there", result) # Verify that the user is asked for name but not password self.assert_not_in_success_response(['id_password'], result) self.assert_in_success_response(['id_full_name'], result) # Click confirm registration button. result = self.client_post( '/accounts/register/', {'full_name': 'New User Name', 'key': confirmation_key, 'terms': True}) 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) -> None: data = {'name': None, 'email': None, 'subdomain': 'zulip', 'is_signup': False, 'next': ''} with mock.patch('logging.warning'): result = self.get_log_into_subdomain(data) self.assert_in_success_response(["You need an invitation to join this organization."], result) 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", value=self.example_email("hamlet"))]) account_response = ResponseMock(200, account_data) result = self.google_oauth2_test(token_response, account_response, subdomain='nonexistent') self.assert_in_success_response(["There is no Zulip organization hosted at this subdomain."], result) 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", value=self.example_email("hamlet"))]) account_response = ResponseMock(200, account_data) result = self.google_oauth2_test(token_response, account_response, subdomain='zephyr') self.assertEqual(result.status_code, 302) self.assertTrue(result.url.startswith("http://zephyr.testserver/accounts/login/subdomain/")) result = self.client_get(result.url.replace('http://zephyr.testserver', ''), subdomain="zephyr") self.assert_in_success_response(['Your email address, hamlet@zulip.com, is not in one of the domains ', 'that are allowed to register for accounts in this organization.'], result) def test_user_cannot_log_into_wrong_subdomain_with_cookie(self) -> None: data = {'name': 'Full Name', 'email': self.example_email("hamlet"), 'subdomain': 'zephyr'} with mock.patch('logging.warning') as mock_warning: result = self.get_log_into_subdomain(data) mock_warning.assert_called_with("Login attempt on invalid subdomain") self.assertEqual(result.status_code, 400) 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") token_response = ResponseMock(200, {'access_token': "unique_token"}) account_data = dict(name=dict(formatted="Full Name"), emails=[dict(type="account", value=email)]) account_response = ResponseMock(200, account_data) result = self.google_oauth2_test(token_response, account_response, subdomain='zulip', is_signup='1') data = load_subdomain_token(result) name = 'Full Name' self.assertEqual(data['email'], email) self.assertEqual(data['name'], name) self.assertEqual(data['subdomain'], 'zulip') self.assertEqual(result.status_code, 302) parsed_url = urllib.parse.urlparse(result.url) uri = "{}://{}{}".format(parsed_url.scheme, parsed_url.netloc, parsed_url.path) self.assertTrue(uri.startswith('http://zulip.testserver/accounts/login/subdomain/')) result = self.client_get(result.url) self.assertEqual(result.status_code, 302) confirmation = Confirmation.objects.all().first() confirmation_key = confirmation.confirmation_key self.assertIn('do_confirm/' + confirmation_key, result.url) result = self.client_get(result.url) self.assert_in_response('action="/accounts/register/"', result) data = {"from_confirmation": "1", "full_name": name, "key": confirmation_key} result = self.client_post('/accounts/register/', data) self.assert_in_response("You're almost there", result) # Verify that the user is asked for name but not password self.assert_not_in_success_response(['id_password'], result) self.assert_in_success_response(['id_full_name'], result) # Click confirm registration button. result = self.client_post( '/accounts/register/', {'full_name': name, 'key': confirmation_key, 'terms': True}) self.assertEqual(result.status_code, 302) user_profile = get_user(email, realm) self.assertEqual(get_session_dict_user(self.client.session), user_profile.id) class GoogleLoginTest(GoogleOAuthTest): @override_settings(ROOT_DOMAIN_LANDING_PAGE=True) 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", value=self.example_email("hamlet"))]) account_response = ResponseMock(200, account_data) result = self.google_oauth2_test(token_response, account_response, subdomain="") self.assertEqual(result.status_code, 302) self.assertIn('subdomain=1', result.url) 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, {})) self.assertEqual(result.status_code, 400) 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) -> None: token_response = ResponseMock(500, {}) with mock.patch("logging.error") as m: result = self.google_oauth2_test(token_response, ResponseMock(500, {})) self.assertEqual(result.status_code, 400) 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) -> None: token_response = ResponseMock(200, {'access_token': "unique_token"}) account_response = ResponseMock(400, {}) with mock.patch("logging.warning") as m: result = self.google_oauth2_test(token_response, account_response) self.assertEqual(result.status_code, 400) 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) -> None: token_response = ResponseMock(200, {'access_token': "unique_token"}) account_response = ResponseMock(500, {}) with mock.patch("logging.error") as m: result = self.google_oauth2_test(token_response, account_response) self.assertEqual(result.status_code, 400) 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) -> None: token_response = ResponseMock(200, {'access_token': "unique_token"}) account_data = dict(name=dict(formatted="Full Name"), emails=[]) account_response = ResponseMock(200, account_data) with mock.patch("logging.error") as m: result = self.google_oauth2_test(token_response, account_response, subdomain="zulip") 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) -> 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) -> 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) -> 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) -> 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) -> 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) self.assertEqual(m.call_args_list[0][0][0], 'Google oauth2 CSRF error') class JSONFetchAPIKeyTest(ZulipTestCase): def setUp(self) -> None: self.user_profile = self.example_user('hamlet') self.email = self.user_profile.email def test_success(self) -> None: self.login(self.email) result = self.client_post("/json/fetch_api_key", dict(user_profile=self.user_profile, password=initial_password(self.email))) self.assert_json_success(result) def test_not_loggedin(self) -> None: result = self.client_post("/json/fetch_api_key", dict(user_profile=self.user_profile, password=initial_password(self.email))) self.assert_json_error(result, "Not logged in: API authentication or user session required", 401) def test_wrong_password(self) -> None: self.login(self.email) result = self.client_post("/json/fetch_api_key", dict(user_profile=self.user_profile, password="wrong")) self.assert_json_error(result, "Your username or password is incorrect.", 400) class FetchAPIKeyTest(ZulipTestCase): def setUp(self) -> None: self.user_profile = self.example_user('hamlet') self.email = self.user_profile.email 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) -> 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) -> None: result = self.client_post("/api/v1/fetch_api_key", dict(username=self.email, password="wrong")) self.assert_json_error(result, "Your username or password is incorrect.", 403) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.GoogleMobileOauth2Backend',), SEND_LOGIN_EMAILS=True) def test_google_oauth2_token_success(self) -> None: self.assertEqual(len(mail.outbox), 0) self.user_profile.date_joined = timezone_now() - datetime.timedelta(seconds=JUST_CREATED_THRESHOLD + 1) self.user_profile.save() with mock.patch( 'apiclient.sample_tools.client.verify_id_token', return_value={ "email_verified": True, "email": self.example_email("hamlet"), }): result = self.client_post("/api/v1/fetch_api_key", dict(username="google-oauth2-token", password="token")) self.assert_json_success(result) self.assertEqual(len(mail.outbox), 1) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.GoogleMobileOauth2Backend',)) 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", dict(username="google-oauth2-token", password="token")) 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) -> None: with mock.patch( 'apiclient.sample_tools.client.verify_id_token', return_value={ "email_verified": True, "email": "nobody@zulip.com", }): result = self.client_post("/api/v1/fetch_api_key", dict(username="google-oauth2-token", password="token")) self.assert_json_error( result, "This user is not registered; do so from a browser.", 403) 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, password=initial_password(self.email))) 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) -> None: ldap_patcher = mock.patch('django_auth_ldap.config.ldap.initialize') self.mock_initialize = ldap_patcher.start() self.mock_ldap = MockLDAP() self.mock_initialize.return_value = self.mock_ldap self.backend = ZulipLDAPAuthBackend() self.mock_ldap.directory = { 'uid=hamlet,ou=users,dc=zulip,dc=com': { 'userPassword': 'testing' } } with self.settings( LDAP_APPEND_DOMAIN='zulip.com', AUTH_LDAP_BIND_PASSWORD='', AUTH_LDAP_USER_DN_TEMPLATE='uid=%(user)s,ou=users,dc=zulip,dc=com'): result = self.client_post("/api/v1/fetch_api_key", dict(username=self.email, password="testing")) self.assert_json_success(result) self.mock_ldap.reset() self.mock_initialize.stop() 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) -> None: do_deactivate_realm(self.user_profile.realm) result = self.client_post("/api/v1/fetch_api_key", dict(username=self.email, password=initial_password(self.email))) self.assert_json_error_contains(result, "This organization has been deactivated", 403) class DevFetchAPIKeyTest(ZulipTestCase): def setUp(self) -> None: self.user_profile = self.example_user('hamlet') self.email = self.user_profile.email def test_success(self) -> None: result = self.client_post("/api/v1/dev_fetch_api_key", dict(username=self.email)) self.assert_json_success(result) data = result.json() self.assertEqual(data["email"], self.email) user_api_keys = get_all_api_keys(self.user_profile) self.assertIn(data['api_key'], user_api_keys) 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) -> 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) -> 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) -> 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, "This organization has been deactivated", 403) 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) -> None: result = self.client_get("/api/v1/dev_list_users") 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) -> None: with mock.patch('zerver.views.auth.dev_auth_enabled', return_value=False): result = self.client_get("/api/v1/dev_list_users") self.assert_json_error_contains(result, "Dev environment not enabled.", 400) class FetchAuthBackends(ZulipTestCase): def assert_on_error(self, error: Optional[str]) -> None: if error: raise AssertionError(error) def test_get_server_settings(self) -> None: def check_result(result: HttpResponse, extra_fields: List[Tuple[str, Validator]]=[]) -> None: self.assert_json_success(result) checker = check_dict_only([ ('authentication_methods', check_dict_only([ ('google', check_bool), ('github', check_bool), ('email', check_bool), ('ldap', check_bool), ('dev', check_bool), ('remoteuser', check_bool), ('password', check_bool), ])), ('email_auth_enabled', check_bool), ('require_email_format_usernames', check_bool), ('realm_uri', check_string), ('zulip_version', check_string), ('push_notifications_enabled', check_bool), ('msg', check_string), ('result', check_string), ] + extra_fields) self.assert_on_error(checker("data", result.json())) result = self.client_get("/api/v1/server_settings", subdomain="") check_result(result) with self.settings(ROOT_DOMAIN_LANDING_PAGE=False): result = self.client_get("/api/v1/server_settings", subdomain="") check_result(result) with self.settings(ROOT_DOMAIN_LANDING_PAGE=False): result = self.client_get("/api/v1/server_settings", subdomain="zulip") check_result(result, [ ('realm_name', check_string), ('realm_description', check_string), ('realm_icon', check_string), ]) 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() self.assertEqual(set(data.keys()), {'msg', 'password', 'github', 'google', 'email', 'ldap', 'dev', 'result', 'remoteuser', 'zulip_version'}) for backend in set(data.keys()) - {'msg', 'result', 'zulip_version'}: self.assertTrue(isinstance(data[backend], bool)) 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") self.assert_json_success(result) data = result.json() self.assertEqual(data, { 'msg': '', 'password': False, 'github': False, 'google': True, 'dev': True, 'email': False, 'ldap': False, 'remoteuser': False, 'result': 'success', 'zulip_version': ZULIP_VERSION, }) # Test subdomains cases with self.settings(ROOT_DOMAIN_LANDING_PAGE=False): result = self.client_get("/api/v1/get_auth_backends") self.assert_json_success(result) data = result.json() self.assertEqual(data, { 'msg': '', 'password': False, 'github': False, 'google': True, 'email': False, 'ldap': False, 'remoteuser': False, 'dev': True, 'result': 'success', 'zulip_version': ZULIP_VERSION, }) # Verify invalid subdomain result = self.client_get("/api/v1/get_auth_backends", subdomain="invalid") self.assert_json_error_contains(result, "Invalid subdomain", 400) # Verify correct behavior with a valid subdomain with # some backends disabled for the realm realm = get_realm("zulip") do_set_realm_authentication_methods(realm, dict(Google=False, Email=False, Dev=True)) result = self.client_get("/api/v1/get_auth_backends", subdomain="zulip") self.assert_json_success(result) data = result.json() self.assertEqual(data, { 'msg': '', 'password': False, 'github': False, 'google': False, 'email': False, 'ldap': False, 'remoteuser': False, 'dev': True, 'result': 'success', 'zulip_version': ZULIP_VERSION, }) with self.settings(ROOT_DOMAIN_LANDING_PAGE=True): # With ROOT_DOMAIN_LANDING_PAGE, homepage fails result = self.client_get("/api/v1/get_auth_backends", subdomain="") self.assert_json_error_contains(result, "Subdomain required", 400) # With ROOT_DOMAIN_LANDING_PAGE, subdomain pages succeed result = self.client_get("/api/v1/get_auth_backends", subdomain="zulip") self.assert_json_success(result) data = result.json() self.assertEqual(data, { 'msg': '', 'password': False, 'github': False, 'google': False, 'email': False, 'remoteuser': False, 'ldap': False, 'dev': True, 'result': 'success', 'zulip_version': ZULIP_VERSION, }) class TestTwoFactor(ZulipTestCase): def test_direct_dev_login_with_2fa(self) -> None: email = self.example_email('hamlet') user_profile = self.example_user('hamlet') with self.settings(TWO_FACTOR_AUTHENTICATION_ENABLED=True): data = {'direct_email': email} result = self.client_post('/accounts/login/local/', data) self.assertEqual(result.status_code, 302) self.assertEqual(get_session_dict_user(self.client.session), user_profile.id) # User logs in but when otp device doesn't exist. self.assertNotIn('otp_device_id', self.client.session.keys()) self.create_default_device(user_profile) data = {'direct_email': email} result = self.client_post('/accounts/login/local/', data) self.assertEqual(result.status_code, 302) self.assertEqual(get_session_dict_user(self.client.session), user_profile.id) # User logs in when otp device exists. self.assertIn('otp_device_id', self.client.session.keys()) @mock.patch('two_factor.models.totp') def test_two_factor_login_with_ldap(self, mock_totp): # type: (mock.MagicMock) -> None token = 123456 email = self.example_email('hamlet') password = 'testing' user_profile = self.example_user('hamlet') user_profile.set_password(password) user_profile.save() self.create_default_device(user_profile) def totp(*args, **kwargs): # type: (*Any, **Any) -> int return token mock_totp.side_effect = totp # Setup LDAP ldap_user_attr_map = {'full_name': 'fn', 'short_name': 'sn'} ldap_patcher = mock.patch('django_auth_ldap.config.ldap.initialize') mock_initialize = ldap_patcher.start() mock_ldap = MockLDAP() mock_initialize.return_value = mock_ldap full_name = 'New LDAP fullname' mock_ldap.directory = { 'uid=hamlet,ou=users,dc=zulip,dc=com': { 'userPassword': 'testing', 'fn': [full_name], 'sn': ['shortname'], } } with self.settings( AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',), TWO_FACTOR_CALL_GATEWAY='two_factor.gateways.fake.Fake', TWO_FACTOR_SMS_GATEWAY='two_factor.gateways.fake.Fake', TWO_FACTOR_AUTHENTICATION_ENABLED=True, POPULATE_PROFILE_VIA_LDAP=True, LDAP_APPEND_DOMAIN='zulip.com', AUTH_LDAP_BIND_PASSWORD='', AUTH_LDAP_USER_ATTR_MAP=ldap_user_attr_map, AUTH_LDAP_USER_DN_TEMPLATE='uid=%(user)s,ou=users,dc=zulip,dc=com'): first_step_data = {"username": email, "password": password, "two_factor_login_view-current_step": "auth"} result = self.client_post("/accounts/login/", first_step_data) self.assertEqual(result.status_code, 200) second_step_data = {"token-otp_token": str(token), "two_factor_login_view-current_step": "token"} result = self.client_post("/accounts/login/", second_step_data) self.assertEqual(result.status_code, 302) self.assertEqual(result['Location'], 'http://zulip.testserver') # Going to login page should redirect to `realm.uri` if user is # already logged in. result = self.client_get('/accounts/login/') self.assertEqual(result.status_code, 302) self.assertEqual(result['Location'], 'http://zulip.testserver') class TestDevAuthBackend(ZulipTestCase): def test_login_success(self) -> None: user_profile = self.example_user('hamlet') email = user_profile.email data = {'direct_email': email} result = self.client_post('/accounts/login/local/', data) self.assertEqual(result.status_code, 302) self.assertEqual(get_session_dict_user(self.client.session), user_profile.id) def test_login_success_with_2fa(self) -> None: user_profile = self.example_user('hamlet') self.create_default_device(user_profile) email = user_profile.email data = {'direct_email': email} with self.settings(TWO_FACTOR_AUTHENTICATION_ENABLED=True): result = self.client_post('/accounts/login/local/', data) self.assertEqual(result.status_code, 302) self.assertEqual(result.url, 'http://zulip.testserver') self.assertEqual(get_session_dict_user(self.client.session), user_profile.id) self.assertIn('otp_device_id', list(self.client.session.keys())) def test_redirect_to_next_url(self) -> None: def do_local_login(formaction: str) -> HttpResponse: user_email = self.example_email('hamlet') data = {'direct_email': user_email} return self.client_post(formaction, data) res = do_local_login('/accounts/login/local/') self.assertEqual(res.status_code, 302) self.assertEqual(res.url, 'http://zulip.testserver') res = do_local_login('/accounts/login/local/?next=/user_uploads/path_to_image') self.assertEqual(res.status_code, 302) self.assertEqual(res.url, 'http://zulip.testserver/user_uploads/path_to_image') # In local Email based authentication we never make browser send the hash # to the backend. Rather we depend upon the browser's behaviour of persisting # hash anchors in between redirect requests. See below stackoverflow conversation # https://stackoverflow.com/questions/5283395/url-hash-is-persisting-between-redirects res = do_local_login('/accounts/login/local/?next=#narrow/stream/7-test-here') self.assertEqual(res.status_code, 302) self.assertEqual(res.url, 'http://zulip.testserver') def test_login_with_subdomain(self) -> None: user_profile = self.example_user('hamlet') email = user_profile.email data = {'direct_email': email} result = self.client_post('/accounts/login/local/', data) self.assertEqual(result.status_code, 302) self.assertEqual(get_session_dict_user(self.client.session), user_profile.id) 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) result = self.client_post('/devlogin/', subdomain="") self.assert_in_success_response(["Click on a user to log in!"], result) self.assert_in_success_response(["iago@zulip.com", "hamlet@zulip.com"], result) self.assert_in_success_response(["starnine@mit.edu", "espuser@mit.edu"], result) data = {'new_realm': 'zephyr'} result = self.client_post('/devlogin/', data, subdomain="zulip") self.assertEqual(result.status_code, 302) self.assertEqual(result.url, "http://zephyr.testserver") result = self.client_get('/devlogin/', subdomain="zephyr") 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) self.assert_not_in_success_response(["iago@zulip.com", "hamlet@zulip.com"], result) 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/") self.assert_in_success_response(["iago@zulip.com", "hamlet@zulip.com"], result) self.assert_not_in_success_response(["starnine@mit.edu", "espuser@mit.edu"], result) self.assert_in_success_response(["Click on a user to log in to Zulip Dev!"], result) with mock.patch('zerver.views.auth.get_realm_from_request', return_value=get_realm('zephyr')): result = self.client_post("http://zulip.testserver/devlogin/", {'new_realm': 'zephyr'}) self.assertEqual(result["Location"], "http://zephyr.testserver") result = self.client_get("http://zephyr.testserver/devlogin/") self.assert_not_in_success_response(["iago@zulip.com", "hamlet@zulip.com"], result) 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) -> None: email = self.example_email("hamlet") data = {'direct_email': email} with self.settings(AUTHENTICATION_BACKENDS=('zproject.backends.EmailAuthBackend',)): with mock.patch('django.core.handlers.exception.logger'): response = self.client_post('/accounts/login/local/', data) self.assertRedirects(response, reverse('dev_not_supported')) def test_login_failure_due_to_nonexistent_user(self) -> None: email = 'nonexisting@zulip.com' data = {'direct_email': email} with mock.patch('django.core.handlers.exception.logger'): response = self.client_post('/accounts/login/local/', data) self.assertRedirects(response, reverse('dev_not_supported')) class TestZulipRemoteUserBackend(ZulipTestCase): def test_login_success(self) -> None: user_profile = self.example_user('hamlet') email = user_profile.email with self.settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipRemoteUserBackend',)): result = self.client_post('/accounts/login/sso/', REMOTE_USER=email) 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) -> None: username = 'hamlet' user_profile = self.example_user('hamlet') with self.settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipRemoteUserBackend',), SSO_APPEND_DOMAIN='zulip.com'): result = self.client_post('/accounts/login/sso/', REMOTE_USER=username) self.assertEqual(result.status_code, 302) self.assertEqual(get_session_dict_user(self.client.session), user_profile.id) 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) -> None: email = 'nonexisting@zulip.com' with self.settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipRemoteUserBackend',)): result = self.client_post('/accounts/login/sso/', REMOTE_USER=email) self.assertEqual(result.status_code, 200) 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) -> 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) -> 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) -> 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'): result = self.client_post('http://testserver:9080/accounts/login/sso/', REMOTE_USER=email) self.assertEqual(result.status_code, 200) self.assertIs(get_session_dict_user(self.client.session), None) self.assert_in_response("You need an invitation to join this organization.", result) 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=''): result = self.client_post('http://testserver:9080/accounts/login/sso/', REMOTE_USER=email) self.assertEqual(result.status_code, 200) self.assertIs(get_session_dict_user(self.client.session), None) self.assert_in_response("You need an invitation to join this organization.", result) 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'): with self.settings( AUTHENTICATION_BACKENDS=('zproject.backends.ZulipRemoteUserBackend',)): result = self.client_post('/accounts/login/sso/', REMOTE_USER=email) self.assertEqual(result.status_code, 302) self.assertIs(get_session_dict_user(self.client.session), user_profile.id) @override_settings(SEND_LOGIN_EMAILS=True) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipRemoteUserBackend',)) def test_login_mobile_flow_otp_success(self) -> None: user_profile = self.example_user('hamlet') email = user_profile.email user_profile.date_joined = timezone_now() - datetime.timedelta(seconds=61) user_profile.save() mobile_flow_otp = '1234abcd' * 8 # Verify that the right thing happens with an invalid-format OTP result = self.client_post('/accounts/login/sso/', dict(mobile_flow_otp="1234"), REMOTE_USER=email, HTTP_USER_AGENT = "ZulipAndroid") self.assertIs(get_session_dict_user(self.client.session), None) self.assert_json_error_contains(result, "Invalid OTP", 400) result = self.client_post('/accounts/login/sso/', dict(mobile_flow_otp="invalido" * 8), REMOTE_USER=email, HTTP_USER_AGENT = "ZulipAndroid") self.assertIs(get_session_dict_user(self.client.session), None) self.assert_json_error_contains(result, "Invalid OTP", 400) result = self.client_post('/accounts/login/sso/', dict(mobile_flow_otp=mobile_flow_otp), REMOTE_USER=email, HTTP_USER_AGENT = "ZulipAndroid") self.assertEqual(result.status_code, 302) redirect_url = result['Location'] parsed_url = urllib.parse.urlparse(redirect_url) query_params = urllib.parse.parse_qs(parsed_url.query) self.assertEqual(parsed_url.scheme, 'zulip') self.assertEqual(query_params["realm"], ['http://zulip.testserver']) self.assertEqual(query_params["email"], [self.example_email("hamlet")]) encrypted_api_key = query_params["otp_encrypted_api_key"][0] hamlet_api_keys = get_all_api_keys(self.example_user('hamlet')) self.assertIn(otp_decrypt_api_key(encrypted_api_key, mobile_flow_otp), hamlet_api_keys) self.assertEqual(len(mail.outbox), 1) self.assertIn('Zulip on Android', mail.outbox[0].body) def test_redirect_to(self) -> None: """This test verifies the behavior of the redirect_to logic in login_or_register_remote_user.""" def test_with_redirect_to_param_set_as_next(next: str='') -> HttpResponse: user_profile = self.example_user('hamlet') email = user_profile.email with self.settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipRemoteUserBackend',)): result = self.client_post('/accounts/login/sso/?next=' + next, REMOTE_USER=email) return result res = test_with_redirect_to_param_set_as_next() self.assertEqual('http://zulip.testserver', res.url) res = test_with_redirect_to_param_set_as_next('/user_uploads/image_path') self.assertEqual('http://zulip.testserver/user_uploads/image_path', res.url) # Third-party domains are rejected and just send you to root domain res = test_with_redirect_to_param_set_as_next('https://rogue.zulip-like.server/login') self.assertEqual('http://zulip.testserver', res.url) # In SSO based auth we never make browser send the hash to the backend. # Rather we depend upon the browser's behaviour of persisting hash anchors # in between redirect requests. See below stackoverflow conversation # https://stackoverflow.com/questions/5283395/url-hash-is-persisting-between-redirects res = test_with_redirect_to_param_set_as_next('#narrow/stream/7-test-here') self.assertEqual('http://zulip.testserver', res.url) class TestJWTLogin(ZulipTestCase): """ JWT uses ZulipDummyBackend. """ 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") realm = get_realm('zulip') auth_key = settings.JWT_AUTH_KEYS['zulip'] web_token = jwt.encode(payload, auth_key).decode('utf8') user_profile = get_user(email, realm) data = {'json_web_token': web_token} result = self.client_post('/accounts/login/jwt/', data) 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) -> None: payload = {'realm': 'zulip.com'} with self.settings(JWT_AUTH_KEYS={'zulip': 'key'}): auth_key = settings.JWT_AUTH_KEYS['zulip'] web_token = jwt.encode(payload, auth_key).decode('utf8') data = {'json_web_token': web_token} 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) -> None: payload = {'user': 'hamlet'} with self.settings(JWT_AUTH_KEYS={'zulip': 'key'}): auth_key = settings.JWT_AUTH_KEYS['zulip'] web_token = jwt.encode(payload, auth_key).decode('utf8') data = {'json_web_token': web_token} result = self.client_post('/accounts/login/jwt/', data) self.assert_json_error_contains(result, "No organization specified in JSON web token claims", 400) 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) -> 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) -> 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) data = {'json_web_token': 'bad token'} 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) -> None: payload = {'user': 'nonexisting', 'realm': 'zulip.com'} with self.settings(JWT_AUTH_KEYS={'zulip': 'key'}): auth_key = settings.JWT_AUTH_KEYS['zulip'] web_token = jwt.encode(payload, auth_key).decode('utf8') data = {'json_web_token': web_token} result = self.client_post('/accounts/login/jwt/', data) self.assertEqual(result.status_code, 200) # This should ideally be not 200. self.assertIs(get_session_dict_user(self.client.session), None) # The /accounts/login/jwt/ endpoint should also handle the case # where the authentication attempt throws UserProfile.DoesNotExist. with mock.patch( 'zerver.views.auth.authenticate', side_effect=UserProfile.DoesNotExist("Do not exist")): result = self.client_post('/accounts/login/jwt/', data) 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) -> 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'), \ mock.patch('logging.warning'): auth_key = settings.JWT_AUTH_KEYS['acme'] web_token = jwt.encode(payload, auth_key).decode('utf8') data = {'json_web_token': web_token} result = self.client_post('/accounts/login/jwt/', data) 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) -> None: payload = {'user': 'hamlet', 'realm': 'zulip.com'} with self.settings(JWT_AUTH_KEYS={'': 'key'}): with mock.patch('zerver.views.auth.get_subdomain', return_value=''), \ mock.patch('logging.warning'): auth_key = settings.JWT_AUTH_KEYS[''] web_token = jwt.encode(payload, auth_key).decode('utf8') data = {'json_web_token': web_token} result = self.client_post('/accounts/login/jwt/', data) 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) -> 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'): auth_key = settings.JWT_AUTH_KEYS['zulip'] web_token = jwt.encode(payload, auth_key).decode('utf8') data = {'json_web_token': web_token} result = self.client_post('/accounts/login/jwt/', data) self.assertEqual(result.status_code, 302) user_profile = self.example_user('hamlet') self.assertEqual(get_session_dict_user(self.client.session), user_profile.id) class TestLDAP(ZulipTestCase): def setUp(self) -> None: user_profile = self.example_user('hamlet') self.setup_subdomain(user_profile) ldap_patcher = mock.patch('django_auth_ldap.config.ldap.initialize') self.mock_initialize = ldap_patcher.start() self.mock_ldap = MockLDAP() self.mock_initialize.return_value = self.mock_ldap self.backend = ZulipLDAPAuthBackend() # Internally `_realm` attribute is automatically set by the # `authenticate()` method. But for testing the `get_or_build_user()` # method separately, we need to set it manually. self.backend._realm = get_realm('zulip') def tearDown(self) -> None: self.mock_ldap.reset() self.mock_initialize.stop() def setup_subdomain(self, user_profile: UserProfile) -> None: realm = user_profile.realm realm.string_id = 'zulip' realm.save() def test_generate_dev_ldap_dir(self) -> None: ldap_dir = generate_dev_ldap_dir('A', 10) self.assertEqual(len(ldap_dir), 10) regex = re.compile(r'(uid\=)+[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+(\,ou\=users\,dc\=zulip\,dc\=com)') for key, value in ldap_dir.items(): self.assertTrue(regex.match(key)) self.assertCountEqual(list(value.keys()), ['cn', 'userPassword']) ldap_dir = generate_dev_ldap_dir('b', 9) self.assertEqual(len(ldap_dir), 9) regex = re.compile(r'(uid\=)+[a-zA-Z0-9_.+-]+(\,ou\=users\,dc\=zulip\,dc\=com)') for key, value in ldap_dir.items(): self.assertTrue(regex.match(key)) self.assertCountEqual(list(value.keys()), ['cn', 'userPassword']) ldap_dir = generate_dev_ldap_dir('c', 8) self.assertEqual(len(ldap_dir), 8) regex = re.compile(r'(uid\=)+[a-zA-Z0-9_.+-]+(\,ou\=users\,dc\=zulip\,dc\=com)') for key, value in ldap_dir.items(): self.assertTrue(regex.match(key)) self.assertCountEqual(list(value.keys()), ['cn', 'userPassword', 'email']) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',)) def test_login_success(self) -> None: self.mock_ldap.directory = { 'uid=hamlet,ou=users,dc=zulip,dc=com': { 'userPassword': 'testing' } } with self.settings( LDAP_APPEND_DOMAIN='zulip.com', AUTH_LDAP_BIND_PASSWORD='', AUTH_LDAP_USER_DN_TEMPLATE='uid=%(user)s,ou=users,dc=zulip,dc=com'): user_profile = self.backend.authenticate(self.example_email("hamlet"), 'testing', realm=get_realm('zulip')) assert(user_profile is not None) self.assertEqual(user_profile.email, self.example_email("hamlet")) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',)) def test_login_success_with_email_attr(self) -> None: self.mock_ldap.directory = { 'uid=letham,ou=users,dc=zulip,dc=com': { 'userPassword': 'testing', 'email': ['hamlet@zulip.com'], } } with self.settings(LDAP_EMAIL_ATTR='email', AUTH_LDAP_BIND_PASSWORD='', AUTH_LDAP_USER_DN_TEMPLATE='uid=%(user)s,ou=users,dc=zulip,dc=com'): user_profile = self.backend.authenticate("letham", 'testing', realm=get_realm('zulip')) assert (user_profile is not None) 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) -> None: self.mock_ldap.directory = { 'uid=hamlet,ou=users,dc=zulip,dc=com': { 'userPassword': 'testing' } } with self.settings( LDAP_APPEND_DOMAIN='zulip.com', AUTH_LDAP_BIND_PASSWORD='', AUTH_LDAP_USER_DN_TEMPLATE='uid=%(user)s,ou=users,dc=zulip,dc=com'): user = self.backend.authenticate(self.example_email("hamlet"), 'wrong') self.assertIs(user, None) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',)) def test_login_failure_due_to_nonexistent_user(self) -> None: self.mock_ldap.directory = { 'uid=hamlet,ou=users,dc=zulip,dc=com': { 'userPassword': 'testing' } } with self.settings( LDAP_APPEND_DOMAIN='zulip.com', AUTH_LDAP_BIND_PASSWORD='', AUTH_LDAP_USER_DN_TEMPLATE='uid=%(user)s,ou=users,dc=zulip,dc=com'): user = self.backend.authenticate('nonexistent@zulip.com', 'testing') self.assertIs(user, None) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',)) def test_ldap_permissions(self) -> None: backend = self.backend self.assertFalse(backend.has_perm(None, None)) self.assertFalse(backend.has_module_perms(None, None)) self.assertTrue(backend.get_all_permissions(None, None) == set()) self.assertTrue(backend.get_group_permissions(None, None) == set()) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',)) 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) -> 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_build_user_when_user_exists(self) -> None: class _LDAPUser: attrs = {'fn': ['Full Name'], 'sn': ['Short Name']} backend = self.backend email = self.example_email("hamlet") user_profile, created = backend.get_or_build_user(str(email), _LDAPUser()) self.assertFalse(created) self.assertEqual(user_profile.email, email) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',)) def test_get_or_build_user_when_user_does_not_exist(self) -> None: class _LDAPUser: attrs = {'fn': ['Full Name'], 'sn': ['Short Name']} ldap_user_attr_map = {'full_name': 'fn', 'short_name': 'sn'} with self.settings(AUTH_LDAP_USER_ATTR_MAP=ldap_user_attr_map): backend = self.backend email = 'nonexisting@zulip.com' user_profile, created = backend.get_or_build_user(email, _LDAPUser()) self.assertTrue(created) self.assertEqual(user_profile.email, email) self.assertEqual(user_profile.full_name, 'Full Name') @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',)) def test_get_or_build_user_when_user_has_invalid_name(self) -> None: class _LDAPUser: attrs = {'fn': ['<invalid name>'], 'sn': ['Short Name']} ldap_user_attr_map = {'full_name': 'fn', 'short_name': 'sn'} with self.settings(AUTH_LDAP_USER_ATTR_MAP=ldap_user_attr_map): backend = self.backend email = 'nonexisting@zulip.com' with self.assertRaisesRegex(Exception, "Invalid characters in name!"): backend.get_or_build_user(email, _LDAPUser()) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',)) def test_get_or_build_user_when_realm_is_deactivated(self) -> None: class _LDAPUser: attrs = {'fn': ['Full Name'], 'sn': ['Short Name']} ldap_user_attr_map = {'full_name': 'fn', 'short_name': 'sn'} with self.settings(AUTH_LDAP_USER_ATTR_MAP=ldap_user_attr_map): backend = self.backend email = 'nonexisting@zulip.com' do_deactivate_realm(backend._realm) with self.assertRaisesRegex(Exception, 'Realm has been deactivated'): backend.get_or_build_user(email, _LDAPUser()) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',)) def test_get_or_build_user_when_ldap_has_no_email_attr(self) -> None: class _LDAPUser: attrs = {'fn': ['Full Name'], 'sn': ['Short Name']} nonexisting_attr = 'email' with self.settings(LDAP_EMAIL_ATTR=nonexisting_attr): backend = self.backend email = 'nonexisting@zulip.com' with self.assertRaisesRegex(Exception, 'LDAP user doesn\'t have the needed email attribute'): backend.get_or_build_user(email, _LDAPUser()) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',)) 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, 'Email hamlet@zulip.com does not match LDAP domain acme.com.'): with self.settings(LDAP_APPEND_DOMAIN='acme.com'): backend.django_to_ldap_username(email) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',)) 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) -> None: self.mock_ldap.directory = { 'uid=hamlet,ou=users,dc=zulip,dc=com': { 'userPassword': 'testing' } } with self.settings( LDAP_APPEND_DOMAIN='zulip.com', AUTH_LDAP_BIND_PASSWORD='', AUTH_LDAP_USER_DN_TEMPLATE='uid=%(user)s,ou=users,dc=zulip,dc=com'): user_profile = self.backend.authenticate(self.example_email("hamlet"), 'testing', realm=get_realm('zephyr')) self.assertIs(user_profile, None) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',)) def test_login_failure_due_to_invalid_subdomain(self) -> None: self.mock_ldap.directory = { 'uid=hamlet,ou=users,dc=zulip,dc=com': { 'userPassword': 'testing' } } with self.settings( LDAP_APPEND_DOMAIN='zulip.com', AUTH_LDAP_BIND_PASSWORD='', AUTH_LDAP_USER_DN_TEMPLATE='uid=%(user)s,ou=users,dc=zulip,dc=com'): user_profile = self.backend.authenticate(self.example_email("hamlet"), 'testing', realm=None) self.assertIs(user_profile, None) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',)) def test_login_success_with_valid_subdomain(self) -> None: self.mock_ldap.directory = { 'uid=hamlet,ou=users,dc=zulip,dc=com': { 'userPassword': 'testing' } } with self.settings( LDAP_APPEND_DOMAIN='zulip.com', AUTH_LDAP_BIND_PASSWORD='', AUTH_LDAP_USER_DN_TEMPLATE='uid=%(user)s,ou=users,dc=zulip,dc=com'): user_profile = self.backend.authenticate(self.example_email("hamlet"), 'testing', realm=get_realm('zulip')) assert(user_profile is not None) 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) -> None: self.mock_ldap.directory = { 'uid=hamlet,ou=users,dc=zulip,dc=com': { 'userPassword': 'testing' } } user_profile = self.example_user("hamlet") do_deactivate_user(user_profile) with self.settings( LDAP_APPEND_DOMAIN='zulip.com', AUTH_LDAP_BIND_PASSWORD='', AUTH_LDAP_USER_DN_TEMPLATE='uid=%(user)s,ou=users,dc=zulip,dc=com'): user_profile = self.backend.authenticate(self.example_email("hamlet"), 'testing', realm=get_realm('zulip')) 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) -> None: self.mock_ldap.directory = { 'uid=nonexisting,ou=users,dc=acme,dc=com': { 'cn': ['NonExisting', ], 'userPassword': 'testing' } } with self.settings( LDAP_APPEND_DOMAIN='acme.com', AUTH_LDAP_BIND_PASSWORD='', AUTH_LDAP_USER_DN_TEMPLATE='uid=%(user)s,ou=users,dc=acme,dc=com'): user_profile = self.backend.authenticate('nonexisting@acme.com', 'testing', realm=get_realm('zulip')) assert(user_profile is not None) self.assertEqual(user_profile.email, 'nonexisting@acme.com') self.assertEqual(user_profile.full_name, 'NonExisting') self.assertEqual(user_profile.realm.string_id, 'zulip') class TestZulipLDAPUserPopulator(ZulipTestCase): 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) -> None: backend = ZulipAuthMixin() result = backend.get_user(11111) self.assertIs(result, None) class TestPasswordAuthEnabled(ZulipTestCase): 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) -> 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) -> 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) -> 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) -> 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) -> None: with self.settings(AUTHENTICATION_BACKENDS=('zproject.backends.EmailAuthBackend', 'zproject.backends.ZulipLDAPAuthBackend'), LDAP_APPEND_DOMAIN="zulip.com"): realm = Realm.objects.get(string_id='zulip') self.assertFalse(require_email_format_usernames(realm)) class TestMaybeSendToRegistration(ZulipTestCase): def test_sso_only_when_preregistration_user_does_not_exist(self) -> None: rf = RequestFactory() request = rf.get('/') request.session = {} request.user = None # Creating a mock Django form in order to keep the test simple. # This form will be returned by the create_hompage_form function # and will always be valid so that the code that we want to test # actually runs. class Form: def is_valid(self) -> bool: return True with self.settings(ONLY_SSO=True): with mock.patch('zerver.views.auth.HomepageForm', return_value=Form()): self.assertEqual(PreregistrationUser.objects.all().count(), 0) result = maybe_send_to_registration(request, self.example_email("hamlet"), is_signup=True) self.assertEqual(result.status_code, 302) confirmation = Confirmation.objects.all().first() confirmation_key = confirmation.confirmation_key self.assertIn('do_confirm/' + confirmation_key, result.url) self.assertEqual(PreregistrationUser.objects.all().count(), 1) result = self.client_get(result.url) 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) -> None: rf = RequestFactory() request = rf.get('/') request.session = {} request.user = None # Creating a mock Django form in order to keep the test simple. # This form will be returned by the create_hompage_form function # and will always be valid so that the code that we want to test # actually runs. class Form: def is_valid(self) -> bool: return True email = self.example_email("hamlet") user = PreregistrationUser(email=email) user.save() with self.settings(ONLY_SSO=True): with mock.patch('zerver.views.auth.HomepageForm', return_value=Form()): self.assertEqual(PreregistrationUser.objects.all().count(), 1) result = maybe_send_to_registration(request, email, is_signup=True) self.assertEqual(result.status_code, 302) confirmation = Confirmation.objects.all().first() confirmation_key = confirmation.confirmation_key self.assertIn('do_confirm/' + confirmation_key, result.url) self.assertEqual(PreregistrationUser.objects.all().count(), 1) class TestAdminSetBackends(ZulipTestCase): def test_change_enabled_backends(self) -> None: # Log in as admin self.login(self.example_email("iago")) result = self.client_patch("/json/realm", { 'authentication_methods': ujson.dumps({u'Email': False, u'Dev': True})}) self.assert_json_success(result) realm = get_realm('zulip') self.assertFalse(password_auth_enabled(realm)) self.assertTrue(dev_auth_enabled(realm)) def test_disable_all_backends(self) -> None: # Log in as admin self.login(self.example_email("iago")) result = self.client_patch("/json/realm", { 'authentication_methods': ujson.dumps({u'Email': False, u'Dev': False})}) self.assert_json_error(result, 'At least one authentication method must be enabled.') realm = get_realm('zulip') self.assertTrue(password_auth_enabled(realm)) self.assertTrue(dev_auth_enabled(realm)) def test_supported_backends_only_updated(self) -> None: # Log in as admin self.login(self.example_email("iago")) # Set some supported and unsupported backends result = self.client_patch("/json/realm", { 'authentication_methods': ujson.dumps({u'Email': False, u'Dev': True, u'GitHub': False})}) self.assert_json_success(result) realm = get_realm('zulip') # Check that unsupported backend is not enabled self.assertFalse(github_auth_enabled(realm)) self.assertTrue(dev_auth_enabled(realm)) self.assertFalse(password_auth_enabled(realm)) class EmailValidatorTestCase(ZulipTestCase): def test_valid_email(self) -> None: validate_login_email(self.example_email("hamlet")) def test_invalid_email(self) -> None: with self.assertRaises(JsonableError): validate_login_email(u'hamlet') def test_validate_email(self) -> None: inviter = self.example_user('hamlet') cordelia = self.example_user('cordelia') error, _ = validate_email(inviter, 'fred+5555@zulip.com') self.assertIn('containing + are not allowed', error) _, error = validate_email(inviter, cordelia.email) self.assertEqual(error, 'Already has an account.') cordelia.is_active = False cordelia.save() _, error = validate_email(inviter, cordelia.email) self.assertEqual(error, 'Already has an account.') _, error = validate_email(inviter, 'fred-is-fine@zulip.com') self.assertEqual(error, None) class LDAPBackendTest(ZulipTestCase): @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',)) 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 error = ZulipLDAPConfigurationError('Realm is None', error_type) with mock.patch('zproject.backends.ZulipLDAPAuthBackend.get_or_build_user', side_effect=error), \ mock.patch('django_auth_ldap.backend._LDAPUser._authenticate_user_dn'): response = self.client_post('/login/', data) self.assertEqual(response.status_code, 302) self.assertEqual(response.url, reverse('ldap_error_realm_is_none')) response = self.client_get(response.url) self.assert_in_response('You are trying to login using LDAP ' 'without creating an', response)
[ "Any", "UserProfile", "Any", "Any", "int", "Any", "Dict[str, str]", "ResponseMock", "ResponseMock", "Dict[str, Any]", "Optional[str]", "HttpResponse", "str", "UserProfile" ]
[ 3084, 6375, 17612, 17627, 18823, 18834, 19903, 40691, 40723, 47327, 75395, 75559, 86242, 106341 ]
[ 3087, 6386, 17615, 17630, 18826, 18837, 19917, 40703, 40735, 47341, 75408, 75571, 86245, 106352 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_bots.py
import filecmp import os import ujson from django.core import mail from django.http import HttpResponse from django.test import override_settings from mock import patch, MagicMock from typing import Any, Dict, List, Mapping from zerver.lib.actions import do_change_stream_invite_only, do_deactivate_user from zerver.lib.bot_config import get_bot_config from zerver.models import get_realm, get_stream, \ Realm, Stream, UserProfile, get_user, get_bot_services, Service, \ is_cross_realm_bot_email from zerver.lib.test_classes import ZulipTestCase, UploadSerializeMixin from zerver.lib.test_helpers import ( avatar_disk_path, get_test_image_file, queries_captured, tornado_redirected_to_list, ) from zerver.lib.integrations import EMBEDDED_BOTS from zerver.lib.bot_lib import get_bot_handler from zulip_bots.custom_exceptions import ConfigValidationError class BotTest(ZulipTestCase, UploadSerializeMixin): def get_bot_user(self, email: str) -> UserProfile: realm = get_realm("zulip") bot = get_user(email, realm) return bot def assert_num_bots_equal(self, count: int) -> None: result = self.client_get("/json/bots") self.assert_json_success(result) self.assertEqual(count, len(result.json()['bots'])) def create_bot(self, **extras: Any) -> Dict[str, Any]: bot_info = { 'full_name': 'The Bot of Hamlet', 'short_name': 'hambot', 'bot_type': '1', } bot_info.update(extras) result = self.client_post("/json/bots", bot_info) self.assert_json_success(result) return result.json() def test_bot_domain(self) -> None: self.login(self.example_email('hamlet')) self.create_bot() self.assertTrue(UserProfile.objects.filter(email='hambot-bot@zulip.testserver').exists()) # The other cases are hard to test directly, since we don't allow creating bots from # the wrong subdomain, and because 'testserver.example.com' is not a valid domain for the bot's email. # So we just test the Raelm.get_bot_domain function. realm = get_realm('zulip') self.assertEqual(realm.get_bot_domain(), 'zulip.testserver') def deactivate_bot(self) -> None: email = 'hambot-bot@zulip.testserver' result = self.client_delete("/json/bots/{}".format(self.get_bot_user(email).id)) self.assert_json_success(result) def test_add_bot_with_bad_username(self) -> None: self.login(self.example_email('hamlet')) self.assert_num_bots_equal(0) # Invalid username bot_info = dict( full_name='My bot name', short_name='@', ) result = self.client_post("/json/bots", bot_info) self.assert_json_error(result, 'Bad name or username') self.assert_num_bots_equal(0) # Empty username bot_info = dict( full_name='My bot name', short_name='', ) result = self.client_post("/json/bots", bot_info) self.assert_json_error(result, 'Bad name or username') self.assert_num_bots_equal(0) def test_add_bot_with_no_name(self) -> None: self.login(self.example_email('hamlet')) self.assert_num_bots_equal(0) bot_info = dict( full_name='a', short_name='bot', ) result = self.client_post("/json/bots", bot_info) self.assert_json_error(result, 'Name too short!') self.assert_num_bots_equal(0) def test_json_users_with_bots(self) -> None: hamlet = self.example_user('hamlet') self.login(hamlet.email) self.assert_num_bots_equal(0) num_bots = 30 for i in range(num_bots): full_name = 'Bot %d' % (i,) short_name = 'bot-%d' % (i,) bot_info = dict( full_name=full_name, short_name=short_name, bot_type=1 ) result = self.client_post("/json/bots", bot_info) self.assert_json_success(result) self.assert_num_bots_equal(num_bots) with queries_captured() as queries: users_result = self.client_get('/json/users') self.assert_json_success(users_result) self.assert_length(queries, 3) def test_add_bot(self) -> None: self.login(self.example_email('hamlet')) self.assert_num_bots_equal(0) events = [] # type: List[Mapping[str, Any]] with tornado_redirected_to_list(events): result = self.create_bot() self.assert_num_bots_equal(1) email = 'hambot-bot@zulip.testserver' bot = self.get_bot_user(email) event = [e for e in events if e['event']['type'] == 'realm_bot'][0] self.assertEqual( dict( type='realm_bot', op='add', bot=dict(email='hambot-bot@zulip.testserver', user_id=bot.id, bot_type=bot.bot_type, full_name='The Bot of Hamlet', is_active=True, api_key=result['api_key'], avatar_url=result['avatar_url'], default_sending_stream=None, default_events_register_stream=None, default_all_public_streams=False, services=[], owner=self.example_email('hamlet')) ), event['event'] ) users_result = self.client_get('/json/users') members = ujson.loads(users_result.content)['members'] bots = [m for m in members if m['email'] == 'hambot-bot@zulip.testserver'] self.assertEqual(len(bots), 1) bot = bots[0] self.assertEqual(bot['bot_owner'], self.example_email('hamlet')) self.assertEqual(bot['user_id'], self.get_bot_user(email).id) def test_add_bot_with_username_in_use(self) -> None: self.login(self.example_email('hamlet')) self.assert_num_bots_equal(0) result = self.create_bot() self.assert_num_bots_equal(1) # The short_name is used in the email, which we call # "Username" for legacy reasons. bot_info = dict( full_name='whatever', short_name='hambot', ) result = self.client_post("/json/bots", bot_info) self.assert_json_error(result, 'Username already in use') dup_full_name = 'The Bot of Hamlet' bot_info = dict( full_name=dup_full_name, short_name='whatever', ) result = self.client_post("/json/bots", bot_info) self.assert_json_error(result, 'Name is already in use!') def test_add_bot_with_user_avatar(self) -> None: email = 'hambot-bot@zulip.testserver' realm = get_realm('zulip') self.login(self.example_email('hamlet')) self.assert_num_bots_equal(0) with get_test_image_file('img.png') as fp: self.create_bot(file=fp) profile = get_user(email, realm) # Make sure that avatar image that we've uploaded is same with avatar image in the server self.assertTrue(filecmp.cmp(fp.name, os.path.splitext(avatar_disk_path(profile))[0] + ".original")) self.assert_num_bots_equal(1) self.assertEqual(profile.avatar_source, UserProfile.AVATAR_FROM_USER) self.assertTrue(os.path.exists(avatar_disk_path(profile))) def test_add_bot_with_too_many_files(self) -> None: self.login(self.example_email('hamlet')) self.assert_num_bots_equal(0) with get_test_image_file('img.png') as fp1, \ get_test_image_file('img.gif') as fp2: bot_info = dict( full_name='whatever', short_name='whatever', file1=fp1, file2=fp2, ) result = self.client_post("/json/bots", bot_info) self.assert_json_error(result, 'You may only upload one file at a time') self.assert_num_bots_equal(0) def test_add_bot_with_default_sending_stream(self) -> None: email = 'hambot-bot@zulip.testserver' realm = get_realm('zulip') self.login(self.example_email('hamlet')) self.assert_num_bots_equal(0) result = self.create_bot(default_sending_stream='Denmark') self.assert_num_bots_equal(1) self.assertEqual(result['default_sending_stream'], 'Denmark') profile = get_user(email, realm) assert(profile.default_sending_stream is not None) self.assertEqual(profile.default_sending_stream.name, 'Denmark') def test_add_bot_with_default_sending_stream_not_subscribed(self) -> None: email = 'hambot-bot@zulip.testserver' realm = get_realm('zulip') self.login(self.example_email('hamlet')) self.assert_num_bots_equal(0) result = self.create_bot(default_sending_stream='Rome') self.assert_num_bots_equal(1) self.assertEqual(result['default_sending_stream'], 'Rome') profile = get_user(email, realm) assert(profile.default_sending_stream is not None) self.assertEqual(profile.default_sending_stream.name, 'Rome') def test_bot_add_subscription(self) -> None: """ Calling POST /json/users/me/subscriptions should successfully add streams, and a stream to the list of subscriptions and confirm the right number of events are generated. When 'principals' has a bot, no notification message event or invitation email is sent when add_subscriptions_backend is called in the above api call. """ self.login(self.example_email('hamlet')) # Normal user i.e. not a bot. request_data = { 'principals': '["' + self.example_email('iago') + '"]' } events = [] # type: List[Mapping[str, Any]] with tornado_redirected_to_list(events): result = self.common_subscribe_to_streams(self.example_email('hamlet'), ['Rome'], request_data) self.assert_json_success(result) msg_event = [e for e in events if e['event']['type'] == 'message'] self.assert_length(msg_event, 1) # Notification message event is sent. # Create a bot. self.assert_num_bots_equal(0) result = self.create_bot() self.assert_num_bots_equal(1) # A bot bot_request_data = { 'principals': '["hambot-bot@zulip.testserver"]' } events_bot = [] # type: List[Mapping[str, Any]] with tornado_redirected_to_list(events_bot): result = self.common_subscribe_to_streams(self.example_email('hamlet'), ['Rome'], bot_request_data) self.assert_json_success(result) # No notification message event or invitation email is sent because of bot. msg_event = [e for e in events_bot if e['event']['type'] == 'message'] self.assert_length(msg_event, 0) self.assertEqual(len(events_bot), len(events) - 1) # Test runner automatically redirects all sent email to a dummy 'outbox'. self.assertEqual(len(mail.outbox), 0) def test_add_bot_with_default_sending_stream_private_allowed(self) -> None: self.login(self.example_email('hamlet')) user_profile = self.example_user('hamlet') stream = get_stream("Denmark", user_profile.realm) self.subscribe(user_profile, stream.name) do_change_stream_invite_only(stream, True) self.assert_num_bots_equal(0) events = [] # type: List[Mapping[str, Any]] with tornado_redirected_to_list(events): result = self.create_bot(default_sending_stream='Denmark') self.assert_num_bots_equal(1) self.assertEqual(result['default_sending_stream'], 'Denmark') email = 'hambot-bot@zulip.testserver' realm = get_realm('zulip') profile = get_user(email, realm) assert(profile.default_sending_stream is not None) self.assertEqual(profile.default_sending_stream.name, 'Denmark') event = [e for e in events if e['event']['type'] == 'realm_bot'][0] self.assertEqual( dict( type='realm_bot', op='add', bot=dict(email='hambot-bot@zulip.testserver', user_id=profile.id, full_name='The Bot of Hamlet', bot_type=profile.bot_type, is_active=True, api_key=result['api_key'], avatar_url=result['avatar_url'], default_sending_stream='Denmark', default_events_register_stream=None, default_all_public_streams=False, services=[], owner=self.example_email('hamlet')) ), event['event'] ) self.assertEqual(event['users'], {user_profile.id, }) def test_add_bot_with_default_sending_stream_private_denied(self) -> None: self.login(self.example_email('hamlet')) realm = self.example_user('hamlet').realm stream = get_stream("Denmark", realm) self.unsubscribe(self.example_user('hamlet'), "Denmark") do_change_stream_invite_only(stream, True) bot_info = { 'full_name': 'The Bot of Hamlet', 'short_name': 'hambot', 'default_sending_stream': 'Denmark', } result = self.client_post("/json/bots", bot_info) self.assert_json_error(result, "Invalid stream name 'Denmark'") def test_add_bot_with_default_events_register_stream(self) -> None: bot_email = 'hambot-bot@zulip.testserver' bot_realm = get_realm('zulip') self.login(self.example_email('hamlet')) self.assert_num_bots_equal(0) result = self.create_bot(default_events_register_stream='Denmark') self.assert_num_bots_equal(1) self.assertEqual(result['default_events_register_stream'], 'Denmark') profile = get_user(bot_email, bot_realm) assert(profile.default_events_register_stream is not None) self.assertEqual(profile.default_events_register_stream.name, 'Denmark') def test_add_bot_with_default_events_register_stream_private_allowed(self) -> None: self.login(self.example_email('hamlet')) user_profile = self.example_user('hamlet') stream = self.subscribe(user_profile, 'Denmark') do_change_stream_invite_only(stream, True) self.assert_num_bots_equal(0) events = [] # type: List[Mapping[str, Any]] with tornado_redirected_to_list(events): result = self.create_bot(default_events_register_stream='Denmark') self.assert_num_bots_equal(1) self.assertEqual(result['default_events_register_stream'], 'Denmark') bot_email = 'hambot-bot@zulip.testserver' bot_realm = get_realm('zulip') bot_profile = get_user(bot_email, bot_realm) assert(bot_profile.default_events_register_stream is not None) self.assertEqual(bot_profile.default_events_register_stream.name, 'Denmark') event = [e for e in events if e['event']['type'] == 'realm_bot'][0] self.assertEqual( dict( type='realm_bot', op='add', bot=dict(email='hambot-bot@zulip.testserver', full_name='The Bot of Hamlet', user_id=bot_profile.id, bot_type=bot_profile.bot_type, is_active=True, api_key=result['api_key'], avatar_url=result['avatar_url'], default_sending_stream=None, default_events_register_stream='Denmark', default_all_public_streams=False, services=[], owner=self.example_email('hamlet')) ), event['event'] ) self.assertEqual(event['users'], {user_profile.id, }) def test_add_bot_with_default_events_register_stream_private_denied(self) -> None: self.login(self.example_email('hamlet')) realm = self.example_user('hamlet').realm stream = get_stream("Denmark", realm) self.unsubscribe(self.example_user('hamlet'), "Denmark") do_change_stream_invite_only(stream, True) self.assert_num_bots_equal(0) bot_info = { 'full_name': 'The Bot of Hamlet', 'short_name': 'hambot', 'default_events_register_stream': 'Denmark', } result = self.client_post("/json/bots", bot_info) self.assert_json_error(result, "Invalid stream name 'Denmark'") def test_add_bot_with_default_all_public_streams(self) -> None: self.login(self.example_email('hamlet')) self.assert_num_bots_equal(0) result = self.create_bot(default_all_public_streams=ujson.dumps(True)) self.assert_num_bots_equal(1) self.assertTrue(result['default_all_public_streams']) bot_email = 'hambot-bot@zulip.testserver' bot_realm = get_realm('zulip') profile = get_user(bot_email, bot_realm) self.assertEqual(profile.default_all_public_streams, True) def test_deactivate_bot(self) -> None: self.login(self.example_email('hamlet')) self.assert_num_bots_equal(0) self.create_bot() self.assert_num_bots_equal(1) self.deactivate_bot() # You can deactivate the same bot twice. self.deactivate_bot() self.assert_num_bots_equal(0) def test_deactivate_bogus_bot(self) -> None: """Deleting a bogus bot will succeed silently.""" self.login(self.example_email('hamlet')) self.assert_num_bots_equal(0) self.create_bot() self.assert_num_bots_equal(1) invalid_user_id = 1000 result = self.client_delete("/json/bots/{}".format(invalid_user_id)) self.assert_json_error(result, 'No such bot') self.assert_num_bots_equal(1) def test_deactivate_bot_with_owner_deactivation(self) -> None: email = self.example_email("hamlet") user = self.example_user('hamlet') self.login(email) bot_info = { 'full_name': u'The Bot of Hamlet', 'short_name': u'hambot', } result = self.client_post("/json/bots", bot_info) self.assert_json_success(result) bot_info = { 'full_name': u'The Another Bot of Hamlet', 'short_name': u'hambot-another', } result = self.client_post("/json/bots", bot_info) self.assert_json_success(result) all_bots = UserProfile.objects.filter(is_bot=True, bot_owner=user, is_active=True) bots = [bot for bot in all_bots] self.assertEqual(len(bots), 2) result = self.client_delete('/json/users/me') self.assert_json_success(result) user = self.example_user('hamlet') self.assertFalse(user.is_active) self.login(self.example_email("iago")) all_bots = UserProfile.objects.filter(is_bot=True, bot_owner=user, is_active=True) bots = [bot for bot in all_bots] self.assertEqual(len(bots), 0) def test_cannot_deactivate_other_realm_bot(self) -> None: realm = get_realm("zephyr") self.login(self.mit_email("starnine"), realm=realm) bot_info = { 'full_name': 'The Bot in zephyr', 'short_name': 'starn-bot', 'bot_type': '1', } result = self.client_post("/json/bots", bot_info, subdomain="zephyr") self.assert_json_success(result) result = self.client_get("/json/bots", subdomain="zephyr") bot_email = result.json()['bots'][0]['username'] bot = get_user(bot_email, realm) self.login(self.example_email("iago")) result = self.client_delete("/json/bots/{}".format(bot.id)) self.assert_json_error(result, 'No such bot') def test_bot_deactivation_attacks(self) -> None: """You cannot deactivate somebody else's bot.""" self.login(self.example_email('hamlet')) self.assert_num_bots_equal(0) self.create_bot() self.assert_num_bots_equal(1) # Have Othello try to deactivate both Hamlet and # Hamlet's bot. self.login(self.example_email('othello')) # Cannot deactivate a user as a bot result = self.client_delete("/json/bots/{}".format(self.example_user("hamlet").id)) self.assert_json_error(result, 'No such bot') email = 'hambot-bot@zulip.testserver' result = self.client_delete("/json/bots/{}".format(self.get_bot_user(email).id)) self.assert_json_error(result, 'Insufficient permission') # But we don't actually deactivate the other person's bot. self.login(self.example_email('hamlet')) self.assert_num_bots_equal(1) # Cannot deactivate a bot as a user result = self.client_delete("/json/users/{}".format(self.get_bot_user(email).id)) self.assert_json_error(result, 'No such user') self.assert_num_bots_equal(1) def test_bot_permissions(self) -> None: self.login(self.example_email('hamlet')) self.assert_num_bots_equal(0) self.create_bot() self.assert_num_bots_equal(1) # Have Othello try to mess with Hamlet's bots. self.login(self.example_email('othello')) email = 'hambot-bot@zulip.testserver' result = self.client_post("/json/bots/{}/api_key/regenerate".format(self.get_bot_user(email).id)) self.assert_json_error(result, 'Insufficient permission') bot_info = { 'full_name': 'Fred', } result = self.client_patch("/json/bots/{}".format(self.get_bot_user(email).id), bot_info) self.assert_json_error(result, 'Insufficient permission') def get_bot(self) -> Dict[str, Any]: result = self.client_get("/json/bots") bots = result.json()['bots'] return bots[0] def test_update_api_key(self) -> None: self.login(self.example_email('hamlet')) self.create_bot() bot = self.get_bot() old_api_key = bot['api_key'] email = 'hambot-bot@zulip.testserver' result = self.client_post('/json/bots/{}/api_key/regenerate'.format(self.get_bot_user(email).id)) self.assert_json_success(result) new_api_key = result.json()['api_key'] self.assertNotEqual(old_api_key, new_api_key) bot = self.get_bot() self.assertEqual(new_api_key, bot['api_key']) def test_update_api_key_for_invalid_user(self) -> None: self.login(self.example_email('hamlet')) invalid_user_id = 1000 result = self.client_post('/json/bots/{}/api_key/regenerate'.format(invalid_user_id)) self.assert_json_error(result, 'No such bot') def test_add_bot_with_bot_type_default(self) -> None: bot_email = 'hambot-bot@zulip.testserver' bot_realm = get_realm('zulip') self.login(self.example_email('hamlet')) self.assert_num_bots_equal(0) self.create_bot(bot_type=UserProfile.DEFAULT_BOT) self.assert_num_bots_equal(1) profile = get_user(bot_email, bot_realm) self.assertEqual(profile.bot_type, UserProfile.DEFAULT_BOT) def test_add_bot_with_bot_type_incoming_webhook(self) -> None: bot_email = 'hambot-bot@zulip.testserver' bot_realm = get_realm('zulip') self.login(self.example_email('hamlet')) self.assert_num_bots_equal(0) self.create_bot(bot_type=UserProfile.INCOMING_WEBHOOK_BOT) self.assert_num_bots_equal(1) profile = get_user(bot_email, bot_realm) self.assertEqual(profile.bot_type, UserProfile.INCOMING_WEBHOOK_BOT) def test_add_bot_with_bot_type_invalid(self) -> None: bot_info = { 'full_name': 'The Bot of Hamlet', 'short_name': 'hambot', 'bot_type': 7, } self.login(self.example_email('hamlet')) self.assert_num_bots_equal(0) result = self.client_post("/json/bots", bot_info) self.assert_num_bots_equal(0) self.assert_json_error(result, 'Invalid bot type') def test_no_generic_bots_allowed_for_non_admins(self) -> None: bot_info = { 'full_name': 'The Bot of Hamlet', 'short_name': 'hambot', 'bot_type': 1, } bot_email = 'hambot-bot@zulip.testserver' bot_realm = get_realm('zulip') bot_realm.bot_creation_policy = Realm.BOT_CREATION_LIMIT_GENERIC_BOTS bot_realm.save(update_fields=['bot_creation_policy']) # A regular user cannot create a generic bot self.login(self.example_email('hamlet')) self.assert_num_bots_equal(0) result = self.client_post("/json/bots", bot_info) self.assert_num_bots_equal(0) self.assert_json_error(result, 'Must be an organization administrator') # But can create an incoming webhook self.assert_num_bots_equal(0) self.create_bot(bot_type=UserProfile.INCOMING_WEBHOOK_BOT) self.assert_num_bots_equal(1) profile = get_user(bot_email, bot_realm) self.assertEqual(profile.bot_type, UserProfile.INCOMING_WEBHOOK_BOT) def test_no_generic_bot_reactivation_allowed_for_non_admins(self) -> None: self.login(self.example_email('hamlet')) self.create_bot(bot_type=UserProfile.DEFAULT_BOT) bot_realm = get_realm('zulip') bot_realm.bot_creation_policy = Realm.BOT_CREATION_LIMIT_GENERIC_BOTS bot_realm.save(update_fields=['bot_creation_policy']) bot_email = 'hambot-bot@zulip.testserver' bot_user = get_user(bot_email, bot_realm) do_deactivate_user(bot_user) # A regular user cannot reactivate a generic bot self.assert_num_bots_equal(0) result = self.client_post("/json/users/%s/reactivate" % (bot_user.id,)) self.assert_json_error(result, 'Must be an organization administrator') self.assert_num_bots_equal(0) def test_no_generic_bots_allowed_for_admins(self) -> None: bot_email = 'hambot-bot@zulip.testserver' bot_realm = get_realm('zulip') bot_realm.bot_creation_policy = Realm.BOT_CREATION_LIMIT_GENERIC_BOTS bot_realm.save(update_fields=['bot_creation_policy']) # An administrator can create any type of bot self.login(self.example_email('iago')) self.assert_num_bots_equal(0) self.create_bot(bot_type=UserProfile.DEFAULT_BOT) self.assert_num_bots_equal(1) profile = get_user(bot_email, bot_realm) self.assertEqual(profile.bot_type, UserProfile.DEFAULT_BOT) def test_no_bots_allowed_for_non_admins(self) -> None: bot_info = { 'full_name': 'The Bot of Hamlet', 'short_name': 'hambot', 'bot_type': 1, } bot_realm = get_realm('zulip') bot_realm.bot_creation_policy = Realm.BOT_CREATION_ADMINS_ONLY bot_realm.save(update_fields=['bot_creation_policy']) # A regular user cannot create a generic bot self.login(self.example_email('hamlet')) self.assert_num_bots_equal(0) result = self.client_post("/json/bots", bot_info) self.assert_num_bots_equal(0) self.assert_json_error(result, 'Must be an organization administrator') # Also, a regular user cannot create a incoming bot bot_info['bot_type'] = 2 self.login(self.example_email('hamlet')) self.assert_num_bots_equal(0) result = self.client_post("/json/bots", bot_info) self.assert_num_bots_equal(0) self.assert_json_error(result, 'Must be an organization administrator') def test_no_bots_allowed_for_admins(self) -> None: bot_email = 'hambot-bot@zulip.testserver' bot_realm = get_realm('zulip') bot_realm.bot_creation_policy = Realm.BOT_CREATION_ADMINS_ONLY bot_realm.save(update_fields=['bot_creation_policy']) # An administrator can create any type of bot self.login(self.example_email('iago')) self.assert_num_bots_equal(0) self.create_bot(bot_type=UserProfile.DEFAULT_BOT) self.assert_num_bots_equal(1) profile = get_user(bot_email, bot_realm) self.assertEqual(profile.bot_type, UserProfile.DEFAULT_BOT) def test_patch_bot_full_name(self) -> None: self.login(self.example_email('hamlet')) bot_info = { 'full_name': 'The Bot of Hamlet', 'short_name': 'hambot', } result = self.client_post("/json/bots", bot_info) self.assert_json_success(result) bot_info = { 'full_name': 'Fred', } email = 'hambot-bot@zulip.testserver' result = self.client_patch("/json/bots/{}".format(self.get_bot_user(email).id), bot_info) self.assert_json_success(result) self.assertEqual('Fred', result.json()['full_name']) bot = self.get_bot() self.assertEqual('Fred', bot['full_name']) def test_patch_bot_full_name_in_use(self) -> None: self.login(self.example_email('hamlet')) original_name = 'The Bot of Hamlet' bot_info = { 'full_name': original_name, 'short_name': 'hambot', } result = self.client_post("/json/bots", bot_info) self.assert_json_success(result) bot_email = 'hambot-bot@zulip.testserver' bot = self.get_bot_user(bot_email) url = "/json/bots/{}".format(bot.id) # It doesn't matter whether a name is taken by a human # or a bot, we can't use it. already_taken_name = self.example_user('cordelia').full_name bot_info = { 'full_name': already_taken_name, } result = self.client_patch(url, bot_info) self.assert_json_error(result, "Name is already in use!") # We can use our own name (with extra whitespace), and the # server should silently do nothing. original_name_with_padding = ' ' + original_name + ' ' bot_info = { 'full_name': original_name_with_padding, } result = self.client_patch(url, bot_info) self.assert_json_success(result) bot = self.get_bot_user(bot_email) self.assertEqual(bot.full_name, original_name) # And let's do a sanity check with an actual name change # after our various attempts that either failed or did # nothing. bot_info = { 'full_name': 'Hal', } result = self.client_patch(url, bot_info) self.assert_json_success(result) bot = self.get_bot_user(bot_email) self.assertEqual(bot.full_name, 'Hal') def test_patch_bot_full_name_non_bot(self) -> None: self.login(self.example_email('iago')) bot_info = { 'full_name': 'Fred', } result = self.client_patch("/json/bots/{}".format(self.example_user("hamlet").id), bot_info) self.assert_json_error(result, "No such bot") def test_patch_bot_owner(self) -> None: self.login(self.example_email('hamlet')) bot_info = { 'full_name': u'The Bot of Hamlet', 'short_name': u'hambot', } result = self.client_post("/json/bots", bot_info) self.assert_json_success(result) bot_info = { 'bot_owner_id': self.example_user('othello').id, } email = 'hambot-bot@zulip.testserver' result = self.client_patch("/json/bots/{}".format(self.get_bot_user(email).id), bot_info) self.assert_json_success(result) # Test bot's owner has been changed successfully. self.assertEqual(result.json()['bot_owner'], self.example_email('othello')) self.login(self.example_email('othello')) bot = self.get_bot() self.assertEqual('The Bot of Hamlet', bot['full_name']) def test_patch_bot_owner_bad_user_id(self) -> None: self.login(self.example_email('hamlet')) self.create_bot() self.assert_num_bots_equal(1) email = 'hambot-bot@zulip.testserver' profile = get_user('hambot-bot@zulip.testserver', get_realm('zulip')) bad_bot_owner_id = 999999 bot_info = { 'bot_owner_id': bad_bot_owner_id, } result = self.client_patch("/json/bots/{}".format(self.get_bot_user(email).id), bot_info) self.assert_json_error(result, "Failed to change owner, no such user") profile = get_user('hambot-bot@zulip.testserver', get_realm('zulip')) self.assertEqual(profile.bot_owner, self.example_user("hamlet")) def test_patch_bot_owner_deactivated(self) -> None: self.login(self.example_email('hamlet')) self.create_bot() self.assert_num_bots_equal(1) target_user_profile = self.example_user("othello") do_deactivate_user(target_user_profile) target_user_profile = self.example_user('othello') self.assertFalse(target_user_profile.is_active) bot_info = { 'bot_owner_id': self.example_user('othello').id, } email = 'hambot-bot@zulip.testserver' result = self.client_patch("/json/bots/{}".format(self.get_bot_user(email).id), bot_info) self.assert_json_error(result, "Failed to change owner, user is deactivated") profile = self.get_bot_user(email) self.assertEqual(profile.bot_owner, self.example_user("hamlet")) def test_patch_bot_owner_must_be_in_same_realm(self) -> None: self.login(self.example_email('hamlet')) self.create_bot() self.assert_num_bots_equal(1) bot_info = { 'bot_owner_id': self.mit_user("starnine").id, } email = 'hambot-bot@zulip.testserver' result = self.client_patch("/json/bots/{}".format(self.get_bot_user(email).id), bot_info) self.assert_json_error(result, "Failed to change owner, no such user") profile = self.get_bot_user(email) self.assertEqual(profile.bot_owner, self.example_user("hamlet")) def test_patch_bot_owner_noop(self) -> None: self.login(self.example_email('hamlet')) self.create_bot() self.assert_num_bots_equal(1) bot_info = { 'bot_owner_id': self.example_user('hamlet').id, } email = 'hambot-bot@zulip.testserver' result = self.client_patch("/json/bots/{}".format(self.get_bot_user(email).id), bot_info) # Check that we're still the owner self.assert_json_success(result) profile = self.get_bot_user(email) self.assertEqual(profile.bot_owner, self.example_user("hamlet")) def test_patch_bot_owner_a_bot(self) -> None: self.login(self.example_email('hamlet')) self.create_bot() self.assert_num_bots_equal(1) bot_info = { 'full_name': u'Another Bot of Hamlet', 'short_name': u'hamelbot', } result = self.client_post("/json/bots", bot_info) self.assert_json_success(result) bot_info = { 'bot_owner_id': self.get_bot_user('hamelbot-bot@zulip.testserver').id, } email = 'hambot-bot@zulip.testserver' result = self.client_patch("/json/bots/{}".format(self.get_bot_user(email).id), bot_info) self.assert_json_error(result, "Failed to change owner, bots can't own other bots") profile = get_user(email, get_realm('zulip')) self.assertEqual(profile.bot_owner, self.example_user("hamlet")) @override_settings(LOCAL_UPLOADS_DIR='var/bot_avatar') def test_patch_bot_avatar(self) -> None: self.login(self.example_email('hamlet')) bot_info = { 'full_name': 'The Bot of Hamlet', 'short_name': 'hambot', } result = self.client_post("/json/bots", bot_info) self.assert_json_success(result) bot_email = 'hambot-bot@zulip.testserver' bot_realm = get_realm('zulip') profile = get_user(bot_email, bot_realm) self.assertEqual(profile.avatar_source, UserProfile.AVATAR_FROM_GRAVATAR) email = 'hambot-bot@zulip.testserver' # Try error case first (too many files): with get_test_image_file('img.png') as fp1, \ get_test_image_file('img.gif') as fp2: result = self.client_patch_multipart( '/json/bots/{}'.format(self.get_bot_user(email).id), dict(file1=fp1, file2=fp2)) self.assert_json_error(result, 'You may only upload one file at a time') profile = get_user(bot_email, bot_realm) self.assertEqual(profile.avatar_version, 1) # HAPPY PATH with get_test_image_file('img.png') as fp: result = self.client_patch_multipart( '/json/bots/{}'.format(self.get_bot_user(email).id), dict(file=fp)) profile = get_user(bot_email, bot_realm) self.assertEqual(profile.avatar_version, 2) # Make sure that avatar image that we've uploaded is same with avatar image in the server self.assertTrue(filecmp.cmp(fp.name, os.path.splitext(avatar_disk_path(profile))[0] + ".original")) self.assert_json_success(result) self.assertEqual(profile.avatar_source, UserProfile.AVATAR_FROM_USER) self.assertTrue(os.path.exists(avatar_disk_path(profile))) def test_patch_bot_to_stream(self) -> None: self.login(self.example_email('hamlet')) bot_info = { 'full_name': 'The Bot of Hamlet', 'short_name': 'hambot', } result = self.client_post("/json/bots", bot_info) self.assert_json_success(result) bot_info = { 'default_sending_stream': 'Denmark', } email = 'hambot-bot@zulip.testserver' result = self.client_patch("/json/bots/{}".format(self.get_bot_user(email).id), bot_info) self.assert_json_success(result) self.assertEqual('Denmark', result.json()['default_sending_stream']) bot = self.get_bot() self.assertEqual('Denmark', bot['default_sending_stream']) def test_patch_bot_to_stream_not_subscribed(self) -> None: self.login(self.example_email('hamlet')) bot_info = { 'full_name': 'The Bot of Hamlet', 'short_name': 'hambot', } result = self.client_post("/json/bots", bot_info) self.assert_json_success(result) bot_info = { 'default_sending_stream': 'Rome', } email = 'hambot-bot@zulip.testserver' result = self.client_patch("/json/bots/{}".format(self.get_bot_user(email).id), bot_info) self.assert_json_success(result) self.assertEqual('Rome', result.json()['default_sending_stream']) bot = self.get_bot() self.assertEqual('Rome', bot['default_sending_stream']) def test_patch_bot_to_stream_none(self) -> None: self.login(self.example_email('hamlet')) bot_info = { 'full_name': 'The Bot of Hamlet', 'short_name': 'hambot', } result = self.client_post("/json/bots", bot_info) self.assert_json_success(result) bot_info = { 'default_sending_stream': '', } email = 'hambot-bot@zulip.testserver' result = self.client_patch("/json/bots/{}".format(self.get_bot_user(email).id), bot_info) self.assert_json_success(result) bot_email = "hambot-bot@zulip.testserver" bot_realm = get_realm('zulip') default_sending_stream = get_user(bot_email, bot_realm).default_sending_stream self.assertEqual(None, default_sending_stream) bot = self.get_bot() self.assertEqual(None, bot['default_sending_stream']) def test_patch_bot_to_stream_private_allowed(self) -> None: self.login(self.example_email('hamlet')) user_profile = self.example_user('hamlet') stream = self.subscribe(user_profile, "Denmark") do_change_stream_invite_only(stream, True) bot_info = { 'full_name': 'The Bot of Hamlet', 'short_name': 'hambot', } result = self.client_post("/json/bots", bot_info) self.assert_json_success(result) bot_info = { 'default_sending_stream': 'Denmark', } email = 'hambot-bot@zulip.testserver' result = self.client_patch("/json/bots/{}".format(self.get_bot_user(email).id), bot_info) self.assert_json_success(result) self.assertEqual('Denmark', result.json()['default_sending_stream']) bot = self.get_bot() self.assertEqual('Denmark', bot['default_sending_stream']) def test_patch_bot_to_stream_private_denied(self) -> None: self.login(self.example_email('hamlet')) realm = self.example_user('hamlet').realm stream = get_stream("Denmark", realm) self.unsubscribe(self.example_user('hamlet'), "Denmark") do_change_stream_invite_only(stream, True) bot_info = { 'full_name': 'The Bot of Hamlet', 'short_name': 'hambot', } result = self.client_post("/json/bots", bot_info) self.assert_json_success(result) bot_info = { 'default_sending_stream': 'Denmark', } email = 'hambot-bot@zulip.testserver' result = self.client_patch("/json/bots/{}".format(self.get_bot_user(email).id), bot_info) self.assert_json_error(result, "Invalid stream name 'Denmark'") def test_patch_bot_to_stream_not_found(self) -> None: self.login(self.example_email('hamlet')) bot_info = { 'full_name': 'The Bot of Hamlet', 'short_name': 'hambot', } result = self.client_post("/json/bots", bot_info) self.assert_json_success(result) bot_info = { 'default_sending_stream': 'missing', } email = 'hambot-bot@zulip.testserver' result = self.client_patch("/json/bots/{}".format(self.get_bot_user(email).id), bot_info) self.assert_json_error(result, "Invalid stream name 'missing'") def test_patch_bot_events_register_stream(self) -> None: hamlet = self.example_user('hamlet') self.login(hamlet.email) bot_info = { 'full_name': 'The Bot of Hamlet', 'short_name': 'hambot', } result = self.client_post("/json/bots", bot_info) self.assert_json_success(result) email = 'hambot-bot@zulip.testserver' bot_user = self.get_bot_user(email) url = "/json/bots/{}".format(bot_user.id) # Successfully give the bot a default stream. stream_name = 'Denmark' bot_info = dict(default_events_register_stream=stream_name) result = self.client_patch(url, bot_info) self.assert_json_success(result) self.assertEqual(stream_name, result.json()['default_events_register_stream']) bot = self.get_bot() self.assertEqual(stream_name, bot['default_events_register_stream']) # Make sure we are locked out of an unsubscribed private stream. # We'll subscribe the bot but not the owner (since the check is # on owner). stream_name = 'private_stream' self.make_stream(stream_name, hamlet.realm, invite_only=True) self.subscribe(bot_user, stream_name) bot_info = dict(default_events_register_stream=stream_name) result = self.client_patch(url, bot_info) self.assert_json_error_contains(result, 'Invalid stream name') # Subscribing the owner allows us to patch the stream. self.subscribe(hamlet, stream_name) bot_info = dict(default_events_register_stream=stream_name) result = self.client_patch(url, bot_info) self.assert_json_success(result) # Make sure the bot cannot create their own default stream. url = "/api/v1/bots/{}".format(bot_user.id) result = self.api_patch(bot_user.email, url, bot_info) self.assert_json_error_contains(result, 'endpoint does not accept') def test_patch_bot_events_register_stream_allowed(self) -> None: self.login(self.example_email('hamlet')) user_profile = self.example_user('hamlet') stream = self.subscribe(user_profile, "Denmark") do_change_stream_invite_only(stream, True) bot_info = { 'full_name': 'The Bot of Hamlet', 'short_name': 'hambot', } result = self.client_post("/json/bots", bot_info) self.assert_json_success(result) bot_info = { 'default_events_register_stream': 'Denmark', } email = 'hambot-bot@zulip.testserver' result = self.client_patch("/json/bots/{}".format(self.get_bot_user(email).id), bot_info) self.assert_json_success(result) self.assertEqual('Denmark', result.json()['default_events_register_stream']) bot = self.get_bot() self.assertEqual('Denmark', bot['default_events_register_stream']) def test_patch_bot_events_register_stream_denied(self) -> None: self.login(self.example_email('hamlet')) realm = self.example_user('hamlet').realm stream = get_stream("Denmark", realm) self.unsubscribe(self.example_user('hamlet'), "Denmark") do_change_stream_invite_only(stream, True) bot_info = { 'full_name': 'The Bot of Hamlet', 'short_name': 'hambot', } result = self.client_post("/json/bots", bot_info) self.assert_json_success(result) bot_info = { 'default_events_register_stream': 'Denmark', } email = 'hambot-bot@zulip.testserver' result = self.client_patch("/json/bots/{}".format(self.get_bot_user(email).id), bot_info) self.assert_json_error(result, "Invalid stream name 'Denmark'") def test_patch_bot_events_register_stream_none(self) -> None: self.login(self.example_email('hamlet')) bot_info = { 'full_name': 'The Bot of Hamlet', 'short_name': 'hambot', } result = self.client_post("/json/bots", bot_info) self.assert_json_success(result) bot_info = { 'default_events_register_stream': '', } email = 'hambot-bot@zulip.testserver' result = self.client_patch("/json/bots/{}".format(self.get_bot_user(email).id), bot_info) self.assert_json_success(result) bot_email = "hambot-bot@zulip.testserver" bot_realm = get_realm('zulip') default_events_register_stream = get_user(bot_email, bot_realm).default_events_register_stream self.assertEqual(None, default_events_register_stream) bot = self.get_bot() self.assertEqual(None, bot['default_events_register_stream']) def test_patch_bot_events_register_stream_not_found(self) -> None: self.login(self.example_email('hamlet')) bot_info = { 'full_name': 'The Bot of Hamlet', 'short_name': 'hambot', } result = self.client_post("/json/bots", bot_info) self.assert_json_success(result) bot_info = { 'default_events_register_stream': 'missing', } email = 'hambot-bot@zulip.testserver' result = self.client_patch("/json/bots/{}".format(self.get_bot_user(email).id), bot_info) self.assert_json_error(result, "Invalid stream name 'missing'") def test_patch_bot_default_all_public_streams_true(self) -> None: self.login(self.example_email('hamlet')) bot_info = { 'full_name': 'The Bot of Hamlet', 'short_name': 'hambot', } result = self.client_post("/json/bots", bot_info) self.assert_json_success(result) bot_info = { 'default_all_public_streams': ujson.dumps(True), } email = 'hambot-bot@zulip.testserver' result = self.client_patch("/json/bots/{}".format(self.get_bot_user(email).id), bot_info) self.assert_json_success(result) self.assertEqual(result.json()['default_all_public_streams'], True) bot = self.get_bot() self.assertEqual(bot['default_all_public_streams'], True) def test_patch_bot_default_all_public_streams_false(self) -> None: self.login(self.example_email('hamlet')) bot_info = { 'full_name': 'The Bot of Hamlet', 'short_name': 'hambot', } result = self.client_post("/json/bots", bot_info) self.assert_json_success(result) bot_info = { 'default_all_public_streams': ujson.dumps(False), } email = 'hambot-bot@zulip.testserver' result = self.client_patch("/json/bots/{}".format(self.get_bot_user(email).id), bot_info) self.assert_json_success(result) self.assertEqual(result.json()['default_all_public_streams'], False) bot = self.get_bot() self.assertEqual(bot['default_all_public_streams'], False) def test_patch_bot_via_post(self) -> None: self.login(self.example_email('hamlet')) bot_info = { 'full_name': 'The Bot of Hamlet', 'short_name': 'hambot', } result = self.client_post("/json/bots", bot_info) self.assert_json_success(result) bot_info = { 'full_name': 'Fred', 'method': 'PATCH' } email = 'hambot-bot@zulip.testserver' # Important: We intentionally use the wrong method, post, here. result = self.client_post("/json/bots/{}".format(self.get_bot_user(email).id), bot_info) self.assert_json_success(result) self.assertEqual('Fred', result.json()['full_name']) bot = self.get_bot() self.assertEqual('Fred', bot['full_name']) def test_patch_bogus_bot(self) -> None: """Deleting a bogus bot will succeed silently.""" self.login(self.example_email('hamlet')) self.create_bot() bot_info = { 'full_name': 'Fred', } invalid_user_id = 1000 result = self.client_patch("/json/bots/{}".format(invalid_user_id), bot_info) self.assert_json_error(result, 'No such bot') self.assert_num_bots_equal(1) def test_patch_outgoing_webhook_bot(self) -> None: self.login(self.example_email('hamlet')) bot_info = { 'full_name': u'The Bot of Hamlet', 'short_name': u'hambot', 'bot_type': UserProfile.OUTGOING_WEBHOOK_BOT, 'payload_url': ujson.dumps("http://foo.bar.com"), 'service_interface': Service.GENERIC, } result = self.client_post("/json/bots", bot_info) self.assert_json_success(result) bot_info = { 'service_payload_url': ujson.dumps("http://foo.bar2.com"), 'service_interface': Service.SLACK, } email = 'hambot-bot@zulip.testserver' result = self.client_patch("/json/bots/{}".format(self.get_bot_user(email).id), bot_info) self.assert_json_success(result) service_interface = ujson.loads(result.content)['service_interface'] self.assertEqual(service_interface, Service.SLACK) service_payload_url = ujson.loads(result.content)['service_payload_url'] self.assertEqual(service_payload_url, "http://foo.bar2.com") @patch('zulip_bots.bots.giphy.giphy.GiphyHandler.validate_config') def test_patch_bot_config_data(self, mock_validate_config: MagicMock) -> None: self.create_test_bot('test', self.example_user("hamlet"), full_name=u'Bot with config data', bot_type=UserProfile.EMBEDDED_BOT, service_name='giphy', config_data=ujson.dumps({'key': '12345678'})) bot_info = {'config_data': ujson.dumps({'key': '87654321'})} email = 'test-bot@zulip.testserver' result = self.client_patch("/json/bots/{}".format(self.get_bot_user(email).id), bot_info) self.assert_json_success(result) config_data = ujson.loads(result.content)['config_data'] self.assertEqual(config_data, ujson.loads(bot_info['config_data'])) def test_outgoing_webhook_invalid_interface(self): # type: () -> None self.login(self.example_email('hamlet')) bot_info = { 'full_name': 'Outgoing Webhook test bot', 'short_name': 'outgoingservicebot', 'bot_type': UserProfile.OUTGOING_WEBHOOK_BOT, 'payload_url': ujson.dumps('http://127.0.0.1:5002'), 'interface_type': -1, } result = self.client_post("/json/bots", bot_info) self.assert_json_error(result, 'Invalid interface type') bot_info['interface_type'] = Service.GENERIC result = self.client_post("/json/bots", bot_info) self.assert_json_success(result) def test_create_outgoing_webhook_bot(self, **extras: Any) -> None: self.login(self.example_email('hamlet')) bot_info = { 'full_name': 'Outgoing Webhook test bot', 'short_name': 'outgoingservicebot', 'bot_type': UserProfile.OUTGOING_WEBHOOK_BOT, 'payload_url': ujson.dumps('http://127.0.0.1:5002'), } bot_info.update(extras) result = self.client_post("/json/bots", bot_info) self.assert_json_success(result) bot_email = "outgoingservicebot-bot@zulip.testserver" bot_realm = get_realm('zulip') bot = get_user(bot_email, bot_realm) services = get_bot_services(bot.id) service = services[0] self.assertEqual(len(services), 1) self.assertEqual(service.name, "outgoingservicebot") self.assertEqual(service.base_url, "http://127.0.0.1:5002") self.assertEqual(service.user_profile, bot) # invalid URL test case. bot_info['payload_url'] = ujson.dumps('http://127.0.0.:5002') result = self.client_post("/json/bots", bot_info) self.assert_json_error(result, "payload_url is not a URL") def test_get_bot_handler(self) -> None: # Test for valid service. test_service_name = 'converter' test_bot_handler = get_bot_handler(test_service_name) self.assertEqual(str(type(test_bot_handler)), "<class 'zulip_bots.bots.converter.converter.ConverterHandler'>") # Test for invalid service. test_service_name = "incorrect_bot_service_foo" test_bot_handler = get_bot_handler(test_service_name) self.assertEqual(test_bot_handler, None) def test_if_each_embedded_bot_service_exists(self) -> None: for embedded_bot in EMBEDDED_BOTS: self.assertIsNotNone(get_bot_handler(embedded_bot.name)) def test_outgoing_webhook_interface_type(self) -> None: self.login(self.example_email('hamlet')) bot_info = { 'full_name': 'Outgoing Webhook test bot', 'short_name': 'outgoingservicebot', 'bot_type': UserProfile.OUTGOING_WEBHOOK_BOT, 'payload_url': ujson.dumps('http://127.0.0.1:5002'), 'interface_type': -1, } result = self.client_post("/json/bots", bot_info) self.assert_json_error(result, 'Invalid interface type') bot_info['interface_type'] = Service.GENERIC result = self.client_post("/json/bots", bot_info) self.assert_json_success(result) def test_create_embedded_bot_with_disabled_embedded_bots(self, **extras: Any) -> None: with self.settings(EMBEDDED_BOTS_ENABLED=False): self.create_test_bot(short_name='embeddedservicebot', user_profile=self.example_user("hamlet"), bot_type=UserProfile.EMBEDDED_BOT, service_name='followup', config_data=ujson.dumps({'key': 'value'}), assert_json_error_msg='Embedded bots are not enabled.', **extras) def test_create_embedded_bot(self, **extras: Any) -> None: bot_config_info = {'key': 'value'} self.create_test_bot(short_name='embeddedservicebot', user_profile=self.example_user("hamlet"), bot_type=UserProfile.EMBEDDED_BOT, service_name='followup', config_data=ujson.dumps(bot_config_info), **extras) bot_email = "embeddedservicebot-bot@zulip.testserver" bot_realm = get_realm('zulip') bot = get_user(bot_email, bot_realm) services = get_bot_services(bot.id) service = services[0] bot_config = get_bot_config(bot) self.assertEqual(bot_config, bot_config_info) self.assertEqual(len(services), 1) self.assertEqual(service.name, "followup") self.assertEqual(service.user_profile, bot) def test_create_embedded_bot_with_incorrect_service_name(self, **extras: Any) -> None: self.create_test_bot(short_name='embeddedservicebot', user_profile=self.example_user("hamlet"), bot_type=UserProfile.EMBEDDED_BOT, service_name='not_existing_service', assert_json_error_msg='Invalid embedded bot name.', **extras) def test_create_embedded_bot_with_invalid_config_value(self, **extras: Any) -> None: self.create_test_bot(short_name='embeddedservicebot', user_profile=self.example_user("hamlet"), service_name='followup', config_data=ujson.dumps({'invalid': ['config', 'value']}), assert_json_error_msg='config_data contains a value that is not a string', **extras) # Test to create embedded bot with an incorrect config value incorrect_bot_config_info = {'key': 'incorrect key'} bot_info = { 'full_name': 'Embedded test bot', 'short_name': 'embeddedservicebot3', 'bot_type': UserProfile.EMBEDDED_BOT, 'service_name': 'giphy', 'config_data': ujson.dumps(incorrect_bot_config_info) } bot_info.update(extras) with patch('zulip_bots.bots.giphy.giphy.GiphyHandler.validate_config', side_effect=ConfigValidationError): result = self.client_post("/json/bots", bot_info) self.assert_json_error(result, 'Invalid configuration data!') def test_is_cross_realm_bot_email(self) -> None: self.assertTrue(is_cross_realm_bot_email("notification-bot@zulip.com")) self.assertTrue(is_cross_realm_bot_email("notification-BOT@zulip.com")) self.assertFalse(is_cross_realm_bot_email("random-bot@zulip.com")) with self.settings(CROSS_REALM_BOT_EMAILS={"random-bot@zulip.com"}): self.assertTrue(is_cross_realm_bot_email("random-bot@zulip.com")) self.assertFalse(is_cross_realm_bot_email("notification-bot@zulip.com"))
[ "str", "int", "Any", "MagicMock", "Any", "Any", "Any", "Any", "Any" ]
[ 968, 1124, 1322, 52298, 53787, 56348, 56944, 57901, 58374 ]
[ 971, 1127, 1325, 52307, 53790, 56351, 56947, 57904, 58377 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_bugdown.py
# -*- coding: utf-8 -*- from django.conf import settings from django.test import TestCase, override_settings from zerver.lib import bugdown from zerver.lib.actions import ( do_set_user_display_setting, do_remove_realm_emoji, do_set_alert_words, get_realm, ) from zerver.lib.alert_words import alert_words_in_realm from zerver.lib.camo import get_camo_url from zerver.lib.create_user import create_user from zerver.lib.emoji import get_emoji_url from zerver.lib.exceptions import BugdownRenderingException from zerver.lib.mention import possible_mentions, possible_user_group_mentions from zerver.lib.message import render_markdown from zerver.lib.request import ( JsonableError, ) from zerver.lib.user_groups import create_user_group from zerver.lib.test_classes import ( ZulipTestCase, ) from zerver.lib.test_runner import slow from zerver.lib import mdiff from zerver.lib.tex import render_tex from zerver.models import ( realm_in_local_realm_filters_cache, flush_per_request_caches, flush_realm_filter, get_client, get_realm, get_stream, realm_filters_for_realm, MAX_MESSAGE_LENGTH, Message, Stream, Realm, RealmEmoji, RealmFilter, Recipient, UserProfile, UserGroup, ) import copy import mock import os import ujson import urllib from zerver.lib.str_utils import NonBinaryStr from typing import Any, AnyStr, Dict, List, Optional, Set, Tuple class FencedBlockPreprocessorTest(TestCase): def test_simple_quoting(self) -> None: processor = bugdown.fenced_code.FencedBlockPreprocessor(None) markdown = [ '~~~ quote', 'hi', 'bye', '', '' ] expected = [ '', '> hi', '> bye', '', '', '' ] lines = processor.run(markdown) self.assertEqual(lines, expected) def test_serial_quoting(self) -> None: processor = bugdown.fenced_code.FencedBlockPreprocessor(None) markdown = [ '~~~ quote', 'hi', '~~~', '', '~~~ quote', 'bye', '', '' ] expected = [ '', '> hi', '', '', '', '> bye', '', '', '' ] lines = processor.run(markdown) self.assertEqual(lines, expected) def test_serial_code(self) -> None: processor = bugdown.fenced_code.FencedBlockPreprocessor(None) # Simulate code formatting. processor.format_code = lambda lang, code: lang + ':' + code # type: ignore # mypy doesn't allow monkey-patching functions processor.placeholder = lambda s: '**' + s.strip('\n') + '**' # type: ignore # https://github.com/python/mypy/issues/708 markdown = [ '``` .py', 'hello()', '```', '', '```vb.net', 'goodbye()', '```', '', '```c#', 'weirdchar()', '```', '' ] expected = [ '', '**py:hello()**', '', '', '', '**vb.net:goodbye()**', '', '', '', '**c#:weirdchar()**', '', '' ] lines = processor.run(markdown) self.assertEqual(lines, expected) def test_nested_code(self) -> None: processor = bugdown.fenced_code.FencedBlockPreprocessor(None) # Simulate code formatting. processor.format_code = lambda lang, code: lang + ':' + code # type: ignore # mypy doesn't allow monkey-patching functions processor.placeholder = lambda s: '**' + s.strip('\n') + '**' # type: ignore # https://github.com/python/mypy/issues/708 markdown = [ '~~~ quote', 'hi', '``` .py', 'hello()', '```', '', '' ] expected = [ '', '> hi', '', '> **py:hello()**', '', '', '' ] lines = processor.run(markdown) self.assertEqual(lines, expected) def bugdown_convert(text: str) -> str: return bugdown.convert(text, message_realm=get_realm('zulip')) class BugdownMiscTest(ZulipTestCase): def test_diffs_work_as_expected(self) -> None: str1 = "<p>The quick brown fox jumps over the lazy dog. Animal stories are fun, yeah</p>" str2 = "<p>The fast fox jumps over the lazy dogs and cats. Animal stories are fun</p>" expected_diff = "\u001b[34m-\u001b[0m <p>The \u001b[33mquick brown\u001b[0m fox jumps over the lazy dog. Animal stories are fun\u001b[31m, yeah\u001b[0m</p>\n\u001b[34m+\u001b[0m <p>The \u001b[33mfast\u001b[0m fox jumps over the lazy dog\u001b[32ms and cats\u001b[0m. Animal stories are fun</p>\n" self.assertEqual(mdiff.diff_strings(str1, str2), expected_diff) def test_get_full_name_info(self) -> None: realm = get_realm('zulip') def make_user(email: str, full_name: str) -> UserProfile: return create_user( email=email, password='whatever', realm=realm, full_name=full_name, short_name='whatever', ) fred1 = make_user('fred1@example.com', 'Fred Flintstone') fred1.is_active = False fred1.save() fred2 = make_user('fred2@example.com', 'Fred Flintstone') fred3 = make_user('fred3@example.com', 'Fred Flintstone') fred3.is_active = False fred3.save() fred4 = make_user('fred4@example.com', 'Fred Flintstone') fred4_key = 'fred flintstone|{}'.format(fred4.id) dct = bugdown.get_full_name_info(realm.id, {'Fred Flintstone', 'cordelia LEAR', 'Not A User'}) self.assertEqual(set(dct.keys()), {'fred flintstone', fred4_key, 'cordelia lear'}) self.assertEqual(dct['fred flintstone'], dict( email='fred2@example.com', full_name='Fred Flintstone', id=fred2.id )) self.assertEqual(dct[fred4_key], dict( email='fred4@example.com', full_name='Fred Flintstone', id=fred4.id )) def test_mention_data(self) -> None: realm = get_realm('zulip') hamlet = self.example_user('hamlet') cordelia = self.example_user('cordelia') content = '@**King Hamlet** @**Cordelia lear**' mention_data = bugdown.MentionData(realm.id, content) self.assertEqual(mention_data.get_user_ids(), {hamlet.id, cordelia.id}) self.assertEqual(mention_data.get_user_by_id(hamlet.id), dict( email=hamlet.email, full_name=hamlet.full_name, id=hamlet.id )) user = mention_data.get_user('king hamLET') assert(user is not None) self.assertEqual(user['email'], hamlet.email) def test_invalid_katex_path(self) -> None: with self.settings(STATIC_ROOT="/invalid/path"): with mock.patch('logging.error') as mock_logger: render_tex("random text") mock_logger.assert_called_with("Cannot find KaTeX for latex rendering!") class BugdownTest(ZulipTestCase): def setUp(self) -> None: bugdown.clear_state_for_testing() def assertEqual(self, first: Any, second: Any, msg: str = "") -> None: if isinstance(first, str) and isinstance(second, str): if first != second: raise AssertionError("Actual and expected outputs do not match; showing diff.\n" + mdiff.diff_strings(first, second) + msg) else: super().assertEqual(first, second) def load_bugdown_tests(self) -> Tuple[Dict[str, Any], List[List[str]]]: test_fixtures = {} data_file = open(os.path.join(os.path.dirname(__file__), 'fixtures/markdown_test_cases.json'), 'r') data = ujson.loads('\n'.join(data_file.readlines())) for test in data['regular_tests']: test_fixtures[test['name']] = test return test_fixtures, data['linkify_tests'] def test_bugdown_no_ignores(self) -> None: # We do not want any ignored tests to be committed and merged. format_tests, linkify_tests = self.load_bugdown_tests() for name, test in format_tests.items(): message = 'Test "%s" shouldn\'t be ignored.' % (name,) is_ignored = test.get('ignore', False) self.assertFalse(is_ignored, message) @slow("Aggregate of runs dozens of individual markdown tests") def test_bugdown_fixtures(self) -> None: format_tests, linkify_tests = self.load_bugdown_tests() valid_keys = set(["name", "input", "expected_output", "backend_only_rendering", "marked_expected_output", "text_content", "translate_emoticons", "ignore"]) for name, test in format_tests.items(): # Check that there aren't any unexpected keys as those are often typos self.assertEqual(len(set(test.keys()) - valid_keys), 0) # Ignore tests if specified if test.get('ignore', False): continue # nocoverage if test.get('translate_emoticons', False): # Create a userprofile and send message with it. user_profile = self.example_user('othello') do_set_user_display_setting(user_profile, 'translate_emoticons', True) msg = Message(sender=user_profile, sending_client=get_client("test")) converted = render_markdown(msg, test['input']) else: converted = bugdown_convert(test['input']) print("Running Bugdown test %s" % (name,)) self.assertEqual(converted, test['expected_output']) def replaced(payload: str, url: str, phrase: str='') -> str: target = " target=\"_blank\"" if url[:4] == 'http': href = url elif '@' in url: href = 'mailto:' + url target = "" else: href = 'http://' + url return payload % ("<a href=\"%s\"%s title=\"%s\">%s</a>" % (href, target, href, url),) print("Running Bugdown Linkify tests") with mock.patch('zerver.lib.url_preview.preview.link_embed_data_from_cache', return_value=None): for inline_url, reference, url in linkify_tests: try: match = replaced(reference, url, phrase=inline_url) except TypeError: match = reference converted = bugdown_convert(inline_url) self.assertEqual(match, converted) def test_inline_file(self) -> None: msg = 'Check out this file file:///Volumes/myserver/Users/Shared/pi.py' converted = bugdown_convert(msg) self.assertEqual(converted, '<p>Check out this file <a href="file:///Volumes/myserver/Users/Shared/pi.py" target="_blank" title="file:///Volumes/myserver/Users/Shared/pi.py">file:///Volumes/myserver/Users/Shared/pi.py</a></p>') bugdown.clear_state_for_testing() with self.settings(ENABLE_FILE_LINKS=False): realm = Realm.objects.create(string_id='file_links_test') bugdown.maybe_update_markdown_engines(realm.id, False) converted = bugdown.convert(msg, message_realm=realm) self.assertEqual(converted, '<p>Check out this file file:///Volumes/myserver/Users/Shared/pi.py</p>') def test_inline_bitcoin(self) -> None: msg = 'To bitcoin:1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa or not to bitcoin' converted = bugdown_convert(msg) self.assertEqual(converted, '<p>To <a href="bitcoin:1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa" target="_blank" title="bitcoin:1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa">bitcoin:1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa</a> or not to bitcoin</p>') def test_inline_youtube(self) -> None: msg = 'Check out the debate: http://www.youtube.com/watch?v=hx1mjT73xYE' converted = bugdown_convert(msg) self.assertEqual(converted, '<p>Check out the debate: <a href="http://www.youtube.com/watch?v=hx1mjT73xYE" target="_blank" title="http://www.youtube.com/watch?v=hx1mjT73xYE">http://www.youtube.com/watch?v=hx1mjT73xYE</a></p>\n<div class="youtube-video message_inline_image"><a data-id="hx1mjT73xYE" href="http://www.youtube.com/watch?v=hx1mjT73xYE" target="_blank" title="http://www.youtube.com/watch?v=hx1mjT73xYE"><img src="https://i.ytimg.com/vi/hx1mjT73xYE/default.jpg"></a></div>') msg = 'http://www.youtube.com/watch?v=hx1mjT73xYE' converted = bugdown_convert(msg) self.assertEqual(converted, '<p><a href="http://www.youtube.com/watch?v=hx1mjT73xYE" target="_blank" title="http://www.youtube.com/watch?v=hx1mjT73xYE">http://www.youtube.com/watch?v=hx1mjT73xYE</a></p>\n<div class="youtube-video message_inline_image"><a data-id="hx1mjT73xYE" href="http://www.youtube.com/watch?v=hx1mjT73xYE" target="_blank" title="http://www.youtube.com/watch?v=hx1mjT73xYE"><img src="https://i.ytimg.com/vi/hx1mjT73xYE/default.jpg"></a></div>') def test_inline_vimeo(self) -> None: msg = 'Check out the debate: https://vimeo.com/246979354' converted = bugdown_convert(msg) self.assertEqual(converted, '<p>Check out the debate: <a href="https://vimeo.com/246979354" target="_blank" title="https://vimeo.com/246979354">https://vimeo.com/246979354</a></p>') msg = 'https://vimeo.com/246979354' converted = bugdown_convert(msg) self.assertEqual(converted, '<p><a href="https://vimeo.com/246979354" target="_blank" title="https://vimeo.com/246979354">https://vimeo.com/246979354</a></p>') @override_settings(INLINE_IMAGE_PREVIEW=True) def test_inline_image_thumbnail_url(self): # type: () -> None msg = '[foobar](/user_uploads/2/50/w2G6ok9kr8AMCQCTNAUOFMln/IMG_0677.JPG)' thumbnail_img = '<img data-src-fullsize="/thumbnail?url=user_uploads%2F2%2F50%2Fw2G6ok9kr8AMCQCTNAUOFMln%2FIMG_0677.JPG&amp;size=full" src="/thumbnail?url=user_uploads%2F2%2F50%2Fw2G6ok9kr8AMCQCTNAUOFMln%2FIMG_0677.JPG&amp;size=thumbnail"><' converted = bugdown_convert(msg) self.assertIn(thumbnail_img, converted) msg = 'https://www.google.com/images/srpr/logo4w.png' thumbnail_img = '<img data-src-fullsize="/thumbnail?url=https%3A%2F%2Fwww.google.com%2Fimages%2Fsrpr%2Flogo4w.png&amp;size=full" src="/thumbnail?url=https%3A%2F%2Fwww.google.com%2Fimages%2Fsrpr%2Flogo4w.png&amp;size=thumbnail">' converted = bugdown_convert(msg) self.assertIn(thumbnail_img, converted) msg = 'www.google.com/images/srpr/logo4w.png' thumbnail_img = '<img data-src-fullsize="/thumbnail?url=http%3A%2F%2Fwww.google.com%2Fimages%2Fsrpr%2Flogo4w.png&amp;size=full" src="/thumbnail?url=http%3A%2F%2Fwww.google.com%2Fimages%2Fsrpr%2Flogo4w.png&amp;size=thumbnail">' converted = bugdown_convert(msg) self.assertIn(thumbnail_img, converted) msg = 'https://www.google.com/images/srpr/logo4w.png' thumbnail_img = '<div class="message_inline_image"><a href="https://www.google.com/images/srpr/logo4w.png" target="_blank" title="https://www.google.com/images/srpr/logo4w.png"><img src="https://www.google.com/images/srpr/logo4w.png"></a></div>' with self.settings(THUMBOR_URL=''): converted = bugdown_convert(msg) self.assertIn(thumbnail_img, converted) # Any url which is not an external link and doesn't start with # /user_uploads/ is not thumbnailed msg = '[foobar](/static/images/cute/turtle.png)' thumbnail_img = '<div class="message_inline_image"><a href="/static/images/cute/turtle.png" target="_blank" title="foobar"><img src="/static/images/cute/turtle.png"></a></div>' converted = bugdown_convert(msg) self.assertIn(thumbnail_img, converted) msg = '[foobar](/user_avatars/2/emoji/images/50.png)' thumbnail_img = '<div class="message_inline_image"><a href="/user_avatars/2/emoji/images/50.png" target="_blank" title="foobar"><img src="/user_avatars/2/emoji/images/50.png"></a></div>' converted = bugdown_convert(msg) self.assertIn(thumbnail_img, converted) @override_settings(INLINE_IMAGE_PREVIEW=True) def test_inline_image_preview(self): # type: () -> None with_preview = '<div class="message_inline_image"><a href="http://cdn.wallpapersafari.com/13/6/16eVjx.jpeg" target="_blank" title="http://cdn.wallpapersafari.com/13/6/16eVjx.jpeg"><img data-src-fullsize="/thumbnail?url=http%3A%2F%2Fcdn.wallpapersafari.com%2F13%2F6%2F16eVjx.jpeg&amp;size=full" src="/thumbnail?url=http%3A%2F%2Fcdn.wallpapersafari.com%2F13%2F6%2F16eVjx.jpeg&amp;size=thumbnail"></a></div>' without_preview = '<p><a href="http://cdn.wallpapersafari.com/13/6/16eVjx.jpeg" target="_blank" title="http://cdn.wallpapersafari.com/13/6/16eVjx.jpeg">http://cdn.wallpapersafari.com/13/6/16eVjx.jpeg</a></p>' content = 'http://cdn.wallpapersafari.com/13/6/16eVjx.jpeg' sender_user_profile = self.example_user('othello') msg = Message(sender=sender_user_profile, sending_client=get_client("test")) converted = render_markdown(msg, content) self.assertEqual(converted, with_preview) realm = msg.get_realm() setattr(realm, 'inline_image_preview', False) realm.save() sender_user_profile = self.example_user('othello') msg = Message(sender=sender_user_profile, sending_client=get_client("test")) converted = render_markdown(msg, content) self.assertEqual(converted, without_preview) @override_settings(INLINE_IMAGE_PREVIEW=True) def test_inline_image_preview_order(self) -> None: content = 'http://imaging.nikon.com/lineup/dslr/df/img/sample/img_01.jpg\nhttp://imaging.nikon.com/lineup/dslr/df/img/sample/img_02.jpg\nhttp://imaging.nikon.com/lineup/dslr/df/img/sample/img_03.jpg' expected = '<p><a href="http://imaging.nikon.com/lineup/dslr/df/img/sample/img_01.jpg" target="_blank" title="http://imaging.nikon.com/lineup/dslr/df/img/sample/img_01.jpg">http://imaging.nikon.com/lineup/dslr/df/img/sample/img_01.jpg</a><br>\n<a href="http://imaging.nikon.com/lineup/dslr/df/img/sample/img_02.jpg" target="_blank" title="http://imaging.nikon.com/lineup/dslr/df/img/sample/img_02.jpg">http://imaging.nikon.com/lineup/dslr/df/img/sample/img_02.jpg</a><br>\n<a href="http://imaging.nikon.com/lineup/dslr/df/img/sample/img_03.jpg" target="_blank" title="http://imaging.nikon.com/lineup/dslr/df/img/sample/img_03.jpg">http://imaging.nikon.com/lineup/dslr/df/img/sample/img_03.jpg</a></p>\n<div class="message_inline_image"><a href="http://imaging.nikon.com/lineup/dslr/df/img/sample/img_01.jpg" target="_blank" title="http://imaging.nikon.com/lineup/dslr/df/img/sample/img_01.jpg"><img data-src-fullsize="/thumbnail?url=http%3A%2F%2Fimaging.nikon.com%2Flineup%2Fdslr%2Fdf%2Fimg%2Fsample%2Fimg_01.jpg&amp;size=full" src="/thumbnail?url=http%3A%2F%2Fimaging.nikon.com%2Flineup%2Fdslr%2Fdf%2Fimg%2Fsample%2Fimg_01.jpg&amp;size=thumbnail"></a></div><div class="message_inline_image"><a href="http://imaging.nikon.com/lineup/dslr/df/img/sample/img_02.jpg" target="_blank" title="http://imaging.nikon.com/lineup/dslr/df/img/sample/img_02.jpg"><img data-src-fullsize="/thumbnail?url=http%3A%2F%2Fimaging.nikon.com%2Flineup%2Fdslr%2Fdf%2Fimg%2Fsample%2Fimg_02.jpg&amp;size=full" src="/thumbnail?url=http%3A%2F%2Fimaging.nikon.com%2Flineup%2Fdslr%2Fdf%2Fimg%2Fsample%2Fimg_02.jpg&amp;size=thumbnail"></a></div><div class="message_inline_image"><a href="http://imaging.nikon.com/lineup/dslr/df/img/sample/img_03.jpg" target="_blank" title="http://imaging.nikon.com/lineup/dslr/df/img/sample/img_03.jpg"><img data-src-fullsize="/thumbnail?url=http%3A%2F%2Fimaging.nikon.com%2Flineup%2Fdslr%2Fdf%2Fimg%2Fsample%2Fimg_03.jpg&amp;size=full" src="/thumbnail?url=http%3A%2F%2Fimaging.nikon.com%2Flineup%2Fdslr%2Fdf%2Fimg%2Fsample%2Fimg_03.jpg&amp;size=thumbnail"></a></div>' sender_user_profile = self.example_user('othello') msg = Message(sender=sender_user_profile, sending_client=get_client("test")) converted = render_markdown(msg, content) self.assertEqual(converted, expected) content = 'http://imaging.nikon.com/lineup/dslr/df/img/sample/img_01.jpg\n\n>http://imaging.nikon.com/lineup/dslr/df/img/sample/img_02.jpg\n\n* http://imaging.nikon.com/lineup/dslr/df/img/sample/img_03.jpg\n* https://www.google.com/images/srpr/logo4w.png' expected = '<div class="message_inline_image"><a href="http://imaging.nikon.com/lineup/dslr/df/img/sample/img_01.jpg" target="_blank" title="http://imaging.nikon.com/lineup/dslr/df/img/sample/img_01.jpg"><img data-src-fullsize="/thumbnail?url=http%3A%2F%2Fimaging.nikon.com%2Flineup%2Fdslr%2Fdf%2Fimg%2Fsample%2Fimg_01.jpg&amp;size=full" src="/thumbnail?url=http%3A%2F%2Fimaging.nikon.com%2Flineup%2Fdslr%2Fdf%2Fimg%2Fsample%2Fimg_01.jpg&amp;size=thumbnail"></a></div><blockquote>\n<div class="message_inline_image"><a href="http://imaging.nikon.com/lineup/dslr/df/img/sample/img_02.jpg" target="_blank" title="http://imaging.nikon.com/lineup/dslr/df/img/sample/img_02.jpg"><img data-src-fullsize="/thumbnail?url=http%3A%2F%2Fimaging.nikon.com%2Flineup%2Fdslr%2Fdf%2Fimg%2Fsample%2Fimg_02.jpg&amp;size=full" src="/thumbnail?url=http%3A%2F%2Fimaging.nikon.com%2Flineup%2Fdslr%2Fdf%2Fimg%2Fsample%2Fimg_02.jpg&amp;size=thumbnail"></a></div></blockquote>\n<ul>\n<li><div class="message_inline_image"><a href="http://imaging.nikon.com/lineup/dslr/df/img/sample/img_03.jpg" target="_blank" title="http://imaging.nikon.com/lineup/dslr/df/img/sample/img_03.jpg"><img data-src-fullsize="/thumbnail?url=http%3A%2F%2Fimaging.nikon.com%2Flineup%2Fdslr%2Fdf%2Fimg%2Fsample%2Fimg_03.jpg&amp;size=full" src="/thumbnail?url=http%3A%2F%2Fimaging.nikon.com%2Flineup%2Fdslr%2Fdf%2Fimg%2Fsample%2Fimg_03.jpg&amp;size=thumbnail"></a></div></li>\n<li><div class="message_inline_image"><a href="https://www.google.com/images/srpr/logo4w.png" target="_blank" title="https://www.google.com/images/srpr/logo4w.png"><img data-src-fullsize="/thumbnail?url=https%3A%2F%2Fwww.google.com%2Fimages%2Fsrpr%2Flogo4w.png&amp;size=full" src="/thumbnail?url=https%3A%2F%2Fwww.google.com%2Fimages%2Fsrpr%2Flogo4w.png&amp;size=thumbnail"></a></div></li>\n</ul>' sender_user_profile = self.example_user('othello') msg = Message(sender=sender_user_profile, sending_client=get_client("test")) converted = render_markdown(msg, content) self.assertEqual(converted, expected) content = 'Test 1\n[21136101110_1dde1c1a7e_o.jpg](/user_uploads/1/6d/F1PX6u16JA2P-nK45PyxHIYZ/21136101110_1dde1c1a7e_o.jpg) \n\nNext Image\n[IMG_20161116_023910.jpg](/user_uploads/1/69/sh7L06e7uH7NaX6d5WFfVYQp/IMG_20161116_023910.jpg) \n\nAnother Screenshot\n[Screenshot-from-2016-06-01-16-22-42.png](/user_uploads/1/70/_aZmIEWaN1iUaxwkDjkO7bpj/Screenshot-from-2016-06-01-16-22-42.png)' expected = '<p>Test 1<br>\n<a href="/user_uploads/1/6d/F1PX6u16JA2P-nK45PyxHIYZ/21136101110_1dde1c1a7e_o.jpg" target="_blank" title="21136101110_1dde1c1a7e_o.jpg">21136101110_1dde1c1a7e_o.jpg</a> </p>\n<div class="message_inline_image"><a href="/user_uploads/1/6d/F1PX6u16JA2P-nK45PyxHIYZ/21136101110_1dde1c1a7e_o.jpg" target="_blank" title="21136101110_1dde1c1a7e_o.jpg"><img data-src-fullsize="/thumbnail?url=user_uploads%2F1%2F6d%2FF1PX6u16JA2P-nK45PyxHIYZ%2F21136101110_1dde1c1a7e_o.jpg&amp;size=full" src="/thumbnail?url=user_uploads%2F1%2F6d%2FF1PX6u16JA2P-nK45PyxHIYZ%2F21136101110_1dde1c1a7e_o.jpg&amp;size=thumbnail"></a></div><p>Next Image<br>\n<a href="/user_uploads/1/69/sh7L06e7uH7NaX6d5WFfVYQp/IMG_20161116_023910.jpg" target="_blank" title="IMG_20161116_023910.jpg">IMG_20161116_023910.jpg</a> </p>\n<div class="message_inline_image"><a href="/user_uploads/1/69/sh7L06e7uH7NaX6d5WFfVYQp/IMG_20161116_023910.jpg" target="_blank" title="IMG_20161116_023910.jpg"><img data-src-fullsize="/thumbnail?url=user_uploads%2F1%2F69%2Fsh7L06e7uH7NaX6d5WFfVYQp%2FIMG_20161116_023910.jpg&amp;size=full" src="/thumbnail?url=user_uploads%2F1%2F69%2Fsh7L06e7uH7NaX6d5WFfVYQp%2FIMG_20161116_023910.jpg&amp;size=thumbnail"></a></div><p>Another Screenshot<br>\n<a href="/user_uploads/1/70/_aZmIEWaN1iUaxwkDjkO7bpj/Screenshot-from-2016-06-01-16-22-42.png" target="_blank" title="Screenshot-from-2016-06-01-16-22-42.png">Screenshot-from-2016-06-01-16-22-42.png</a></p>\n<div class="message_inline_image"><a href="/user_uploads/1/70/_aZmIEWaN1iUaxwkDjkO7bpj/Screenshot-from-2016-06-01-16-22-42.png" target="_blank" title="Screenshot-from-2016-06-01-16-22-42.png"><img data-src-fullsize="/thumbnail?url=user_uploads%2F1%2F70%2F_aZmIEWaN1iUaxwkDjkO7bpj%2FScreenshot-from-2016-06-01-16-22-42.png&amp;size=full" src="/thumbnail?url=user_uploads%2F1%2F70%2F_aZmIEWaN1iUaxwkDjkO7bpj%2FScreenshot-from-2016-06-01-16-22-42.png&amp;size=thumbnail"></a></div>' msg = Message(sender=sender_user_profile, sending_client=get_client("test")) converted = render_markdown(msg, content) self.assertEqual(converted, expected) @override_settings(INLINE_IMAGE_PREVIEW=False) def test_image_preview_enabled_for_realm(self) -> None: ret = bugdown.image_preview_enabled_for_realm() self.assertEqual(ret, False) settings.INLINE_IMAGE_PREVIEW = True sender_user_profile = self.example_user('othello') message = Message(sender=sender_user_profile, sending_client=get_client("test")) realm = message.get_realm() ret = bugdown.image_preview_enabled_for_realm() self.assertEqual(ret, realm.inline_image_preview) ret = bugdown.image_preview_enabled_for_realm() self.assertEqual(ret, True) @override_settings(INLINE_URL_EMBED_PREVIEW=False) def test_url_embed_preview_enabled_for_realm(self) -> None: sender_user_profile = self.example_user('othello') message = copy.deepcopy(Message(sender=sender_user_profile, sending_client=get_client("test"))) realm = message.get_realm() ret = bugdown.url_embed_preview_enabled_for_realm() self.assertEqual(ret, False) settings.INLINE_URL_EMBED_PREVIEW = True ret = bugdown.url_embed_preview_enabled_for_realm() self.assertEqual(ret, realm.inline_image_preview) def test_inline_dropbox(self) -> None: msg = 'Look at how hilarious our old office was: https://www.dropbox.com/s/ymdijjcg67hv2ta/IMG_0923.JPG' image_info = {'image': 'https://photos-4.dropbox.com/t/2/AABIre1oReJgPYuc_53iv0IHq1vUzRaDg2rrCfTpiWMccQ/12/129/jpeg/1024x1024/2/_/0/4/IMG_0923.JPG/CIEBIAEgAiAHKAIoBw/ymdijjcg67hv2ta/AABz2uuED1ox3vpWWvMpBxu6a/IMG_0923.JPG', 'desc': 'Shared with Dropbox', 'title': 'IMG_0923.JPG'} with mock.patch('zerver.lib.bugdown.fetch_open_graph_image', return_value=image_info): converted = bugdown_convert(msg) self.assertEqual(converted, '<p>Look at how hilarious our old office was: <a href="https://www.dropbox.com/s/ymdijjcg67hv2ta/IMG_0923.JPG" target="_blank" title="https://www.dropbox.com/s/ymdijjcg67hv2ta/IMG_0923.JPG">https://www.dropbox.com/s/ymdijjcg67hv2ta/IMG_0923.JPG</a></p>\n<div class="message_inline_image"><a href="https://www.dropbox.com/s/ymdijjcg67hv2ta/IMG_0923.JPG" target="_blank" title="IMG_0923.JPG"><img src="https://www.dropbox.com/s/ymdijjcg67hv2ta/IMG_0923.JPG?dl=1"></a></div>') msg = 'Look at my hilarious drawing folder: https://www.dropbox.com/sh/cm39k9e04z7fhim/AAAII5NK-9daee3FcF41anEua?dl=' image_info = {'image': 'https://cf.dropboxstatic.com/static/images/icons128/folder_dropbox.png', 'desc': 'Shared with Dropbox', 'title': 'Saves'} with mock.patch('zerver.lib.bugdown.fetch_open_graph_image', return_value=image_info): converted = bugdown_convert(msg) self.assertEqual(converted, '<p>Look at my hilarious drawing folder: <a href="https://www.dropbox.com/sh/cm39k9e04z7fhim/AAAII5NK-9daee3FcF41anEua?dl=" target="_blank" title="https://www.dropbox.com/sh/cm39k9e04z7fhim/AAAII5NK-9daee3FcF41anEua?dl=">https://www.dropbox.com/sh/cm39k9e04z7fhim/AAAII5NK-9daee3FcF41anEua?dl=</a></p>\n<div class="message_inline_ref"><a href="https://www.dropbox.com/sh/cm39k9e04z7fhim/AAAII5NK-9daee3FcF41anEua?dl=" target="_blank" title="Saves"><img src="https://cf.dropboxstatic.com/static/images/icons128/folder_dropbox.png"></a><div><div class="message_inline_image_title">Saves</div><desc class="message_inline_image_desc"></desc></div></div>') def test_inline_dropbox_preview(self) -> None: # Test photo album previews msg = 'https://www.dropbox.com/sc/tditp9nitko60n5/03rEiZldy5' image_info = {'image': 'https://photos-6.dropbox.com/t/2/AAAlawaeD61TyNewO5vVi-DGf2ZeuayfyHFdNTNzpGq-QA/12/271544745/jpeg/1024x1024/2/_/0/5/baby-piglet.jpg/CKnjvYEBIAIgBygCKAc/tditp9nitko60n5/AADX03VAIrQlTl28CtujDcMla/0', 'desc': 'Shared with Dropbox', 'title': '1 photo'} with mock.patch('zerver.lib.bugdown.fetch_open_graph_image', return_value=image_info): converted = bugdown_convert(msg) self.assertEqual(converted, '<p><a href="https://www.dropbox.com/sc/tditp9nitko60n5/03rEiZldy5" target="_blank" title="https://www.dropbox.com/sc/tditp9nitko60n5/03rEiZldy5">https://www.dropbox.com/sc/tditp9nitko60n5/03rEiZldy5</a></p>\n<div class="message_inline_image"><a href="https://www.dropbox.com/sc/tditp9nitko60n5/03rEiZldy5" target="_blank" title="1 photo"><img src="https://photos-6.dropbox.com/t/2/AAAlawaeD61TyNewO5vVi-DGf2ZeuayfyHFdNTNzpGq-QA/12/271544745/jpeg/1024x1024/2/_/0/5/baby-piglet.jpg/CKnjvYEBIAIgBygCKAc/tditp9nitko60n5/AADX03VAIrQlTl28CtujDcMla/0"></a></div>') def test_inline_dropbox_negative(self) -> None: # Make sure we're not overzealous in our conversion: msg = 'Look at the new dropbox logo: https://www.dropbox.com/static/images/home_logo.png' with mock.patch('zerver.lib.bugdown.fetch_open_graph_image', return_value=None): converted = bugdown_convert(msg) self.assertEqual(converted, '<p>Look at the new dropbox logo: <a href="https://www.dropbox.com/static/images/home_logo.png" target="_blank" title="https://www.dropbox.com/static/images/home_logo.png">https://www.dropbox.com/static/images/home_logo.png</a></p>\n<div class="message_inline_image"><a href="https://www.dropbox.com/static/images/home_logo.png" target="_blank" title="https://www.dropbox.com/static/images/home_logo.png"><img data-src-fullsize="/thumbnail?url=https%3A%2F%2Fwww.dropbox.com%2Fstatic%2Fimages%2Fhome_logo.png&amp;size=full" src="/thumbnail?url=https%3A%2F%2Fwww.dropbox.com%2Fstatic%2Fimages%2Fhome_logo.png&amp;size=thumbnail"></a></div>') def test_inline_dropbox_bad(self) -> None: # Don't fail on bad dropbox links msg = "https://zulip-test.dropbox.com/photos/cl/ROmr9K1XYtmpneM" with mock.patch('zerver.lib.bugdown.fetch_open_graph_image', return_value=None): converted = bugdown_convert(msg) self.assertEqual(converted, '<p><a href="https://zulip-test.dropbox.com/photos/cl/ROmr9K1XYtmpneM" target="_blank" title="https://zulip-test.dropbox.com/photos/cl/ROmr9K1XYtmpneM">https://zulip-test.dropbox.com/photos/cl/ROmr9K1XYtmpneM</a></p>') def test_inline_github_preview(self) -> None: # Test photo album previews msg = 'Test: https://github.com/zulip/zulip/blob/master/static/images/logo/zulip-icon-128x128.png' converted = bugdown_convert(msg) self.assertEqual(converted, '<p>Test: <a href="https://github.com/zulip/zulip/blob/master/static/images/logo/zulip-icon-128x128.png" target="_blank" title="https://github.com/zulip/zulip/blob/master/static/images/logo/zulip-icon-128x128.png">https://github.com/zulip/zulip/blob/master/static/images/logo/zulip-icon-128x128.png</a></p>\n<div class="message_inline_image"><a href="https://github.com/zulip/zulip/blob/master/static/images/logo/zulip-icon-128x128.png" target="_blank" title="https://github.com/zulip/zulip/blob/master/static/images/logo/zulip-icon-128x128.png"><img data-src-fullsize="/thumbnail?url=https%3A%2F%2Fraw.githubusercontent.com%2Fzulip%2Fzulip%2Fmaster%2Fstatic%2Fimages%2Flogo%2Fzulip-icon-128x128.png&amp;size=full" src="/thumbnail?url=https%3A%2F%2Fraw.githubusercontent.com%2Fzulip%2Fzulip%2Fmaster%2Fstatic%2Fimages%2Flogo%2Fzulip-icon-128x128.png&amp;size=thumbnail"></a></div>') msg = 'Test: https://developer.github.com/assets/images/hero-circuit-bg.png' converted = bugdown_convert(msg) self.assertEqual(converted, '<p>Test: <a href="https://developer.github.com/assets/images/hero-circuit-bg.png" target="_blank" title="https://developer.github.com/assets/images/hero-circuit-bg.png">https://developer.github.com/assets/images/hero-circuit-bg.png</a></p>\n<div class="message_inline_image"><a href="https://developer.github.com/assets/images/hero-circuit-bg.png" target="_blank" title="https://developer.github.com/assets/images/hero-circuit-bg.png"><img data-src-fullsize="/thumbnail?url=https%3A%2F%2Fdeveloper.github.com%2Fassets%2Fimages%2Fhero-circuit-bg.png&amp;size=full" src="/thumbnail?url=https%3A%2F%2Fdeveloper.github.com%2Fassets%2Fimages%2Fhero-circuit-bg.png&amp;size=thumbnail"></a></div>') def test_twitter_id_extraction(self) -> None: self.assertEqual(bugdown.get_tweet_id('http://twitter.com/#!/VizzQuotes/status/409030735191097344'), '409030735191097344') self.assertEqual(bugdown.get_tweet_id('http://twitter.com/VizzQuotes/status/409030735191097344'), '409030735191097344') self.assertEqual(bugdown.get_tweet_id('http://twitter.com/VizzQuotes/statuses/409030735191097344'), '409030735191097344') self.assertEqual(bugdown.get_tweet_id('https://twitter.com/wdaher/status/1017581858'), '1017581858') self.assertEqual(bugdown.get_tweet_id('https://twitter.com/wdaher/status/1017581858/'), '1017581858') self.assertEqual(bugdown.get_tweet_id('https://twitter.com/windyoona/status/410766290349879296/photo/1'), '410766290349879296') self.assertEqual(bugdown.get_tweet_id('https://twitter.com/windyoona/status/410766290349879296/'), '410766290349879296') def test_inline_interesting_links(self) -> None: def make_link(url: str) -> str: return '<a href="%s" target="_blank" title="%s">%s</a>' % (url, url, url) normal_tweet_html = ('<a href="https://twitter.com/Twitter" target="_blank"' ' title="https://twitter.com/Twitter">@Twitter</a> ' 'meets @seepicturely at #tcdisrupt cc.' '<a href="https://twitter.com/boscomonkey" target="_blank"' ' title="https://twitter.com/boscomonkey">@boscomonkey</a> ' '<a href="https://twitter.com/episod" target="_blank"' ' title="https://twitter.com/episod">@episod</a> ' '<a href="http://t.co/6J2EgYM" target="_blank"' ' title="http://t.co/6J2EgYM">http://instagr.am/p/MuW67/</a>') mention_in_link_tweet_html = """<a href="http://t.co/@foo" target="_blank" title="http://t.co/@foo">http://foo.com</a>""" media_tweet_html = ('<a href="http://t.co/xo7pAhK6n3" target="_blank" title="http://t.co/xo7pAhK6n3">' 'http://twitter.com/NEVNBoston/status/421654515616849920/photo/1</a>') emoji_in_tweet_html = """Zulip is <span class="emoji emoji-1f4af" title="100">:100:</span>% open-source!""" def make_inline_twitter_preview(url: str, tweet_html: str, image_html: str='') -> str: ## As of right now, all previews are mocked to be the exact same tweet return ('<div class="inline-preview-twitter">' '<div class="twitter-tweet">' '<a href="%s" target="_blank">' '<img class="twitter-avatar"' ' src="https://external-content.zulipcdn.net/external_content/1f7cd2436976d410eab8189ebceda87ae0b34ead/687474703a2f2f7062732e7477696d672e63' '6f6d2f70726f66696c655f696d616765732f313338303931323137332f53637265656e5f73686f745f323031312d30362d30335f61745f372e33352e33' '365f504d5f6e6f726d616c2e706e67">' '</a>' '<p>%s</p>' '<span>- Eoin McMillan (@imeoin)</span>' '%s' '</div>' '</div>') % (url, tweet_html, image_html) msg = 'http://www.twitter.com' converted = bugdown_convert(msg) self.assertEqual(converted, '<p>%s</p>' % make_link('http://www.twitter.com')) msg = 'http://www.twitter.com/wdaher/' converted = bugdown_convert(msg) self.assertEqual(converted, '<p>%s</p>' % make_link('http://www.twitter.com/wdaher/')) msg = 'http://www.twitter.com/wdaher/status/3' converted = bugdown_convert(msg) self.assertEqual(converted, '<p>%s</p>' % make_link('http://www.twitter.com/wdaher/status/3')) # id too long msg = 'http://www.twitter.com/wdaher/status/2879779692873154569' converted = bugdown_convert(msg) self.assertEqual(converted, '<p>%s</p>' % make_link('http://www.twitter.com/wdaher/status/2879779692873154569')) # id too large (i.e. tweet doesn't exist) msg = 'http://www.twitter.com/wdaher/status/999999999999999999' converted = bugdown_convert(msg) self.assertEqual(converted, '<p>%s</p>' % make_link('http://www.twitter.com/wdaher/status/999999999999999999')) msg = 'http://www.twitter.com/wdaher/status/287977969287315456' converted = bugdown_convert(msg) self.assertEqual(converted, '<p>%s</p>\n%s' % ( make_link('http://www.twitter.com/wdaher/status/287977969287315456'), make_inline_twitter_preview('http://www.twitter.com/wdaher/status/287977969287315456', normal_tweet_html))) msg = 'https://www.twitter.com/wdaher/status/287977969287315456' converted = bugdown_convert(msg) self.assertEqual(converted, '<p>%s</p>\n%s' % ( make_link('https://www.twitter.com/wdaher/status/287977969287315456'), make_inline_twitter_preview('https://www.twitter.com/wdaher/status/287977969287315456', normal_tweet_html))) msg = 'http://twitter.com/wdaher/status/287977969287315456' converted = bugdown_convert(msg) self.assertEqual(converted, '<p>%s</p>\n%s' % ( make_link('http://twitter.com/wdaher/status/287977969287315456'), make_inline_twitter_preview('http://twitter.com/wdaher/status/287977969287315456', normal_tweet_html))) # A max of 3 will be converted msg = ('http://twitter.com/wdaher/status/287977969287315456 ' 'http://twitter.com/wdaher/status/287977969287315457 ' 'http://twitter.com/wdaher/status/287977969287315457 ' 'http://twitter.com/wdaher/status/287977969287315457') converted = bugdown_convert(msg) self.assertEqual(converted, '<p>%s %s %s %s</p>\n%s%s%s' % ( make_link('http://twitter.com/wdaher/status/287977969287315456'), make_link('http://twitter.com/wdaher/status/287977969287315457'), make_link('http://twitter.com/wdaher/status/287977969287315457'), make_link('http://twitter.com/wdaher/status/287977969287315457'), make_inline_twitter_preview('http://twitter.com/wdaher/status/287977969287315456', normal_tweet_html), make_inline_twitter_preview('http://twitter.com/wdaher/status/287977969287315457', normal_tweet_html), make_inline_twitter_preview('http://twitter.com/wdaher/status/287977969287315457', normal_tweet_html))) # Tweet has a mention in a URL, only the URL is linked msg = 'http://twitter.com/wdaher/status/287977969287315458' converted = bugdown_convert(msg) self.assertEqual(converted, '<p>%s</p>\n%s' % ( make_link('http://twitter.com/wdaher/status/287977969287315458'), make_inline_twitter_preview('http://twitter.com/wdaher/status/287977969287315458', mention_in_link_tweet_html))) # Tweet with an image msg = 'http://twitter.com/wdaher/status/287977969287315459' converted = bugdown_convert(msg) self.assertEqual(converted, '<p>%s</p>\n%s' % ( make_link('http://twitter.com/wdaher/status/287977969287315459'), make_inline_twitter_preview('http://twitter.com/wdaher/status/287977969287315459', media_tweet_html, ('<div class="twitter-image">' '<a href="http://t.co/xo7pAhK6n3" target="_blank" title="http://t.co/xo7pAhK6n3">' '<img src="https://pbs.twimg.com/media/BdoEjD4IEAIq86Z.jpg:small">' '</a>' '</div>')))) msg = 'http://twitter.com/wdaher/status/287977969287315460' converted = bugdown_convert(msg) self.assertEqual(converted, '<p>%s</p>\n%s' % ( make_link('http://twitter.com/wdaher/status/287977969287315460'), make_inline_twitter_preview('http://twitter.com/wdaher/status/287977969287315460', emoji_in_tweet_html))) def test_fetch_tweet_data_settings_validation(self) -> None: with self.settings(TEST_SUITE=False, TWITTER_CONSUMER_KEY=None): self.assertIs(None, bugdown.fetch_tweet_data('287977969287315459')) def test_content_has_emoji(self) -> None: self.assertFalse(bugdown.content_has_emoji_syntax('boring')) self.assertFalse(bugdown.content_has_emoji_syntax('hello: world')) self.assertFalse(bugdown.content_has_emoji_syntax(':foobar')) self.assertFalse(bugdown.content_has_emoji_syntax('::: hello :::')) self.assertTrue(bugdown.content_has_emoji_syntax('foo :whatever:')) self.assertTrue(bugdown.content_has_emoji_syntax('\n:whatever:')) self.assertTrue(bugdown.content_has_emoji_syntax(':smile: ::::::')) def test_realm_emoji(self) -> None: def emoji_img(name: str, file_name: str, realm_id: int) -> str: return '<img alt="%s" class="emoji" src="%s" title="%s">' % ( name, get_emoji_url(file_name, realm_id), name[1:-1].replace("_", " ")) realm = get_realm('zulip') # Needs to mock an actual message because that's how bugdown obtains the realm msg = Message(sender=self.example_user('hamlet')) converted = bugdown.convert(":green_tick:", message_realm=realm, message=msg) realm_emoji = RealmEmoji.objects.filter(realm=realm, name='green_tick', deactivated=False).get() self.assertEqual(converted, '<p>%s</p>' % (emoji_img(':green_tick:', realm_emoji.file_name, realm.id))) # Deactivate realm emoji. do_remove_realm_emoji(realm, 'green_tick') converted = bugdown.convert(":green_tick:", message_realm=realm, message=msg) self.assertEqual(converted, '<p>:green_tick:</p>') def test_deactivated_realm_emoji(self) -> None: # Deactivate realm emoji. realm = get_realm('zulip') do_remove_realm_emoji(realm, 'green_tick') msg = Message(sender=self.example_user('hamlet')) converted = bugdown.convert(":green_tick:", message_realm=realm, message=msg) self.assertEqual(converted, '<p>:green_tick:</p>') def test_unicode_emoji(self) -> None: msg = u'\u2615' # ☕ converted = bugdown_convert(msg) self.assertEqual(converted, u'<p><span class="emoji emoji-2615" title="coffee">:coffee:</span></p>') msg = u'\u2615\u2615' # ☕☕ converted = bugdown_convert(msg) self.assertEqual(converted, u'<p><span class="emoji emoji-2615" title="coffee">:coffee:</span><span class="emoji emoji-2615" title="coffee">:coffee:</span></p>') def test_no_translate_emoticons_if_off(self) -> None: user_profile = self.example_user('othello') do_set_user_display_setting(user_profile, 'translate_emoticons', False) msg = Message(sender=user_profile, sending_client=get_client("test")) content = u':)' expected = u'<p>:)</p>' converted = render_markdown(msg, content) self.assertEqual(converted, expected) def test_same_markup(self) -> None: msg = u'\u2615' # ☕ unicode_converted = bugdown_convert(msg) msg = u':coffee:' # ☕☕ converted = bugdown_convert(msg) self.assertEqual(converted, unicode_converted) def test_realm_patterns(self) -> None: realm = get_realm('zulip') url_format_string = r"https://trac.zulip.net/ticket/%(id)s" realm_filter = RealmFilter(realm=realm, pattern=r"#(?P<id>[0-9]{2,8})", url_format_string=url_format_string) realm_filter.save() self.assertEqual( realm_filter.__str__(), '<RealmFilter(zulip): #(?P<id>[0-9]{2,8})' ' https://trac.zulip.net/ticket/%(id)s>') msg = Message(sender=self.example_user('othello')) msg.set_topic_name("#444") flush_per_request_caches() content = "We should fix #224 and #115, but not issue#124 or #1124z or [trac #15](https://trac.zulip.net/ticket/16) today." converted = bugdown.convert(content, message_realm=realm, message=msg) converted_topic = bugdown.topic_links(realm.id, msg.topic_name()) self.assertEqual(converted, '<p>We should fix <a href="https://trac.zulip.net/ticket/224" target="_blank" title="https://trac.zulip.net/ticket/224">#224</a> and <a href="https://trac.zulip.net/ticket/115" target="_blank" title="https://trac.zulip.net/ticket/115">#115</a>, but not issue#124 or #1124z or <a href="https://trac.zulip.net/ticket/16" target="_blank" title="https://trac.zulip.net/ticket/16">trac #15</a> today.</p>') self.assertEqual(converted_topic, [u'https://trac.zulip.net/ticket/444']) RealmFilter(realm=realm, pattern=r'#(?P<id>[a-zA-Z]+-[0-9]+)', url_format_string=r'https://trac.zulip.net/ticket/%(id)s').save() msg = Message(sender=self.example_user('hamlet')) content = '#ZUL-123 was fixed and code was deployed to production, also #zul-321 was deployed to staging' converted = bugdown.convert(content, message_realm=realm, message=msg) self.assertEqual(converted, '<p><a href="https://trac.zulip.net/ticket/ZUL-123" target="_blank" title="https://trac.zulip.net/ticket/ZUL-123">#ZUL-123</a> was fixed and code was deployed to production, also <a href="https://trac.zulip.net/ticket/zul-321" target="_blank" title="https://trac.zulip.net/ticket/zul-321">#zul-321</a> was deployed to staging</p>') def test_maybe_update_markdown_engines(self) -> None: realm = get_realm('zulip') url_format_string = r"https://trac.zulip.net/ticket/%(id)s" realm_filter = RealmFilter(realm=realm, pattern=r"#(?P<id>[0-9]{2,8})", url_format_string=url_format_string) realm_filter.save() bugdown.realm_filter_data = {} bugdown.maybe_update_markdown_engines(None, False) all_filters = bugdown.realm_filter_data zulip_filters = all_filters[realm.id] self.assertEqual(len(zulip_filters), 1) self.assertEqual(zulip_filters[0], (u'#(?P<id>[0-9]{2,8})', u'https://trac.zulip.net/ticket/%(id)s', realm_filter.id)) def test_flush_realm_filter(self) -> None: realm = get_realm('zulip') def flush() -> None: ''' flush_realm_filter is a post-save hook, so calling it directly for testing is kind of awkward ''' class Instance: realm_id = None # type: Optional[int] instance = Instance() instance.realm_id = realm.id flush_realm_filter(sender=None, instance=instance) def save_new_realm_filter() -> None: realm_filter = RealmFilter(realm=realm, pattern=r"whatever", url_format_string='whatever') realm_filter.save() # start fresh for our realm flush() self.assertFalse(realm_in_local_realm_filters_cache(realm.id)) # call this just for side effects of populating the cache realm_filters_for_realm(realm.id) self.assertTrue(realm_in_local_realm_filters_cache(realm.id)) # Saving a new RealmFilter should have the side effect of # flushing the cache. save_new_realm_filter() self.assertFalse(realm_in_local_realm_filters_cache(realm.id)) # and flush it one more time, to make sure we don't get a KeyError flush() self.assertFalse(realm_in_local_realm_filters_cache(realm.id)) def test_realm_patterns_negative(self) -> None: realm = get_realm('zulip') RealmFilter(realm=realm, pattern=r"#(?P<id>[0-9]{2,8})", url_format_string=r"https://trac.zulip.net/ticket/%(id)s").save() boring_msg = Message(sender=self.example_user('othello')) boring_msg.set_topic_name("no match here") converted_boring_topic = bugdown.topic_links(realm.id, boring_msg.topic_name()) self.assertEqual(converted_boring_topic, []) def test_is_status_message(self) -> None: user_profile = self.example_user('othello') msg = Message(sender=user_profile, sending_client=get_client("test")) content = '/me makes a list\n* one\n* two' rendered_content = render_markdown(msg, content) self.assertEqual( rendered_content, '<p>/me makes a list</p>\n<ul>\n<li>one</li>\n<li>two</li>\n</ul>' ) self.assertFalse(Message.is_status_message(content, rendered_content)) content = '/me takes a walk' rendered_content = render_markdown(msg, content) self.assertEqual( rendered_content, '<p>/me takes a walk</p>' ) self.assertTrue(Message.is_status_message(content, rendered_content)) content = '/me writes a second line\nline' rendered_content = render_markdown(msg, content) self.assertEqual( rendered_content, '<p>/me writes a second line<br>\nline</p>' ) self.assertFalse(Message.is_status_message(content, rendered_content)) def test_alert_words(self) -> None: user_profile = self.example_user('othello') do_set_alert_words(user_profile, ["ALERTWORD", "scaryword"]) msg = Message(sender=user_profile, sending_client=get_client("test")) realm_alert_words = alert_words_in_realm(user_profile.realm) def render(msg: Message, content: str) -> str: return render_markdown(msg, content, realm_alert_words=realm_alert_words, user_ids={user_profile.id}) content = "We have an ALERTWORD day today!" self.assertEqual(render(msg, content), "<p>We have an ALERTWORD day today!</p>") self.assertEqual(msg.user_ids_with_alert_words, set([user_profile.id])) msg = Message(sender=user_profile, sending_client=get_client("test")) content = "We have a NOTHINGWORD day today!" self.assertEqual(render(msg, content), "<p>We have a NOTHINGWORD day today!</p>") self.assertEqual(msg.user_ids_with_alert_words, set()) def test_mention_wildcard(self) -> None: user_profile = self.example_user('othello') msg = Message(sender=user_profile, sending_client=get_client("test")) content = "@**all** test" self.assertEqual(render_markdown(msg, content), '<p><span class="user-mention" data-user-id="*">' '@all' '</span> test</p>') self.assertTrue(msg.mentions_wildcard) def test_mention_everyone(self) -> None: user_profile = self.example_user('othello') msg = Message(sender=user_profile, sending_client=get_client("test")) content = "@**everyone** test" self.assertEqual(render_markdown(msg, content), '<p><span class="user-mention" data-user-id="*">' '@everyone' '</span> test</p>') self.assertTrue(msg.mentions_wildcard) def test_mention_stream(self) -> None: user_profile = self.example_user('othello') msg = Message(sender=user_profile, sending_client=get_client("test")) content = "@**stream** test" self.assertEqual(render_markdown(msg, content), '<p><span class="user-mention" data-user-id="*">' '@stream' '</span> test</p>') self.assertTrue(msg.mentions_wildcard) def test_mention_at_wildcard(self) -> None: user_profile = self.example_user('othello') msg = Message(sender=user_profile, sending_client=get_client("test")) content = "@all test" self.assertEqual(render_markdown(msg, content), '<p>@all test</p>') self.assertFalse(msg.mentions_wildcard) self.assertEqual(msg.mentions_user_ids, set([])) def test_mention_at_everyone(self) -> None: user_profile = self.example_user('othello') msg = Message(sender=user_profile, sending_client=get_client("test")) content = "@everyone test" self.assertEqual(render_markdown(msg, content), '<p>@everyone test</p>') self.assertFalse(msg.mentions_wildcard) self.assertEqual(msg.mentions_user_ids, set([])) def test_mention_word_starting_with_at_wildcard(self) -> None: user_profile = self.example_user('othello') msg = Message(sender=user_profile, sending_client=get_client("test")) content = "test @alleycat.com test" self.assertEqual(render_markdown(msg, content), '<p>test @alleycat.com test</p>') self.assertFalse(msg.mentions_wildcard) self.assertEqual(msg.mentions_user_ids, set([])) def test_mention_at_normal_user(self) -> None: user_profile = self.example_user('othello') msg = Message(sender=user_profile, sending_client=get_client("test")) content = "@aaron test" self.assertEqual(render_markdown(msg, content), '<p>@aaron test</p>') self.assertFalse(msg.mentions_wildcard) self.assertEqual(msg.mentions_user_ids, set([])) def test_mention_single(self) -> None: sender_user_profile = self.example_user('othello') user_profile = self.example_user('hamlet') msg = Message(sender=sender_user_profile, sending_client=get_client("test")) user_id = user_profile.id content = "@**King Hamlet**" self.assertEqual(render_markdown(msg, content), '<p><span class="user-mention" ' 'data-user-id="%s">' '@King Hamlet</span></p>' % (user_id)) self.assertEqual(msg.mentions_user_ids, set([user_profile.id])) def test_possible_mentions(self) -> None: def assert_mentions(content: str, names: Set[str]) -> None: self.assertEqual(possible_mentions(content), names) assert_mentions('', set()) assert_mentions('boring', set()) assert_mentions('@**all**', set()) assert_mentions('smush@**steve**smush', set()) assert_mentions( 'Hello @**King Hamlet** and @**Cordelia Lear**\n@**Foo van Barson|1234** @**all**', {'King Hamlet', 'Cordelia Lear', 'Foo van Barson|1234'} ) def test_mention_multiple(self) -> None: sender_user_profile = self.example_user('othello') hamlet = self.example_user('hamlet') cordelia = self.example_user('cordelia') msg = Message(sender=sender_user_profile, sending_client=get_client("test")) content = "@**King Hamlet** and @**Cordelia Lear**, check this out" self.assertEqual(render_markdown(msg, content), '<p>' '<span class="user-mention" ' 'data-user-id="%s">@King Hamlet</span> and ' '<span class="user-mention" ' 'data-user-id="%s">@Cordelia Lear</span>, ' 'check this out</p>' % (hamlet.id, cordelia.id)) self.assertEqual(msg.mentions_user_ids, set([hamlet.id, cordelia.id])) def test_mention_duplicate_full_name(self) -> None: realm = get_realm('zulip') def make_user(email: str, full_name: str) -> UserProfile: return create_user( email=email, password='whatever', realm=realm, full_name=full_name, short_name='whatever', ) sender_user_profile = self.example_user('othello') twin1 = make_user('twin1@example.com', 'Mark Twin') twin2 = make_user('twin2@example.com', 'Mark Twin') cordelia = self.example_user('cordelia') msg = Message(sender=sender_user_profile, sending_client=get_client("test")) content = "@**Mark Twin|{}**, @**Mark Twin|{}** and @**Cordelia Lear**, hi.".format(twin1.id, twin2.id) self.assertEqual(render_markdown(msg, content), '<p>' '<span class="user-mention" ' 'data-user-id="%s">@Mark Twin</span>, ' '<span class="user-mention" ' 'data-user-id="%s">@Mark Twin</span> and ' '<span class="user-mention" ' 'data-user-id="%s">@Cordelia Lear</span>, ' 'hi.</p>' % (twin1.id, twin2.id, cordelia.id)) self.assertEqual(msg.mentions_user_ids, set([twin1.id, twin2.id, cordelia.id])) def test_mention_invalid(self) -> None: sender_user_profile = self.example_user('othello') msg = Message(sender=sender_user_profile, sending_client=get_client("test")) content = "Hey @**Nonexistent User**" self.assertEqual(render_markdown(msg, content), '<p>Hey @<strong>Nonexistent User</strong></p>') self.assertEqual(msg.mentions_user_ids, set()) def create_user_group_for_test(self, user_group_name: str) -> UserGroup: othello = self.example_user('othello') return create_user_group(user_group_name, [othello], get_realm('zulip')) def test_user_group_mention_single(self) -> None: sender_user_profile = self.example_user('othello') user_profile = self.example_user('hamlet') msg = Message(sender=sender_user_profile, sending_client=get_client("test")) user_id = user_profile.id user_group = self.create_user_group_for_test('support') content = "@**King Hamlet** @*support*" self.assertEqual(render_markdown(msg, content), '<p><span class="user-mention" ' 'data-user-id="%s">' '@King Hamlet</span> ' '<span class="user-group-mention" ' 'data-user-group-id="%s">' '@support</span></p>' % (user_id, user_group.id)) self.assertEqual(msg.mentions_user_ids, set([user_profile.id])) self.assertEqual(msg.mentions_user_group_ids, set([user_group.id])) def test_possible_user_group_mentions(self) -> None: def assert_mentions(content: str, names: Set[str]) -> None: self.assertEqual(possible_user_group_mentions(content), names) assert_mentions('', set()) assert_mentions('boring', set()) assert_mentions('@**all**', set()) assert_mentions('smush@*steve*smush', set()) assert_mentions( '@*support* Hello @**King Hamlet** and @**Cordelia Lear**\n' '@**Foo van Barson** @**all**', {'support'} ) assert_mentions( 'Attention @*support*, @*frontend* and @*backend*\ngroups.', {'support', 'frontend', 'backend'} ) def test_user_group_mention_multiple(self) -> None: sender_user_profile = self.example_user('othello') msg = Message(sender=sender_user_profile, sending_client=get_client("test")) support = self.create_user_group_for_test('support') backend = self.create_user_group_for_test('backend') content = "@*support* and @*backend*, check this out" self.assertEqual(render_markdown(msg, content), '<p>' '<span class="user-group-mention" ' 'data-user-group-id="%s">' '@support</span> ' 'and ' '<span class="user-group-mention" ' 'data-user-group-id="%s">' '@backend</span>, ' 'check this out' '</p>' % (support.id, backend.id)) self.assertEqual(msg.mentions_user_group_ids, set([support.id, backend.id])) def test_user_group_mention_invalid(self) -> None: sender_user_profile = self.example_user('othello') msg = Message(sender=sender_user_profile, sending_client=get_client("test")) content = "Hey @*Nonexistent group*" self.assertEqual(render_markdown(msg, content), '<p>Hey @<em>Nonexistent group</em></p>') self.assertEqual(msg.mentions_user_group_ids, set()) def test_stream_single(self) -> None: denmark = get_stream('Denmark', get_realm('zulip')) sender_user_profile = self.example_user('othello') msg = Message(sender=sender_user_profile, sending_client=get_client("test")) content = "#**Denmark**" self.assertEqual( render_markdown(msg, content), '<p><a class="stream" data-stream-id="{d.id}" href="/#narrow/stream/{d.id}-Denmark">#{d.name}</a></p>'.format( d=denmark )) def test_stream_multiple(self) -> None: sender_user_profile = self.example_user('othello') msg = Message(sender=sender_user_profile, sending_client=get_client("test")) realm = get_realm('zulip') denmark = get_stream('Denmark', realm) scotland = get_stream('Scotland', realm) content = "Look to #**Denmark** and #**Scotland**, there something" self.assertEqual(render_markdown(msg, content), '<p>Look to ' '<a class="stream" ' 'data-stream-id="{denmark.id}" ' 'href="/#narrow/stream/{denmark.id}-Denmark">#{denmark.name}</a> and ' '<a class="stream" ' 'data-stream-id="{scotland.id}" ' 'href="/#narrow/stream/{scotland.id}-Scotland">#{scotland.name}</a>, ' 'there something</p>'.format(denmark=denmark, scotland=scotland)) def test_stream_case_sensitivity(self) -> None: realm = get_realm('zulip') case_sens = Stream.objects.create(name='CaseSens', realm=realm) sender_user_profile = self.example_user('othello') msg = Message(sender=sender_user_profile, sending_client=get_client("test")) content = "#**CaseSens**" self.assertEqual( render_markdown(msg, content), '<p><a class="stream" data-stream-id="{s.id}" href="/#narrow/stream/{s.id}-{s.name}">#{s.name}</a></p>'.format( s=case_sens )) def test_stream_case_sensitivity_nonmatching(self) -> None: """#StreamName requires the stream be spelled with the correct case currently. If we change that in the future, we'll need to change this test.""" realm = get_realm('zulip') Stream.objects.create(name='CaseSens', realm=realm) sender_user_profile = self.example_user('othello') msg = Message(sender=sender_user_profile, sending_client=get_client("test")) content = "#**casesens**" self.assertEqual( render_markdown(msg, content), '<p>#<strong>casesens</strong></p>') def test_possible_stream_names(self) -> None: content = '''#**test here** This mentions #**Denmark** too. #**garçon** #**천국** @**Ignore Person** ''' self.assertEqual( bugdown.possible_linked_stream_names(content), {'test here', 'Denmark', 'garçon', '천국'} ) def test_stream_unicode(self) -> None: realm = get_realm('zulip') uni = Stream.objects.create(name=u'привет', realm=realm) sender_user_profile = self.example_user('othello') msg = Message(sender=sender_user_profile, sending_client=get_client("test")) content = u"#**привет**" quoted_name = '.D0.BF.D1.80.D0.B8.D0.B2.D0.B5.D1.82' href = '/#narrow/stream/{stream_id}-{quoted_name}'.format( stream_id=uni.id, quoted_name=quoted_name) self.assertEqual( render_markdown(msg, content), u'<p><a class="stream" data-stream-id="{s.id}" href="{href}">#{s.name}</a></p>'.format( s=uni, href=href, )) def test_stream_invalid(self) -> None: sender_user_profile = self.example_user('othello') msg = Message(sender=sender_user_profile, sending_client=get_client("test")) content = "There #**Nonexistentstream**" self.assertEqual(render_markdown(msg, content), '<p>There #<strong>Nonexistentstream</strong></p>') self.assertEqual(msg.mentions_user_ids, set()) def test_in_app_modal_link(self) -> None: msg = '!modal_link(#settings, Settings page)' converted = bugdown_convert(msg) self.assertEqual( converted, '<p>' '<a href="#settings" title="#settings">Settings page</a>' '</p>' ) def test_image_preview_title(self) -> None: msg = '[My favorite image](https://example.com/testimage.png)' converted = bugdown_convert(msg) self.assertEqual( converted, '<p>' '<a href="https://example.com/testimage.png" target="_blank" title="https://example.com/testimage.png">My favorite image</a>' '</p>\n' '<div class="message_inline_image">' '<a href="https://example.com/testimage.png" target="_blank" title="My favorite image">' '<img data-src-fullsize="/thumbnail?url=https%3A%2F%2Fexample.com%2Ftestimage.png&amp;size=full" src="/thumbnail?url=https%3A%2F%2Fexample.com%2Ftestimage.png&amp;size=thumbnail">' '</a>' '</div>' ) def test_mit_rendering(self) -> None: """Test the markdown configs for the MIT Zephyr mirroring system; verifies almost all inline patterns are disabled, but inline_interesting_links is still enabled""" msg = "**test**" realm = get_realm("zephyr") client = get_client("zephyr_mirror") message = Message(sending_client=client, sender=self.mit_user("sipbtest")) converted = bugdown.convert(msg, message_realm=realm, message=message) self.assertEqual( converted, "<p>**test**</p>", ) msg = "* test" converted = bugdown.convert(msg, message_realm=realm, message=message) self.assertEqual( converted, "<p>* test</p>", ) msg = "https://lists.debian.org/debian-ctte/2014/02/msg00173.html" converted = bugdown.convert(msg, message_realm=realm, message=message) self.assertEqual( converted, '<p><a href="https://lists.debian.org/debian-ctte/2014/02/msg00173.html" target="_blank" title="https://lists.debian.org/debian-ctte/2014/02/msg00173.html">https://lists.debian.org/debian-ctte/2014/02/msg00173.html</a></p>', ) def test_url_to_a(self) -> None: url = 'javascript://example.com/invalidURL' converted = bugdown.url_to_a(db_data=None, url=url, text=url) self.assertEqual( converted, 'javascript://example.com/invalidURL', ) def test_disabled_code_block_processor(self) -> None: msg = "Hello,\n\n" + \ " I am writing this message to test something. I am writing this message to test something." converted = bugdown_convert(msg) expected_output = '<p>Hello,</p>\n' + \ '<div class="codehilite"><pre><span></span>I am writing this message to test something. I am writing this message to test something.\n' + \ '</pre></div>' self.assertEqual(converted, expected_output) realm = Realm.objects.create(string_id='code_block_processor_test') bugdown.maybe_update_markdown_engines(realm.id, True) converted = bugdown.convert(msg, message_realm=realm, email_gateway=True) expected_output = '<p>Hello,</p>\n' + \ '<p>I am writing this message to test something. I am writing this message to test something.</p>' self.assertEqual(converted, expected_output) def test_normal_link(self) -> None: realm = get_realm("zulip") sender_user_profile = self.example_user('othello') message = Message(sender=sender_user_profile, sending_client=get_client("test")) msg = "http://example.com/#settings/" self.assertEqual( bugdown.convert(msg, message_realm=realm, message=message), '<p><a href="http://example.com/#settings/" target="_blank" title="http://example.com/#settings/">http://example.com/#settings/</a></p>' ) def test_relative_link(self) -> None: realm = get_realm("zulip") sender_user_profile = self.example_user('othello') message = Message(sender=sender_user_profile, sending_client=get_client("test")) msg = "http://zulip.testserver/#narrow/stream/999-hello" self.assertEqual( bugdown.convert(msg, message_realm=realm, message=message), '<p><a href="#narrow/stream/999-hello" title="#narrow/stream/999-hello">http://zulip.testserver/#narrow/stream/999-hello</a></p>' ) def test_relative_link_streams_page(self) -> None: realm = get_realm("zulip") sender_user_profile = self.example_user('othello') message = Message(sender=sender_user_profile, sending_client=get_client("test")) msg = "http://zulip.testserver/#streams/all" self.assertEqual( bugdown.convert(msg, message_realm=realm, message=message), '<p><a href="#streams/all" target="_blank" title="#streams/all">http://zulip.testserver/#streams/all</a></p>' ) def test_md_relative_link(self) -> None: realm = get_realm("zulip") sender_user_profile = self.example_user('othello') message = Message(sender=sender_user_profile, sending_client=get_client("test")) msg = "[hello](http://zulip.testserver/#narrow/stream/999-hello)" self.assertEqual( bugdown.convert(msg, message_realm=realm, message=message), '<p><a href="#narrow/stream/999-hello" title="#narrow/stream/999-hello">hello</a></p>' ) class BugdownApiTests(ZulipTestCase): def test_render_message_api(self) -> None: content = 'That is a **bold** statement' result = self.api_post( self.example_email("othello"), '/api/v1/messages/render', dict(content=content) ) self.assert_json_success(result) self.assertEqual(result.json()['rendered'], u'<p>That is a <strong>bold</strong> statement</p>') def test_render_mention_stream_api(self) -> None: """Determines whether we're correctly passing the realm context""" content = 'This mentions #**Denmark** and @**King Hamlet**.' result = self.api_post( self.example_email("othello"), '/api/v1/messages/render', dict(content=content) ) self.assert_json_success(result) user_id = self.example_user('hamlet').id stream_id = get_stream('Denmark', get_realm('zulip')).id self.assertEqual(result.json()['rendered'], u'<p>This mentions <a class="stream" data-stream-id="%s" href="/#narrow/stream/%s-Denmark">#Denmark</a> and <span class="user-mention" data-user-id="%s">@King Hamlet</span>.</p>' % (stream_id, stream_id, user_id)) class BugdownErrorTests(ZulipTestCase): def test_bugdown_error_handling(self) -> None: with self.simulated_markdown_failure(): with self.assertRaises(BugdownRenderingException): bugdown_convert('') def test_send_message_errors(self) -> None: message = 'whatever' with self.simulated_markdown_failure(): # We don't use assertRaisesRegex because it seems to not # handle i18n properly here on some systems. with self.assertRaises(JsonableError): self.send_stream_message(self.example_email("othello"), "Denmark", message) def test_ultra_long_rendering(self) -> None: """A rendered message with an ultra-long lenght (> 10 * MAX_MESSAGE_LENGTH) throws an exception""" msg = u'mock rendered message\n' * MAX_MESSAGE_LENGTH with mock.patch('zerver.lib.bugdown.timeout', return_value=msg), \ mock.patch('zerver.lib.bugdown.bugdown_logger'): with self.assertRaises(BugdownRenderingException): bugdown_convert(msg) class BugdownAvatarTestCase(ZulipTestCase): def test_possible_avatar_emails(self) -> None: content = ''' hello !avatar(foo@example.com) my email is ignore@ignore.com !gravatar(bar@yo.tv) smushing!avatar(hamlet@example.org) is allowed ''' self.assertEqual( bugdown.possible_avatar_emails(content), {'foo@example.com', 'bar@yo.tv', 'hamlet@example.org'}, ) def test_avatar_with_id(self) -> None: sender_user_profile = self.example_user('othello') message = Message(sender=sender_user_profile, sending_client=get_client("test")) user_profile = self.example_user('hamlet') msg = '!avatar({0})'.format(user_profile.email) converted = bugdown.convert(msg, message=message) values = {'email': user_profile.email, 'id': user_profile.id} self.assertEqual( converted, '<p><img alt="{email}" class="message_body_gravatar" src="/avatar/{id}?s=30" title="{email}"></p>'.format(**values)) def test_avatar_of_unregistered_user(self) -> None: sender_user_profile = self.example_user('othello') message = Message(sender=sender_user_profile, sending_client=get_client("test")) email = 'fakeuser@example.com' msg = '!avatar({0})'.format(email) converted = bugdown.convert(msg, message=message) self.assertEqual( converted, '<p><img alt="{0}" class="message_body_gravatar" src="/avatar/{0}?s=30" title="{0}"></p>'.format(email))
[ "str", "str", "str", "Any", "Any", "str", "str", "str", "str", "str", "str", "str", "int", "Message", "str", "str", "Set[str]", "str", "str", "str", "str", "Set[str]" ]
[ 4396, 5254, 5270, 7592, 7605, 10170, 10180, 34778, 36131, 36148, 42842, 42858, 42873, 51746, 51764, 56334, 56346, 57777, 57793, 59553, 60786, 60798 ]
[ 4399, 5257, 5273, 7595, 7608, 10173, 10183, 34781, 36134, 36151, 42845, 42861, 42876, 51753, 51767, 56337, 56354, 57780, 57796, 59556, 60789, 60806 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_cache.py
from mock import Mock, patch from zerver.apps import flush_cache from zerver.lib.test_classes import ZulipTestCase class AppsTest(ZulipTestCase): def test_cache_gets_flushed(self) -> None: with patch('zerver.apps.logging.info') as mock_logging: with patch('zerver.apps.cache.clear') as mock: # The argument to flush_cache doesn't matter flush_cache(Mock()) mock.assert_called_once() mock_logging.assert_called_once()
[]
[]
[]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_compatibility.py
from zerver.lib.test_classes import ZulipTestCase class CompatibilityTest(ZulipTestCase): def test_compatibility(self) -> None: result = self.client_get("/compatibility", HTTP_USER_AGENT='ZulipMobile/5.0') self.assert_json_success(result) result = self.client_get("/compatibility", HTTP_USER_AGENT='ZulipInvalid/5.0') self.assert_json_error(result, "Client is too old")
[]
[]
[]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_custom_profile_data.py
# -*- coding: utf-8 -*- from typing import Union, List, Dict, Any from mock import patch from zerver.lib.actions import get_realm, try_add_realm_custom_profile_field, \ do_update_user_custom_profile_data, do_remove_realm_custom_profile_field, \ try_reorder_realm_custom_profile_fields from zerver.lib.test_classes import ZulipTestCase from zerver.models import CustomProfileField, \ custom_profile_fields_for_realm, get_realm, CustomProfileFieldValue import ujson class CustomProfileFieldTest(ZulipTestCase): def setUp(self) -> None: self.realm = get_realm("zulip") self.original_count = len(custom_profile_fields_for_realm(self.realm.id)) def custom_field_exists_in_realm(self, field_id: int) -> bool: fields = custom_profile_fields_for_realm(self.realm.id) field_ids = [field.id for field in fields] return (field_id in field_ids) def test_list(self) -> None: self.login(self.example_email("iago")) result = self.client_get("/json/realm/profile_fields") self.assert_json_success(result) self.assertEqual(200, result.status_code) content = result.json() self.assertEqual(len(content["custom_fields"]), self.original_count) def test_list_order(self) -> None: self.login(self.example_email("iago")) realm = get_realm('zulip') order = ( CustomProfileField.objects.filter(realm=realm) .order_by('-order') .values_list('order', flat=True) ) try_reorder_realm_custom_profile_fields(realm, order) result = self.client_get("/json/realm/profile_fields") content = result.json() self.assertListEqual(content["custom_fields"], sorted(content["custom_fields"], key=lambda x: -x["id"])) def test_create(self) -> None: self.login(self.example_email("iago")) realm = get_realm('zulip') data = {"name": u"Phone", "field_type": "text id"} # type: Dict[str, Any] result = self.client_post("/json/realm/profile_fields", info=data) self.assert_json_error(result, u'Argument "field_type" is not valid JSON.') data["name"] = "" data["field_type"] = 100 result = self.client_post("/json/realm/profile_fields", info=data) self.assert_json_error(result, u'Name cannot be blank.') data["name"] = "*" * 41 data["field_type"] = 100 result = self.client_post("/json/realm/profile_fields", info=data) self.assert_json_error(result, 'name is too long (limit: 40 characters)') data["name"] = "Phone" result = self.client_post("/json/realm/profile_fields", info=data) self.assert_json_error(result, u'Invalid field type.') data["name"] = "Phone" data["hint"] = "*" * 81 data["field_type"] = CustomProfileField.SHORT_TEXT result = self.client_post("/json/realm/profile_fields", info=data) msg = "hint is too long (limit: 80 characters)" self.assert_json_error(result, msg) data["name"] = "Phone" data["hint"] = "Contact number" data["field_type"] = CustomProfileField.SHORT_TEXT result = self.client_post("/json/realm/profile_fields", info=data) self.assert_json_success(result) field = CustomProfileField.objects.get(name="Phone", realm=realm) self.assertEqual(field.id, field.order) result = self.client_post("/json/realm/profile_fields", info=data) self.assert_json_error(result, u'A field with that name already exists.') def test_create_choice_field(self) -> None: self.login(self.example_email("iago")) data = {} # type: Dict[str, Union[str, int]] data["name"] = "Favorite programming language" data["field_type"] = CustomProfileField.CHOICE data['field_data'] = 'invalid' result = self.client_post("/json/realm/profile_fields", info=data) error_msg = "Bad value for 'field_data': invalid" self.assert_json_error(result, error_msg) data["field_data"] = ujson.dumps({ 'python': ['1'], 'java': ['2'], }) result = self.client_post("/json/realm/profile_fields", info=data) self.assert_json_error(result, 'field_data is not a dict') data["field_data"] = ujson.dumps({ 'python': {'text': 'Python'}, 'java': {'text': 'Java'}, }) result = self.client_post("/json/realm/profile_fields", info=data) self.assert_json_error(result, "order key is missing from field_data") data["field_data"] = ujson.dumps({ 'python': {'text': 'Python', 'order': ''}, 'java': {'text': 'Java', 'order': '2'}, }) result = self.client_post("/json/realm/profile_fields", info=data) self.assert_json_error(result, 'field_data["order"] cannot be blank.') data["field_data"] = ujson.dumps({ '': {'text': 'Python', 'order': '1'}, 'java': {'text': 'Java', 'order': '2'}, }) result = self.client_post("/json/realm/profile_fields", info=data) self.assert_json_error(result, "'value' cannot be blank.") data["field_data"] = ujson.dumps({ 'python': {'text': 'Python', 'order': 1}, 'java': {'text': 'Java', 'order': '2'}, }) result = self.client_post("/json/realm/profile_fields", info=data) self.assert_json_error(result, 'field_data["order"] is not a string') data["field_data"] = ujson.dumps({}) result = self.client_post("/json/realm/profile_fields", info=data) self.assert_json_error(result, 'Field must have at least one choice.') data["field_data"] = ujson.dumps({ 'python': {'text': 'Python', 'order': '1'}, 'java': {'text': 'Java', 'order': '2'}, }) result = self.client_post("/json/realm/profile_fields", info=data) self.assert_json_success(result) def test_not_realm_admin(self) -> None: self.login(self.example_email("hamlet")) result = self.client_post("/json/realm/profile_fields") self.assert_json_error(result, u'Must be an organization administrator') result = self.client_delete("/json/realm/profile_fields/1") self.assert_json_error(result, 'Must be an organization administrator') def test_delete(self) -> None: self.login(self.example_email("iago")) realm = get_realm('zulip') field = CustomProfileField.objects.get(name="Phone number", realm=realm) result = self.client_delete("/json/realm/profile_fields/100") self.assert_json_error(result, 'Field id 100 not found.') self.assertTrue(self.custom_field_exists_in_realm(field.id)) result = self.client_delete( "/json/realm/profile_fields/{}".format(field.id)) self.assert_json_success(result) self.assertFalse(self.custom_field_exists_in_realm(field.id)) def test_update(self) -> None: self.login(self.example_email("iago")) realm = get_realm('zulip') result = self.client_patch( "/json/realm/profile_fields/100", info={'name': '', 'field_type': CustomProfileField.SHORT_TEXT} ) self.assert_json_error(result, u'Name cannot be blank.') result = self.client_patch( "/json/realm/profile_fields/100", info={'name': 'Phone Number', 'field_type': CustomProfileField.SHORT_TEXT} ) self.assert_json_error(result, u'Field id 100 not found.') field = CustomProfileField.objects.get(name="Phone number", realm=realm) self.assertEqual(CustomProfileField.objects.count(), self.original_count) result = self.client_patch( "/json/realm/profile_fields/{}".format(field.id), info={'name': 'New phone number', 'field_type': CustomProfileField.SHORT_TEXT}) self.assert_json_success(result) field = CustomProfileField.objects.get(id=field.id, realm=realm) self.assertEqual(CustomProfileField.objects.count(), self.original_count) self.assertEqual(field.name, 'New phone number') self.assertIs(field.hint, '') self.assertEqual(field.field_type, CustomProfileField.SHORT_TEXT) result = self.client_patch( "/json/realm/profile_fields/{}".format(field.id), info={'name': '*' * 41, 'field_type': CustomProfileField.SHORT_TEXT}) msg = "name is too long (limit: 40 characters)" self.assert_json_error(result, msg) result = self.client_patch( "/json/realm/profile_fields/{}".format(field.id), info={'name': 'New phone number', 'hint': '*' * 81, 'field_type': CustomProfileField.SHORT_TEXT}) msg = "hint is too long (limit: 80 characters)" self.assert_json_error(result, msg) result = self.client_patch( "/json/realm/profile_fields/{}".format(field.id), info={'name': 'New phone number', 'hint': 'New contact number', 'field_type': CustomProfileField.SHORT_TEXT}) self.assert_json_success(result) field = CustomProfileField.objects.get(id=field.id, realm=realm) self.assertEqual(CustomProfileField.objects.count(), self.original_count) self.assertEqual(field.name, 'New phone number') self.assertEqual(field.hint, 'New contact number') self.assertEqual(field.field_type, CustomProfileField.SHORT_TEXT) field = CustomProfileField.objects.get(name="Favorite editor", realm=realm) result = self.client_patch( "/json/realm/profile_fields/{}".format(field.id), info={'name': 'Favorite editor', 'field_data': 'invalid'}) self.assert_json_error(result, "Bad value for 'field_data': invalid") field_data = ujson.dumps({ 'vim': 'Vim', 'emacs': {'order': '2', 'text': 'Emacs'}, }) result = self.client_patch( "/json/realm/profile_fields/{}".format(field.id), info={'name': 'Favorite editor', 'field_data': field_data}) self.assert_json_error(result, "field_data is not a dict") field_data = ujson.dumps({ 'vim': {'order': '1', 'text': 'Vim'}, 'emacs': {'order': '2', 'text': 'Emacs'}, 'notepad': {'order': '3', 'text': 'Notepad'}, }) result = self.client_patch( "/json/realm/profile_fields/{}".format(field.id), info={'name': 'Favorite editor', 'field_data': field_data}) self.assert_json_success(result) def test_update_is_aware_of_uniqueness(self) -> None: self.login(self.example_email("iago")) realm = get_realm('zulip') field_1 = try_add_realm_custom_profile_field(realm, u"Phone", CustomProfileField.SHORT_TEXT) field_2 = try_add_realm_custom_profile_field(realm, u"Phone 1", CustomProfileField.SHORT_TEXT) self.assertTrue(self.custom_field_exists_in_realm(field_1.id)) self.assertTrue(self.custom_field_exists_in_realm(field_2.id)) result = self.client_patch( "/json/realm/profile_fields/{}".format(field_2.id), info={'name': 'Phone', 'field_type': CustomProfileField.SHORT_TEXT}) self.assert_json_error( result, u'A field with that name already exists.') def assert_error_update_invalid_value(self, field_name: str, new_value: object, error_msg: str) -> None: self.login(self.example_email("iago")) realm = get_realm('zulip') field = CustomProfileField.objects.get(name=field_name, realm=realm) # Update value of field result = self.client_patch("/json/users/me/profile_data", {'data': ujson.dumps([{"id": field.id, "value": new_value}])}) self.assert_json_error(result, error_msg) def test_reorder(self) -> None: self.login(self.example_email("iago")) realm = get_realm('zulip') order = ( CustomProfileField.objects.filter(realm=realm) .order_by('-order') .values_list('order', flat=True) ) result = self.client_patch("/json/realm/profile_fields", info={'order': ujson.dumps(order)}) self.assert_json_success(result) fields = CustomProfileField.objects.filter(realm=realm).order_by('order') for field in fields: self.assertEqual(field.id, order[field.order]) def test_reorder_duplicates(self) -> None: self.login(self.example_email("iago")) realm = get_realm('zulip') order = ( CustomProfileField.objects.filter(realm=realm) .order_by('-order') .values_list('order', flat=True) ) order = list(order) order.append(4) result = self.client_patch("/json/realm/profile_fields", info={'order': ujson.dumps(order)}) self.assert_json_success(result) fields = CustomProfileField.objects.filter(realm=realm).order_by('order') for field in fields: self.assertEqual(field.id, order[field.order]) def test_reorder_unauthorized(self) -> None: self.login(self.example_email("hamlet")) realm = get_realm('zulip') order = ( CustomProfileField.objects.filter(realm=realm) .order_by('-order') .values_list('order', flat=True) ) result = self.client_patch("/json/realm/profile_fields", info={'order': ujson.dumps(order)}) self.assert_json_error(result, "Must be an organization administrator") def test_reorder_invalid(self) -> None: self.login(self.example_email("iago")) order = [100, 200, 300] result = self.client_patch("/json/realm/profile_fields", info={'order': ujson.dumps(order)}) self.assert_json_error( result, u'Invalid order mapping.') order = [1, 2] result = self.client_patch("/json/realm/profile_fields", info={'order': ujson.dumps(order)}) self.assert_json_error( result, u'Invalid order mapping.') def test_update_invalid_field(self) -> None: self.login(self.example_email("iago")) data = [{'id': 1234, 'value': '12'}] result = self.client_patch("/json/users/me/profile_data", { 'data': ujson.dumps(data) }) self.assert_json_error(result, u"Field id 1234 not found.") def test_delete_field_value(self) -> None: iago = self.example_user("iago") self.login(iago.email) realm = get_realm("zulip") invalid_field_id = 1234 result = self.client_delete("/json/users/me/profile_data", { 'data': ujson.dumps([invalid_field_id]) }) self.assert_json_error(result, u'Field id %d not found.' % (invalid_field_id)) field = CustomProfileField.objects.get(name="Mentor", realm=realm) data = [{'id': field.id, 'value': [self.example_user("aaron").id]}] # type: List[Dict[str, Union[int, str, List[int]]]] do_update_user_custom_profile_data(iago, data) iago_value = CustomProfileFieldValue.objects.get(user_profile=iago, field=field) converter = field.FIELD_CONVERTERS[field.field_type] self.assertEqual([self.example_user("aaron").id], converter(iago_value.value)) result = self.client_delete("/json/users/me/profile_data", { 'data': ujson.dumps([field.id]) }) self.assert_json_success(result) # Don't throw an exception here result = self.client_delete("/json/users/me/profile_data", { 'data': ujson.dumps([field.id]) }) self.assert_json_success(result) def test_update_invalid_short_text(self) -> None: field_name = "Phone number" self.assert_error_update_invalid_value(field_name, 't' * 201, u"{} is too long (limit: 50 characters)".format(field_name)) def test_update_invalid_date(self) -> None: field_name = "Birthday" self.assert_error_update_invalid_value(field_name, u"a-b-c", u"{} is not a date".format(field_name)) self.assert_error_update_invalid_value(field_name, 123, u"{} is not a string".format(field_name)) def test_update_invalid_url(self) -> None: field_name = "GitHub profile" self.assert_error_update_invalid_value(field_name, u"not URL", u"{} is not a URL".format(field_name)) def test_update_invalid_user_field(self) -> None: field_name = "Mentor" invalid_user_id = 1000 self.assert_error_update_invalid_value(field_name, [invalid_user_id], u"Invalid user ID: %d" % (invalid_user_id)) def test_create_field_of_type_user(self) -> None: self.login(self.example_email("iago")) data = {"name": "Your mentor", "field_type": CustomProfileField.USER, } result = self.client_post("/json/realm/profile_fields", info=data) self.assert_json_success(result) def test_update_profile_data_successfully(self) -> None: self.login(self.example_email("iago")) realm = get_realm('zulip') fields = [ ('Phone number', 'short text data'), ('Biography', 'long text data'), ('Favorite food', 'short text data'), ('Favorite editor', 'vim'), ('Birthday', '1909-3-5'), ('GitHub profile', 'https://github.com/ABC'), ('Mentor', [self.example_user("cordelia").id]), ] data = [] for i, field_value in enumerate(fields): name, value = field_value field = CustomProfileField.objects.get(name=name, realm=realm) data.append({ 'id': field.id, 'value': value, }) # Update value of field result = self.client_patch("/json/users/me/profile_data", {'data': ujson.dumps(data)}) self.assert_json_success(result) iago = self.example_user('iago') expected_value = {f['id']: f['value'] for f in data} for field_dict in iago.profile_data: self.assertEqual(field_dict['value'], expected_value[field_dict['id']]) for k in ['id', 'type', 'name', 'field_data']: self.assertIn(k, field_dict) # Update value of one field. field = CustomProfileField.objects.get(name='Biography', realm=realm) data = [{ 'id': field.id, 'value': 'foobar', }] result = self.client_patch("/json/users/me/profile_data", {'data': ujson.dumps(data)}) self.assert_json_success(result) for f in iago.profile_data: if f['id'] == field.id: self.assertEqual(f['value'], 'foobar') def test_update_invalid_choice_field(self) -> None: field_name = "Favorite editor" self.assert_error_update_invalid_value(field_name, "foobar", "'foobar' is not a valid choice for '{}'.".format(field_name)) def test_update_choice_field_successfully(self) -> None: self.login(self.example_email("iago")) realm = get_realm('zulip') field = CustomProfileField.objects.get(name='Favorite editor', realm=realm) data = [{ 'id': field.id, 'value': 'emacs', }] result = self.client_patch("/json/users/me/profile_data", {'data': ujson.dumps(data)}) self.assert_json_success(result) def test_delete_internals(self) -> None: user_profile = self.example_user('iago') realm = user_profile.realm field = CustomProfileField.objects.get(name="Phone number", realm=realm) data = [{'id': field.id, 'value': u'123456'}] # type: List[Dict[str, Union[int, str, List[int]]]] do_update_user_custom_profile_data(user_profile, data) self.assertTrue(self.custom_field_exists_in_realm(field.id)) self.assertEqual(user_profile.customprofilefieldvalue_set.count(), self.original_count) do_remove_realm_custom_profile_field(realm, field) self.assertFalse(self.custom_field_exists_in_realm(field.id)) self.assertEqual(user_profile.customprofilefieldvalue_set.count(), self.original_count - 1)
[ "int", "str", "object", "str" ]
[ 729, 11832, 11848, 11867 ]
[ 732, 11835, 11854, 11870 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_decorators.py
# -*- coding: utf-8 -*- import base64 import mock import re import os from collections import defaultdict from typing import Any, Dict, Iterable, List, Optional, Tuple from django_otp.conf import settings as otp_settings from django.test import TestCase, override_settings from django.http import HttpResponse, HttpRequest from django.test.client import RequestFactory from django.conf import settings from zerver.forms import OurAuthenticationForm from zerver.lib.actions import do_deactivate_realm, do_deactivate_user, \ do_reactivate_user, do_reactivate_realm from zerver.lib.exceptions import JsonableError from zerver.lib.initial_password import initial_password from zerver.lib.test_helpers import ( HostRequestMock, ) from zerver.lib.test_classes import ( ZulipTestCase, WebhookTestCase, ) from zerver.lib.response import json_response from zerver.lib.users import get_api_key from zerver.lib.user_agent import parse_user_agent from zerver.lib.request import \ REQ, has_request_variables, RequestVariableMissingError, \ RequestVariableConversionError, RequestConfusingParmsError from zerver.decorator import ( api_key_only_webhook_view, authenticated_api_view, authenticated_rest_api_view, authenticate_notify, cachify, get_client_name, internal_notify_view, is_local_addr, rate_limit, validate_api_key, logged_in_and_active, return_success_on_head_request, to_not_negative_int_or_none, zulip_login_required ) from zerver.lib.cache import ignore_unhashable_lru_cache from zerver.lib.validator import ( check_string, check_dict, check_dict_only, check_bool, check_float, check_int, check_list, Validator, check_variable_type, equals, check_none_or, check_url, check_short_string, check_string_fixed_length, check_capped_string ) from zerver.models import \ get_realm, get_user, UserProfile, Client, Realm, Recipient import ujson class DecoratorTestCase(TestCase): def test_get_client_name(self) -> None: class Request: def __init__(self, GET: Dict[str, str], POST: Dict[str, str], META: Dict[str, str]) -> None: self.GET = GET self.POST = POST self.META = META req = Request( GET=dict(), POST=dict(), META=dict(), ) self.assertEqual(get_client_name(req, is_browser_view=True), 'website') self.assertEqual(get_client_name(req, is_browser_view=False), 'Unspecified') req = Request( GET=dict(), POST=dict(), META=dict(HTTP_USER_AGENT='Mozilla/bla bla bla'), ) self.assertEqual(get_client_name(req, is_browser_view=True), 'website') self.assertEqual(get_client_name(req, is_browser_view=False), 'Mozilla') req = Request( GET=dict(), POST=dict(), META=dict(HTTP_USER_AGENT='ZulipDesktop/bla bla bla'), ) self.assertEqual(get_client_name(req, is_browser_view=True), 'ZulipDesktop') self.assertEqual(get_client_name(req, is_browser_view=False), 'ZulipDesktop') req = Request( GET=dict(), POST=dict(), META=dict(HTTP_USER_AGENT='ZulipMobile/bla bla bla'), ) self.assertEqual(get_client_name(req, is_browser_view=True), 'ZulipMobile') self.assertEqual(get_client_name(req, is_browser_view=False), 'ZulipMobile') req = Request( GET=dict(client='fancy phone'), POST=dict(), META=dict(), ) self.assertEqual(get_client_name(req, is_browser_view=True), 'fancy phone') self.assertEqual(get_client_name(req, is_browser_view=False), 'fancy phone') def test_REQ_aliases(self) -> None: @has_request_variables def double(request: HttpRequest, x: int=REQ(whence='number', aliases=['x', 'n'], converter=int)) -> int: return x + x class Request: GET = {} # type: Dict[str, str] POST = {} # type: Dict[str, str] request = Request() request.POST = dict(bogus='5555') with self.assertRaises(RequestVariableMissingError): double(request) request.POST = dict(number='3') self.assertEqual(double(request), 6) request.POST = dict(x='4') self.assertEqual(double(request), 8) request.POST = dict(n='5') self.assertEqual(double(request), 10) request.POST = dict(number='6', x='7') with self.assertRaises(RequestConfusingParmsError) as cm: double(request) self.assertEqual(str(cm.exception), "Can't decide between 'number' and 'x' arguments") def test_REQ_converter(self) -> None: def my_converter(data: str) -> List[int]: lst = ujson.loads(data) if not isinstance(lst, list): raise ValueError('not a list') if 13 in lst: raise JsonableError('13 is an unlucky number!') return [int(elem) for elem in lst] @has_request_variables def get_total(request: HttpRequest, numbers: Iterable[int]=REQ(converter=my_converter)) -> int: return sum(numbers) class Request: GET = {} # type: Dict[str, str] POST = {} # type: Dict[str, str] request = Request() with self.assertRaises(RequestVariableMissingError): get_total(request) request.POST['numbers'] = 'bad_value' with self.assertRaises(RequestVariableConversionError) as cm: get_total(request) self.assertEqual(str(cm.exception), "Bad value for 'numbers': bad_value") request.POST['numbers'] = ujson.dumps('{fun: unfun}') with self.assertRaises(JsonableError) as cm: get_total(request) self.assertEqual(str(cm.exception), 'Bad value for \'numbers\': "{fun: unfun}"') request.POST['numbers'] = ujson.dumps([2, 3, 5, 8, 13, 21]) with self.assertRaises(JsonableError) as cm: get_total(request) self.assertEqual(str(cm.exception), "13 is an unlucky number!") request.POST['numbers'] = ujson.dumps([1, 2, 3, 4, 5, 6]) result = get_total(request) self.assertEqual(result, 21) def test_REQ_converter_and_validator_invalid(self) -> None: with self.assertRaisesRegex(AssertionError, "converter and validator are mutually exclusive"): @has_request_variables def get_total(request: HttpRequest, numbers: Iterable[int]=REQ(validator=check_list(check_int), converter=lambda x: [])) -> int: return sum(numbers) # nocoverage -- isn't intended to be run def test_REQ_validator(self) -> None: @has_request_variables def get_total(request: HttpRequest, numbers: Iterable[int]=REQ(validator=check_list(check_int))) -> int: return sum(numbers) class Request: GET = {} # type: Dict[str, str] POST = {} # type: Dict[str, str] request = Request() with self.assertRaises(RequestVariableMissingError): get_total(request) request.POST['numbers'] = 'bad_value' with self.assertRaises(JsonableError) as cm: get_total(request) self.assertEqual(str(cm.exception), 'Argument "numbers" is not valid JSON.') request.POST['numbers'] = ujson.dumps([1, 2, "what?", 4, 5, 6]) with self.assertRaises(JsonableError) as cm: get_total(request) self.assertEqual(str(cm.exception), 'numbers[2] is not an integer') request.POST['numbers'] = ujson.dumps([1, 2, 3, 4, 5, 6]) result = get_total(request) self.assertEqual(result, 21) def test_REQ_str_validator(self) -> None: @has_request_variables def get_middle_characters(request: HttpRequest, value: str=REQ(str_validator=check_string_fixed_length(5))) -> str: return value[1:-1] class Request: GET = {} # type: Dict[str, str] POST = {} # type: Dict[str, str] request = Request() with self.assertRaises(RequestVariableMissingError): get_middle_characters(request) request.POST['value'] = 'long_value' with self.assertRaises(JsonableError) as cm: get_middle_characters(request) self.assertEqual(str(cm.exception), 'value has incorrect length 10; should be 5') request.POST['value'] = 'valid' result = get_middle_characters(request) self.assertEqual(result, 'ali') def test_REQ_argument_type(self) -> None: @has_request_variables def get_payload(request: HttpRequest, payload: Dict[str, Any]=REQ(argument_type='body')) -> Dict[str, Any]: return payload class MockRequest: body = {} # type: Any request = MockRequest() request.body = 'notjson' with self.assertRaises(JsonableError) as cm: get_payload(request) self.assertEqual(str(cm.exception), 'Malformed JSON') request.body = '{"a": "b"}' self.assertEqual(get_payload(request), {'a': 'b'}) # Test we properly handle an invalid argument_type. with self.assertRaises(Exception) as cm: @has_request_variables def test(request: HttpRequest, payload: Any=REQ(argument_type="invalid")) -> None: # Any is ok; exception should occur in decorator: pass # nocoverage # this function isn't meant to be called test(request) def test_api_key_only_webhook_view(self) -> None: @api_key_only_webhook_view('ClientName') def my_webhook(request: HttpRequest, user_profile: UserProfile) -> str: return user_profile.email @api_key_only_webhook_view('ClientName') def my_webhook_raises_exception(request: HttpRequest, user_profile: UserProfile) -> None: raise Exception("raised by webhook function") webhook_bot_email = 'webhook-bot@zulip.com' webhook_bot_realm = get_realm('zulip') webhook_bot = get_user(webhook_bot_email, webhook_bot_realm) webhook_bot_api_key = get_api_key(webhook_bot) webhook_client_name = "ZulipClientNameWebhook" request = HostRequestMock() request.POST['api_key'] = 'not_existing_api_key' with self.assertRaisesRegex(JsonableError, "Invalid API key"): my_webhook(request) # type: ignore # mypy doesn't seem to apply the decorator # Start a valid request here request.POST['api_key'] = webhook_bot_api_key with mock.patch('logging.warning') as mock_warning: with self.assertRaisesRegex(JsonableError, "Account is not associated with this subdomain"): api_result = my_webhook(request) # type: ignore # mypy doesn't seem to apply the decorator mock_warning.assert_called_with( "User {} ({}) attempted to access API on wrong " "subdomain ({})".format(webhook_bot_email, 'zulip', '')) with mock.patch('logging.warning') as mock_warning: with self.assertRaisesRegex(JsonableError, "Account is not associated with this subdomain"): request.host = "acme." + settings.EXTERNAL_HOST api_result = my_webhook(request) # type: ignore # mypy doesn't seem to apply the decorator mock_warning.assert_called_with( "User {} ({}) attempted to access API on wrong " "subdomain ({})".format(webhook_bot_email, 'zulip', 'acme')) request.host = "zulip.testserver" # Test when content_type is application/json and request.body # is valid JSON; exception raised in the webhook function # should be re-raised with mock.patch('zerver.decorator.webhook_logger.exception') as mock_exception: with self.assertRaisesRegex(Exception, "raised by webhook function"): request.body = "{}" request.content_type = 'application/json' my_webhook_raises_exception(request) # type: ignore # mypy doesn't seem to apply the decorator # Test when content_type is not application/json; exception raised # in the webhook function should be re-raised with mock.patch('zerver.decorator.webhook_logger.exception') as mock_exception: with self.assertRaisesRegex(Exception, "raised by webhook function"): request.body = "notjson" request.content_type = 'text/plain' my_webhook_raises_exception(request) # type: ignore # mypy doesn't seem to apply the decorator # Test when content_type is application/json but request.body # is not valid JSON; invalid JSON should be logged and the # exception raised in the webhook function should be re-raised with mock.patch('zerver.decorator.webhook_logger.exception') as mock_exception: with self.assertRaisesRegex(Exception, "raised by webhook function"): request.body = "invalidjson" request.content_type = 'application/json' request.META['HTTP_X_CUSTOM_HEADER'] = 'custom_value' my_webhook_raises_exception(request) # type: ignore # mypy doesn't seem to apply the decorator message = """ user: {email} ({realm}) client: {client_name} URL: {path_info} content_type: {content_type} custom_http_headers: {custom_headers} body: {body} """ message = message.strip(' ') mock_exception.assert_called_with(message.format( email=webhook_bot_email, realm=webhook_bot_realm.string_id, client_name=webhook_client_name, path_info=request.META.get('PATH_INFO'), content_type=request.content_type, custom_headers="HTTP_X_CUSTOM_HEADER: custom_value\n", body=request.body, )) with self.settings(RATE_LIMITING=True): with mock.patch('zerver.decorator.rate_limit_user') as rate_limit_mock: api_result = my_webhook(request) # type: ignore # mypy doesn't seem to apply the decorator # Verify rate limiting was attempted. self.assertTrue(rate_limit_mock.called) # Verify decorator set the magic _email field used by some of our back end logging. self.assertEqual(request._email, webhook_bot_email) # Verify the main purpose of the decorator, which is that it passed in the # user_profile to my_webhook, allowing it return the correct # email for the bot (despite the API caller only knowing the API key). self.assertEqual(api_result, webhook_bot_email) # Now deactivate the user webhook_bot.is_active = False webhook_bot.save() with self.assertRaisesRegex(JsonableError, "Account is deactivated"): my_webhook(request) # type: ignore # mypy doesn't seem to apply the decorator # Reactive the user, but deactivate their realm. webhook_bot.is_active = True webhook_bot.save() webhook_bot.realm.deactivated = True webhook_bot.realm.save() with self.assertRaisesRegex(JsonableError, "This organization has been deactivated"): my_webhook(request) # type: ignore # mypy doesn't seem to apply the decorator class DecoratorLoggingTestCase(ZulipTestCase): def test_authenticated_api_view_logging(self) -> None: @authenticated_api_view(is_webhook=True) def my_webhook_raises_exception(request: HttpRequest, user_profile: UserProfile) -> None: raise Exception("raised by webhook function") webhook_bot_email = 'webhook-bot@zulip.com' webhook_bot_realm = get_realm('zulip') webhook_bot = get_user(webhook_bot_email, webhook_bot_realm) webhook_bot_api_key = get_api_key(webhook_bot) request = HostRequestMock() request.method = 'POST' request.POST['api_key'] = webhook_bot_api_key request.POST['email'] = webhook_bot_email request.host = "zulip.testserver" with mock.patch('zerver.decorator.webhook_logger.exception') as mock_exception: with self.assertRaisesRegex(Exception, "raised by webhook function"): request.body = '{}' request.POST['payload'] = '{}' request.content_type = 'text/plain' my_webhook_raises_exception(request) # type: ignore # mypy doesn't seem to apply the decorator message = """ user: {email} ({realm}) client: {client_name} URL: {path_info} content_type: {content_type} custom_http_headers: {custom_headers} body: {body} """ message = message.strip(' ') mock_exception.assert_called_with(message.format( email=webhook_bot_email, realm=webhook_bot_realm.string_id, client_name='Unspecified', path_info=request.META.get('PATH_INFO'), content_type=request.content_type, custom_headers=None, body=request.body, )) def test_authenticated_rest_api_view_logging(self) -> None: @authenticated_rest_api_view(webhook_client_name="ClientName") def my_webhook_raises_exception(request: HttpRequest, user_profile: UserProfile) -> None: raise Exception("raised by webhook function") webhook_bot_email = 'webhook-bot@zulip.com' webhook_bot_realm = get_realm('zulip') request = HostRequestMock() request.META['HTTP_AUTHORIZATION'] = self.encode_credentials(webhook_bot_email) request.method = 'POST' request.host = "zulip.testserver" request.body = '{}' request.POST['payload'] = '{}' request.content_type = 'text/plain' with mock.patch('zerver.decorator.webhook_logger.exception') as mock_exception: with self.assertRaisesRegex(Exception, "raised by webhook function"): my_webhook_raises_exception(request) # type: ignore # mypy doesn't seem to apply the decorator message = """ user: {email} ({realm}) client: {client_name} URL: {path_info} content_type: {content_type} custom_http_headers: {custom_headers} body: {body} """ message = message.strip(' ') mock_exception.assert_called_with(message.format( email=webhook_bot_email, realm=webhook_bot_realm.string_id, client_name='ZulipClientNameWebhook', path_info=request.META.get('PATH_INFO'), content_type=request.content_type, custom_headers=None, body=request.body, )) def test_authenticated_rest_api_view_with_non_webhook_view(self) -> None: @authenticated_rest_api_view() def non_webhook_view_raises_exception(request: HttpRequest, user_profile: UserProfile=None) -> None: raise Exception("raised by a non-webhook view") request = HostRequestMock() request.META['HTTP_AUTHORIZATION'] = self.encode_credentials("aaron@zulip.com") request.method = 'POST' request.host = "zulip.testserver" request.body = '{}' request.content_type = 'application/json' with mock.patch('zerver.decorator.webhook_logger.exception') as mock_exception: with self.assertRaisesRegex(Exception, "raised by a non-webhook view"): non_webhook_view_raises_exception(request) self.assertFalse(mock_exception.called) def test_authenticated_rest_api_view_errors(self) -> None: user_profile = self.example_user("hamlet") api_key = get_api_key(user_profile) credentials = "%s:%s" % (user_profile.email, api_key) api_auth = 'Digest ' + base64.b64encode(credentials.encode('utf-8')).decode('utf-8') result = self.client_post('/api/v1/external/zendesk', {}, HTTP_AUTHORIZATION=api_auth) self.assert_json_error(result, "This endpoint requires HTTP basic authentication.") api_auth = 'Basic ' + base64.b64encode("foo".encode('utf-8')).decode('utf-8') result = self.client_post('/api/v1/external/zendesk', {}, HTTP_AUTHORIZATION=api_auth) self.assert_json_error(result, "Invalid authorization header for basic auth", status_code=401) result = self.client_post('/api/v1/external/zendesk', {}) self.assert_json_error(result, "Missing authorization header for basic auth", status_code=401) class RateLimitTestCase(TestCase): def errors_disallowed(self) -> Any: # Due to what is probably a hack in rate_limit(), # some tests will give a false positive (or succeed # for the wrong reason), unless we complain # about logging errors. There might be a more elegant way # make logging errors fail than what I'm doing here. class TestLoggingErrorException(Exception): pass return mock.patch('logging.error', side_effect=TestLoggingErrorException) def test_internal_local_clients_skip_rate_limiting(self) -> None: class Client: name = 'internal' class Request: client = Client() META = {'REMOTE_ADDR': '127.0.0.1'} req = Request() def f(req: Any) -> str: return 'some value' f = rate_limit()(f) with self.settings(RATE_LIMITING=True): with mock.patch('zerver.decorator.rate_limit_user') as rate_limit_mock: with self.errors_disallowed(): self.assertEqual(f(req), 'some value') self.assertFalse(rate_limit_mock.called) def test_debug_clients_skip_rate_limiting(self) -> None: class Client: name = 'internal' class Request: client = Client() META = {'REMOTE_ADDR': '3.3.3.3'} req = Request() def f(req: Any) -> str: return 'some value' f = rate_limit()(f) with self.settings(RATE_LIMITING=True): with mock.patch('zerver.decorator.rate_limit_user') as rate_limit_mock: with self.errors_disallowed(): with self.settings(DEBUG_RATE_LIMITING=True): self.assertEqual(f(req), 'some value') self.assertFalse(rate_limit_mock.called) def test_rate_limit_setting_of_false_bypasses_rate_limiting(self) -> None: class Client: name = 'external' class Request: client = Client() META = {'REMOTE_ADDR': '3.3.3.3'} user = 'stub' # any non-None value here exercises the correct code path req = Request() def f(req: Any) -> str: return 'some value' f = rate_limit()(f) with self.settings(RATE_LIMITING=False): with mock.patch('zerver.decorator.rate_limit_user') as rate_limit_mock: with self.errors_disallowed(): self.assertEqual(f(req), 'some value') self.assertFalse(rate_limit_mock.called) def test_rate_limiting_happens_in_normal_case(self) -> None: class Client: name = 'external' class Request: client = Client() META = {'REMOTE_ADDR': '3.3.3.3'} user = 'stub' # any non-None value here exercises the correct code path req = Request() def f(req: Any) -> str: return 'some value' f = rate_limit()(f) with self.settings(RATE_LIMITING=True): with mock.patch('zerver.decorator.rate_limit_user') as rate_limit_mock: with self.errors_disallowed(): self.assertEqual(f(req), 'some value') self.assertTrue(rate_limit_mock.called) class ValidatorTestCase(TestCase): def test_check_string(self) -> None: x = "hello" # type: Any self.assertEqual(check_string('x', x), None) x = 4 self.assertEqual(check_string('x', x), 'x is not a string') def test_check_string_fixed_length(self) -> None: x = "hello" # type: Any self.assertEqual(check_string_fixed_length(5)('x', x), None) x = 4 self.assertEqual(check_string_fixed_length(5)('x', x), 'x is not a string') x = "helloz" self.assertEqual(check_string_fixed_length(5)('x', x), 'x has incorrect length 6; should be 5') x = "hi" self.assertEqual(check_string_fixed_length(5)('x', x), 'x has incorrect length 2; should be 5') def test_check_capped_string(self) -> None: x = "hello" # type: Any self.assertEqual(check_capped_string(5)('x', x), None) x = 4 self.assertEqual(check_capped_string(5)('x', x), 'x is not a string') x = "helloz" self.assertEqual(check_capped_string(5)('x', x), 'x is too long (limit: 5 characters)') x = "hi" self.assertEqual(check_capped_string(5)('x', x), None) def test_check_short_string(self) -> None: x = "hello" # type: Any self.assertEqual(check_short_string('x', x), None) x = 'x' * 201 self.assertEqual(check_short_string('x', x), "x is too long (limit: 50 characters)") x = 4 self.assertEqual(check_short_string('x', x), 'x is not a string') def test_check_bool(self) -> None: x = True # type: Any self.assertEqual(check_bool('x', x), None) x = 4 self.assertEqual(check_bool('x', x), 'x is not a boolean') def test_check_int(self) -> None: x = 5 # type: Any self.assertEqual(check_int('x', x), None) x = [{}] self.assertEqual(check_int('x', x), 'x is not an integer') def test_check_to_not_negative_int_or_none(self) -> None: self.assertEqual(to_not_negative_int_or_none('5'), 5) self.assertEqual(to_not_negative_int_or_none(None), None) with self.assertRaises(ValueError): to_not_negative_int_or_none('-5') def test_check_float(self) -> None: x = 5.5 # type: Any self.assertEqual(check_float('x', x), None) x = 5 self.assertEqual(check_float('x', x), 'x is not a float') x = [{}] self.assertEqual(check_float('x', x), 'x is not a float') def test_check_list(self) -> None: x = 999 # type: Any error = check_list(check_string)('x', x) self.assertEqual(error, 'x is not a list') x = ["hello", 5] error = check_list(check_string)('x', x) self.assertEqual(error, 'x[1] is not a string') x = [["yo"], ["hello", "goodbye", 5]] error = check_list(check_list(check_string))('x', x) self.assertEqual(error, 'x[1][2] is not a string') x = ["hello", "goodbye", "hello again"] error = check_list(check_string, length=2)('x', x) self.assertEqual(error, 'x should have exactly 2 items') def test_check_dict(self) -> None: keys = [ ('names', check_list(check_string)), ('city', check_string), ] # type: List[Tuple[str, Validator]] x = { 'names': ['alice', 'bob'], 'city': 'Boston', } # type: Any error = check_dict(keys)('x', x) self.assertEqual(error, None) x = 999 error = check_dict(keys)('x', x) self.assertEqual(error, 'x is not a dict') x = {} error = check_dict(keys)('x', x) self.assertEqual(error, 'names key is missing from x') x = { 'names': ['alice', 'bob', {}] } error = check_dict(keys)('x', x) self.assertEqual(error, 'x["names"][2] is not a string') x = { 'names': ['alice', 'bob'], 'city': 5 } error = check_dict(keys)('x', x) self.assertEqual(error, 'x["city"] is not a string') x = { 'names': ['alice', 'bob'], 'city': 'Boston' } error = check_dict(value_validator=check_string)('x', x) self.assertEqual(error, 'x contains a value that is not a string') x = { 'city': 'Boston' } error = check_dict(value_validator=check_string)('x', x) self.assertEqual(error, None) # test dict_only x = { 'names': ['alice', 'bob'], 'city': 'Boston', } error = check_dict_only(keys)('x', x) self.assertEqual(error, None) x = { 'names': ['alice', 'bob'], 'city': 'Boston', 'state': 'Massachusetts', } error = check_dict_only(keys)('x', x) self.assertEqual(error, 'Unexpected arguments: state') def test_encapsulation(self) -> None: # There might be situations where we want deep # validation, but the error message should be customized. # This is an example. def check_person(val: Any) -> Optional[str]: error = check_dict([ ('name', check_string), ('age', check_int), ])('_', val) if error: return 'This is not a valid person' return None person = {'name': 'King Lear', 'age': 42} self.assertEqual(check_person(person), None) nonperson = 'misconfigured data' self.assertEqual(check_person(nonperson), 'This is not a valid person') def test_check_variable_type(self) -> None: x = 5 # type: Any self.assertEqual(check_variable_type([check_string, check_int])('x', x), None) x = 'x' self.assertEqual(check_variable_type([check_string, check_int])('x', x), None) x = [{}] self.assertEqual(check_variable_type([check_string, check_int])('x', x), 'x is not an allowed_type') def test_equals(self) -> None: x = 5 # type: Any self.assertEqual(equals(5)('x', x), None) self.assertEqual(equals(6)('x', x), 'x != 6 (5 is wrong)') def test_check_none_or(self) -> None: x = 5 # type: Any self.assertEqual(check_none_or(check_int)('x', x), None) x = None self.assertEqual(check_none_or(check_int)('x', x), None) x = 'x' self.assertEqual(check_none_or(check_int)('x', x), 'x is not an integer') def test_check_url(self) -> None: url = "http://127.0.0.1:5002/" # type: Any self.assertEqual(check_url('url', url), None) url = "http://zulip-bots.example.com/" self.assertEqual(check_url('url', url), None) url = "http://127.0.0" self.assertEqual(check_url('url', url), 'url is not a URL') url = 99.3 self.assertEqual(check_url('url', url), 'url is not a string') class DeactivatedRealmTest(ZulipTestCase): def test_send_deactivated_realm(self) -> None: """ rest_dispatch rejects requests in a deactivated realm, both /json and api """ realm = get_realm("zulip") do_deactivate_realm(get_realm("zulip")) result = self.client_post("/json/messages", {"type": "private", "content": "Test message", "client": "test suite", "to": self.example_email("othello")}) self.assert_json_error_contains(result, "Not logged in", status_code=401) # Even if a logged-in session was leaked, it still wouldn't work realm.deactivated = False realm.save() self.login(self.example_email("hamlet")) realm.deactivated = True realm.save() result = self.client_post("/json/messages", {"type": "private", "content": "Test message", "client": "test suite", "to": self.example_email("othello")}) self.assert_json_error_contains(result, "has been deactivated", status_code=400) result = self.api_post(self.example_email("hamlet"), "/api/v1/messages", {"type": "private", "content": "Test message", "client": "test suite", "to": self.example_email("othello")}) self.assert_json_error_contains(result, "has been deactivated", status_code=401) def test_fetch_api_key_deactivated_realm(self) -> None: """ authenticated_json_view views fail in a deactivated realm """ realm = get_realm("zulip") user_profile = self.example_user('hamlet') email = user_profile.email test_password = "abcd1234" user_profile.set_password(test_password) self.login(email) realm.deactivated = True realm.save() result = self.client_post("/json/fetch_api_key", {"password": test_password}) self.assert_json_error_contains(result, "has been deactivated", status_code=400) def test_webhook_deactivated_realm(self) -> None: """ Using a webhook while in a deactivated realm fails """ do_deactivate_realm(get_realm("zulip")) user_profile = self.example_user("hamlet") api_key = get_api_key(user_profile) url = "/api/v1/external/jira?api_key=%s&stream=jira_custom" % (api_key,) data = self.webhook_fixture_data('jira', 'created_v2') result = self.client_post(url, data, content_type="application/json") self.assert_json_error_contains(result, "has been deactivated", status_code=400) class LoginRequiredTest(ZulipTestCase): def test_login_required(self) -> None: """ Verifies the zulip_login_required decorator blocks deactivated users. """ user_profile = self.example_user('hamlet') email = user_profile.email # Verify fails if logged-out result = self.client_get('/accounts/accept_terms/') self.assertEqual(result.status_code, 302) # Verify succeeds once logged-in self.login(email) result = self.client_get('/accounts/accept_terms/') self.assert_in_response("I agree to the", result) # Verify fails if user deactivated (with session still valid) user_profile.is_active = False user_profile.save() result = self.client_get('/accounts/accept_terms/') self.assertEqual(result.status_code, 302) # Verify succeeds if user reactivated do_reactivate_user(user_profile) self.login(email) result = self.client_get('/accounts/accept_terms/') self.assert_in_response("I agree to the", result) # Verify fails if realm deactivated user_profile.realm.deactivated = True user_profile.realm.save() result = self.client_get('/accounts/accept_terms/') self.assertEqual(result.status_code, 302) class FetchAPIKeyTest(ZulipTestCase): def test_fetch_api_key_success(self) -> None: email = self.example_email("cordelia") self.login(email) result = self.client_post("/json/fetch_api_key", {"password": initial_password(email)}) self.assert_json_success(result) def test_fetch_api_key_wrong_password(self) -> None: email = self.example_email("cordelia") self.login(email) result = self.client_post("/json/fetch_api_key", {"password": "wrong_password"}) self.assert_json_error_contains(result, "password is incorrect") class InactiveUserTest(ZulipTestCase): def test_send_deactivated_user(self) -> None: """ rest_dispatch rejects requests from deactivated users, both /json and api """ user_profile = self.example_user('hamlet') email = user_profile.email self.login(email) do_deactivate_user(user_profile) result = self.client_post("/json/messages", {"type": "private", "content": "Test message", "client": "test suite", "to": self.example_email("othello")}) self.assert_json_error_contains(result, "Not logged in", status_code=401) # Even if a logged-in session was leaked, it still wouldn't work do_reactivate_user(user_profile) self.login(email) user_profile.is_active = False user_profile.save() result = self.client_post("/json/messages", {"type": "private", "content": "Test message", "client": "test suite", "to": self.example_email("othello")}) self.assert_json_error_contains(result, "Account is deactivated", status_code=400) result = self.api_post(self.example_email("hamlet"), "/api/v1/messages", {"type": "private", "content": "Test message", "client": "test suite", "to": self.example_email("othello")}) self.assert_json_error_contains(result, "Account is deactivated", status_code=401) def test_fetch_api_key_deactivated_user(self) -> None: """ authenticated_json_view views fail with a deactivated user """ user_profile = self.example_user('hamlet') email = user_profile.email test_password = "abcd1234" user_profile.set_password(test_password) user_profile.save() self.login(email, password=test_password) user_profile.is_active = False user_profile.save() result = self.client_post("/json/fetch_api_key", {"password": test_password}) self.assert_json_error_contains(result, "Account is deactivated", status_code=400) def test_login_deactivated_user(self) -> None: """ logging in fails with an inactive user """ user_profile = self.example_user('hamlet') do_deactivate_user(user_profile) result = self.login_with_return(self.example_email("hamlet")) self.assert_in_response( "Your account is no longer active.", result) def test_login_deactivated_mirror_dummy(self) -> None: """ logging in fails with an inactive user """ user_profile = self.example_user('hamlet') user_profile.is_mirror_dummy = True user_profile.save() password = initial_password(user_profile.email) request = mock.MagicMock() request.get_host.return_value = 'zulip.testserver' # Test a mirror-dummy active user. form = OurAuthenticationForm(request, data={'username': user_profile.email, 'password': password}) with self.settings(AUTHENTICATION_BACKENDS=('zproject.backends.EmailAuthBackend',)): self.assertTrue(form.is_valid()) # Test a mirror-dummy deactivated user. do_deactivate_user(user_profile) user_profile.save() form = OurAuthenticationForm(request, data={'username': user_profile.email, 'password': password}) with self.settings(AUTHENTICATION_BACKENDS=('zproject.backends.EmailAuthBackend',)): self.assertFalse(form.is_valid()) self.assertIn("Please enter a correct email", str(form.errors)) # Test a non-mirror-dummy deactivated user. user_profile.is_mirror_dummy = False user_profile.save() form = OurAuthenticationForm(request, data={'username': user_profile.email, 'password': password}) with self.settings(AUTHENTICATION_BACKENDS=('zproject.backends.EmailAuthBackend',)): self.assertFalse(form.is_valid()) self.assertIn("Your account is no longer active", str(form.errors)) def test_webhook_deactivated_user(self) -> None: """ Deactivated users can't use webhooks """ user_profile = self.example_user('hamlet') do_deactivate_user(user_profile) api_key = get_api_key(user_profile) url = "/api/v1/external/jira?api_key=%s&stream=jira_custom" % (api_key,) data = self.webhook_fixture_data('jira', 'created_v2') result = self.client_post(url, data, content_type="application/json") self.assert_json_error_contains(result, "Account is deactivated", status_code=400) class TestIncomingWebhookBot(ZulipTestCase): def setUp(self) -> None: zulip_realm = get_realm('zulip') self.webhook_bot = get_user('webhook-bot@zulip.com', zulip_realm) def test_webhook_bot_permissions(self) -> None: result = self.api_post("webhook-bot@zulip.com", "/api/v1/messages", {"type": "private", "content": "Test message", "client": "test suite", "to": self.example_email("othello")}) self.assert_json_success(result) post_params = {"anchor": 1, "num_before": 1, "num_after": 1} result = self.api_get("webhook-bot@zulip.com", "/api/v1/messages", dict(post_params)) self.assert_json_error(result, 'This API is not available to incoming webhook bots.', status_code=401) class TestValidateApiKey(ZulipTestCase): def setUp(self) -> None: zulip_realm = get_realm('zulip') self.webhook_bot = get_user('webhook-bot@zulip.com', zulip_realm) self.default_bot = get_user('default-bot@zulip.com', zulip_realm) def test_validate_api_key_if_profile_does_not_exist(self) -> None: with self.assertRaises(JsonableError): validate_api_key(HostRequestMock(), 'email@doesnotexist.com', 'api_key') def test_validate_api_key_if_api_key_does_not_match_profile_api_key(self) -> None: with self.assertRaises(JsonableError): validate_api_key(HostRequestMock(), self.webhook_bot.email, 'not_32_length') with self.assertRaises(JsonableError): # We use default_bot's key but webhook_bot's email address to test # the logic when an API key is passed and it doesn't belong to the # user whose email address has been provided. api_key = get_api_key(self.default_bot) validate_api_key(HostRequestMock(), self.webhook_bot.email, api_key) def test_validate_api_key_if_profile_is_not_active(self) -> None: self._change_is_active_field(self.default_bot, False) with self.assertRaises(JsonableError): api_key = get_api_key(self.default_bot) validate_api_key(HostRequestMock(), self.default_bot.email, api_key) self._change_is_active_field(self.default_bot, True) def test_validate_api_key_if_profile_is_incoming_webhook_and_is_webhook_is_unset(self) -> None: with self.assertRaises(JsonableError): api_key = get_api_key(self.webhook_bot) validate_api_key(HostRequestMock(), self.webhook_bot.email, api_key) def test_validate_api_key_if_profile_is_incoming_webhook_and_is_webhook_is_set(self) -> None: api_key = get_api_key(self.webhook_bot) profile = validate_api_key(HostRequestMock(host="zulip.testserver"), self.webhook_bot.email, api_key, is_webhook=True) self.assertEqual(profile.id, self.webhook_bot.id) def test_validate_api_key_if_email_is_case_insensitive(self) -> None: api_key = get_api_key(self.default_bot) profile = validate_api_key(HostRequestMock(host="zulip.testserver"), self.default_bot.email.upper(), api_key) self.assertEqual(profile.id, self.default_bot.id) def test_valid_api_key_if_user_is_on_wrong_subdomain(self) -> None: with self.settings(RUNNING_INSIDE_TORNADO=False): api_key = get_api_key(self.default_bot) with mock.patch('logging.warning') as mock_warning: with self.assertRaisesRegex(JsonableError, "Account is not associated with this subdomain"): validate_api_key(HostRequestMock(host=settings.EXTERNAL_HOST), self.default_bot.email, api_key) mock_warning.assert_called_with( "User {} ({}) attempted to access API on wrong " "subdomain ({})".format(self.default_bot.email, 'zulip', '')) with mock.patch('logging.warning') as mock_warning: with self.assertRaisesRegex(JsonableError, "Account is not associated with this subdomain"): validate_api_key(HostRequestMock(host='acme.' + settings.EXTERNAL_HOST), self.default_bot.email, api_key) mock_warning.assert_called_with( "User {} ({}) attempted to access API on wrong " "subdomain ({})".format(self.default_bot.email, 'zulip', 'acme')) def _change_is_active_field(self, profile: UserProfile, value: bool) -> None: profile.is_active = value profile.save() class TestInternalNotifyView(TestCase): BORING_RESULT = 'boring' class Request: def __init__(self, POST: Dict[str, Any], META: Dict[str, Any]) -> None: self.POST = POST self.META = META self.method = 'POST' def internal_notify(self, is_tornado: bool, req: HttpRequest) -> HttpResponse: boring_view = lambda req: self.BORING_RESULT return internal_notify_view(is_tornado)(boring_view)(req) def test_valid_internal_requests(self) -> None: secret = 'random' req = self.Request( POST=dict(secret=secret), META=dict(REMOTE_ADDR='127.0.0.1'), ) # type: HttpRequest with self.settings(SHARED_SECRET=secret): self.assertTrue(authenticate_notify(req)) self.assertEqual(self.internal_notify(False, req), self.BORING_RESULT) self.assertEqual(req._email, 'internal') with self.assertRaises(RuntimeError): self.internal_notify(True, req) req._tornado_handler = 'set' with self.settings(SHARED_SECRET=secret): self.assertTrue(authenticate_notify(req)) self.assertEqual(self.internal_notify(True, req), self.BORING_RESULT) self.assertEqual(req._email, 'internal') with self.assertRaises(RuntimeError): self.internal_notify(False, req) def test_internal_requests_with_broken_secret(self) -> None: secret = 'random' req = self.Request( POST=dict(secret=secret), META=dict(REMOTE_ADDR='127.0.0.1'), ) with self.settings(SHARED_SECRET='broken'): self.assertFalse(authenticate_notify(req)) self.assertEqual(self.internal_notify(True, req).status_code, 403) def test_external_requests(self) -> None: secret = 'random' req = self.Request( POST=dict(secret=secret), META=dict(REMOTE_ADDR='3.3.3.3'), ) with self.settings(SHARED_SECRET=secret): self.assertFalse(authenticate_notify(req)) self.assertEqual(self.internal_notify(True, req).status_code, 403) def test_is_local_address(self) -> None: self.assertTrue(is_local_addr('127.0.0.1')) self.assertTrue(is_local_addr('::1')) self.assertFalse(is_local_addr('42.43.44.45')) class TestHumanUsersOnlyDecorator(ZulipTestCase): def test_human_only_endpoints(self) -> None: post_endpoints = [ "/api/v1/users/me/apns_device_token", "/api/v1/users/me/android_gcm_reg_id", "/api/v1/users/me/enter-sends", "/api/v1/users/me/hotspots", "/api/v1/users/me/presence", "/api/v1/users/me/tutorial_status", "/api/v1/report/error", "/api/v1/report/send_times", "/api/v1/report/narrow_times", "/api/v1/report/unnarrow_times", ] for endpoint in post_endpoints: result = self.api_post('default-bot@zulip.com', endpoint) self.assert_json_error(result, "This endpoint does not accept bot requests.") patch_endpoints = [ "/api/v1/settings", "/api/v1/settings/display", "/api/v1/settings/notifications", "/api/v1/users/me/profile_data" ] for endpoint in patch_endpoints: result = self.api_patch('default-bot@zulip.com', endpoint) self.assert_json_error(result, "This endpoint does not accept bot requests.") delete_endpoints = [ "/api/v1/users/me/apns_device_token", "/api/v1/users/me/android_gcm_reg_id", ] for endpoint in delete_endpoints: result = self.api_delete('default-bot@zulip.com', endpoint) self.assert_json_error(result, "This endpoint does not accept bot requests.") class TestAuthenticatedJsonPostViewDecorator(ZulipTestCase): def test_authenticated_json_post_view_if_everything_is_correct(self) -> None: user_email = self.example_email('hamlet') user_realm = get_realm('zulip') self._login(user_email, user_realm) response = self._do_test(user_email) self.assertEqual(response.status_code, 200) def test_authenticated_json_post_view_with_get_request(self) -> None: user_email = self.example_email('hamlet') user_realm = get_realm('zulip') self._login(user_email, user_realm) with mock.patch('logging.warning') as mock_warning: result = self.client_get(r'/json/subscriptions/exists', {'stream': 'Verona'}) self.assertEqual(result.status_code, 405) mock_warning.assert_called_once() # Check we logged the Mock Not Allowed 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: user_email = self.example_email('hamlet') user_realm = get_realm('zulip') self._login(user_email, user_realm) with mock.patch('logging.warning') as mock_warning, \ mock.patch('zerver.decorator.get_subdomain', return_value=''): self.assert_json_error_contains(self._do_test(user_email), "Account is not associated with this " "subdomain") mock_warning.assert_called_with( "User {} ({}) attempted to access API on wrong " "subdomain ({})".format(user_email, 'zulip', '')) with mock.patch('logging.warning') as mock_warning, \ mock.patch('zerver.decorator.get_subdomain', return_value='acme'): self.assert_json_error_contains(self._do_test(user_email), "Account is not associated with this " "subdomain") mock_warning.assert_called_with( "User {} ({}) attempted to access API on wrong " "subdomain ({})".format(user_email, 'zulip', 'acme')) def test_authenticated_json_post_view_if_user_is_incoming_webhook(self) -> None: user_email = 'webhook-bot@zulip.com' user_realm = get_realm('zulip') self._login(user_email, user_realm, password="test") # we set a password because user is a bot self.assert_json_error_contains(self._do_test(user_email), "Webhook bots can only access webhooks") def test_authenticated_json_post_view_if_user_is_not_active(self) -> None: user_email = self.example_email('hamlet') user_realm = get_realm('zulip') self._login(user_email, user_realm, password="test") # Get user_profile after _login so that we have the latest data. user_profile = get_user(user_email, user_realm) # we deactivate user manually because do_deactivate_user removes user session user_profile.is_active = False user_profile.save() self.assert_json_error_contains(self._do_test(user_email), "Account is deactivated") do_reactivate_user(user_profile) def test_authenticated_json_post_view_if_user_realm_is_deactivated(self) -> None: user_email = self.example_email('hamlet') user_realm = get_realm('zulip') user_profile = get_user(user_email, user_realm) self._login(user_email, user_realm) # we deactivate user's realm manually because do_deactivate_user removes user session user_profile.realm.deactivated = True user_profile.realm.save() self.assert_json_error_contains(self._do_test(user_email), "This organization has been deactivated") do_reactivate_realm(user_profile.realm) def _do_test(self, user_email: str) -> HttpResponse: stream_name = "stream name" self.common_subscribe_to_streams(user_email, [stream_name]) data = {"password": initial_password(user_email), "stream": stream_name} return self.client_post(r'/json/subscriptions/exists', data) def _login(self, user_email: str, user_realm: Realm, password: str=None) -> None: if password: user_profile = get_user(user_email, user_realm) user_profile.set_password(password) user_profile.save() self.login(user_email, password) class TestAuthenticatedJsonViewDecorator(ZulipTestCase): def test_authenticated_json_view_if_subdomain_is_invalid(self) -> None: user_email = self.example_email("hamlet") self.login(user_email) with mock.patch('logging.warning') as mock_warning, \ mock.patch('zerver.decorator.get_subdomain', return_value=''): self.assert_json_error_contains(self._do_test(str(user_email)), "Account is not associated with this " "subdomain") mock_warning.assert_called_with( "User {} ({}) attempted to access API on wrong " "subdomain ({})".format(user_email, 'zulip', '')) with mock.patch('logging.warning') as mock_warning, \ mock.patch('zerver.decorator.get_subdomain', return_value='acme'): self.assert_json_error_contains(self._do_test(str(user_email)), "Account is not associated with this " "subdomain") mock_warning.assert_called_with( "User {} ({}) attempted to access API on wrong " "subdomain ({})".format(user_email, 'zulip', 'acme')) def _do_test(self, user_email: str) -> HttpResponse: data = {"password": initial_password(user_email)} return self.client_post(r'/accounts/webathena_kerberos_login/', data) class TestZulipLoginRequiredDecorator(ZulipTestCase): def test_zulip_login_required_if_subdomain_is_invalid(self) -> None: user_email = self.example_email("hamlet") self.login(user_email) with mock.patch('zerver.decorator.get_subdomain', return_value='zulip'): result = self.client_get('/accounts/accept_terms/') self.assertEqual(result.status_code, 200) with mock.patch('zerver.decorator.get_subdomain', return_value=''): result = self.client_get('/accounts/accept_terms/') self.assertEqual(result.status_code, 302) with mock.patch('zerver.decorator.get_subdomain', return_value='acme'): result = self.client_get('/accounts/accept_terms/') self.assertEqual(result.status_code, 302) def test_2fa_failure(self) -> None: @zulip_login_required def test_view(request: HttpRequest) -> HttpResponse: return HttpResponse('Success') request = HttpRequest() request.META['SERVER_NAME'] = 'localhost' request.META['SERVER_PORT'] = 80 request.META['PATH_INFO'] = '' request.user = hamlet = self.example_user('hamlet') request.user.is_verified = lambda: False self.login(hamlet.email) request.session = self.client.session request.get_host = lambda: 'zulip.testserver' response = test_view(request) content = getattr(response, 'content') self.assertEqual(content.decode(), 'Success') with self.settings(TWO_FACTOR_AUTHENTICATION_ENABLED=True): request = HttpRequest() request.META['SERVER_NAME'] = 'localhost' request.META['SERVER_PORT'] = 80 request.META['PATH_INFO'] = '' request.user = hamlet = self.example_user('hamlet') request.user.is_verified = lambda: False self.login(hamlet.email) request.session = self.client.session request.get_host = lambda: 'zulip.testserver' self.create_default_device(request.user) response = test_view(request) status_code = getattr(response, 'status_code') self.assertEqual(status_code, 302) url = getattr(response, 'url') response_url = url.split("?")[0] self.assertEqual(response_url, settings.HOME_NOT_LOGGED_IN) def test_2fa_success(self) -> None: @zulip_login_required def test_view(request: HttpRequest) -> HttpResponse: return HttpResponse('Success') with self.settings(TWO_FACTOR_AUTHENTICATION_ENABLED=True): request = HttpRequest() request.META['SERVER_NAME'] = 'localhost' request.META['SERVER_PORT'] = 80 request.META['PATH_INFO'] = '' request.user = hamlet = self.example_user('hamlet') request.user.is_verified = lambda: True self.login(hamlet.email) request.session = self.client.session request.get_host = lambda: 'zulip.testserver' self.create_default_device(request.user) response = test_view(request) content = getattr(response, 'content') self.assertEqual(content.decode(), 'Success') class TestRequireDecorators(ZulipTestCase): def test_require_server_admin_decorator(self) -> None: user_email = self.example_email('hamlet') user_realm = get_realm('zulip') self.login(user_email) result = self.client_get('/activity') self.assertEqual(result.status_code, 302) user_profile = get_user(user_email, user_realm) user_profile.is_staff = True user_profile.save() result = self.client_get('/activity') self.assertEqual(result.status_code, 200) def test_require_non_guest_user_decorator(self) -> None: guest_user = self.example_user('polonius') self.login(guest_user.email) result = self.common_subscribe_to_streams(guest_user.email, ["Denmark"]) self.assert_json_error(result, "Not allowed for guest users") def test_require_non_guest_human_user_decorator(self) -> None: result = self.api_get("outgoing-webhook@zulip.com", '/api/v1/bots') self.assert_json_error(result, "This endpoint does not accept bot requests.") guest_user = self.example_user('polonius') self.login(guest_user.email) result = self.client_get('/json/bots') self.assert_json_error(result, "Not allowed for guest users") class ReturnSuccessOnHeadRequestDecorator(ZulipTestCase): def test_returns_200_if_request_method_is_head(self) -> None: class HeadRequest: method = 'HEAD' request = HeadRequest() @return_success_on_head_request def test_function(request: HttpRequest) -> HttpResponse: return json_response(msg=u'from_test_function') # nocoverage. isn't meant to be called response = test_function(request) self.assert_json_success(response) self.assertNotEqual(ujson.loads(response.content).get('msg'), u'from_test_function') def test_returns_normal_response_if_request_method_is_not_head(self) -> None: class HeadRequest: method = 'POST' request = HeadRequest() @return_success_on_head_request def test_function(request: HttpRequest) -> HttpResponse: return json_response(msg=u'from_test_function') response = test_function(request) self.assertEqual(ujson.loads(response.content).get('msg'), u'from_test_function') class RestAPITest(ZulipTestCase): def test_method_not_allowed(self) -> None: self.login(self.example_email("hamlet")) result = self.client_patch('/json/users') self.assertEqual(result.status_code, 405) self.assert_in_response('Method Not Allowed', result) def test_options_method(self) -> None: self.login(self.example_email("hamlet")) result = self.client_options('/json/users') self.assertEqual(result.status_code, 204) self.assertEqual(str(result['Allow']), 'GET, POST') result = self.client_options('/json/streams/15') self.assertEqual(result.status_code, 204) self.assertEqual(str(result['Allow']), 'DELETE, PATCH') def test_http_accept_redirect(self) -> None: result = self.client_get('/json/users', HTTP_ACCEPT='text/html') self.assertEqual(result.status_code, 302) self.assertTrue(result["Location"].endswith("/login/?next=/json/users")) class CacheTestCase(ZulipTestCase): def test_cachify_basics(self) -> None: @cachify def add(w: Any, x: Any, y: Any, z: Any) -> Any: return w + x + y + z for i in range(2): self.assertEqual(add(1, 2, 4, 8), 15) self.assertEqual(add('a', 'b', 'c', 'd'), 'abcd') def test_cachify_is_per_call(self) -> None: def test_greetings(greeting: str) -> Tuple[List[str], List[str]]: result_log = [] # type: List[str] work_log = [] # type: List[str] @cachify def greet(first_name: str, last_name: str) -> str: msg = '%s %s %s' % (greeting, first_name, last_name) work_log.append(msg) return msg result_log.append(greet('alice', 'smith')) result_log.append(greet('bob', 'barker')) result_log.append(greet('alice', 'smith')) result_log.append(greet('cal', 'johnson')) return (work_log, result_log) work_log, result_log = test_greetings('hello') self.assertEqual(work_log, [ 'hello alice smith', 'hello bob barker', 'hello cal johnson', ]) self.assertEqual(result_log, [ 'hello alice smith', 'hello bob barker', 'hello alice smith', 'hello cal johnson', ]) work_log, result_log = test_greetings('goodbye') self.assertEqual(work_log, [ 'goodbye alice smith', 'goodbye bob barker', 'goodbye cal johnson', ]) self.assertEqual(result_log, [ 'goodbye alice smith', 'goodbye bob barker', 'goodbye alice smith', 'goodbye cal johnson', ]) class TestUserAgentParsing(ZulipTestCase): def test_user_agent_parsing(self) -> None: """Test for our user agent parsing logic, using a large data set.""" user_agents_parsed = defaultdict(int) # type: Dict[str, int] user_agents_path = os.path.join(settings.DEPLOY_ROOT, "zerver/tests/fixtures/user_agents_unique") for line in open(user_agents_path).readlines(): line = line.strip() match = re.match('^(?P<count>[0-9]+) "(?P<user_agent>.*)"$', line) self.assertIsNotNone(match) groupdict = match.groupdict() count = groupdict["count"] user_agent = groupdict["user_agent"] ret = parse_user_agent(user_agent) user_agents_parsed[ret["name"]] += int(count) class TestIgnoreUnhashableLRUCache(ZulipTestCase): def test_cache_hit(self) -> None: @ignore_unhashable_lru_cache() def f(arg: Any) -> Any: return arg def get_cache_info() -> Tuple[int, int, int]: info = getattr(f, 'cache_info')() hits = getattr(info, 'hits') misses = getattr(info, 'misses') currsize = getattr(info, 'currsize') return hits, misses, currsize def clear_cache() -> None: getattr(f, 'cache_clear')() # Check hashable argument. result = f(1) hits, misses, currsize = get_cache_info() # First one should be a miss. self.assertEqual(hits, 0) self.assertEqual(misses, 1) self.assertEqual(currsize, 1) self.assertEqual(result, 1) result = f(1) hits, misses, currsize = get_cache_info() # Second one should be a hit. self.assertEqual(hits, 1) self.assertEqual(misses, 1) self.assertEqual(currsize, 1) self.assertEqual(result, 1) # Check unhashable argument. result = f([1]) hits, misses, currsize = get_cache_info() # Cache should not be used. self.assertEqual(hits, 1) self.assertEqual(misses, 1) self.assertEqual(currsize, 1) self.assertEqual(result, [1]) # Clear cache. clear_cache() hits, misses, currsize = get_cache_info() self.assertEqual(hits, 0) self.assertEqual(misses, 0) self.assertEqual(currsize, 0)
[ "Dict[str, str]", "Dict[str, str]", "Dict[str, str]", "HttpRequest", "str", "HttpRequest", "HttpRequest", "HttpRequest", "HttpRequest", "HttpRequest", "HttpRequest", "HttpRequest", "UserProfile", "HttpRequest", "UserProfile", "HttpRequest", "UserProfile", "HttpRequest", "UserProfile", "HttpRequest", "Any", "Any", "Any", "Any", "Any", "UserProfile", "bool", "Dict[str, Any]", "Dict[str, Any]", "bool", "HttpRequest", "str", "str", "Realm", "str", "HttpRequest", "HttpRequest", "HttpRequest", "HttpRequest", "Any", "Any", "Any", "Any", "str", "str", "str", "Any" ]
[ 2050, 2072, 2094, 3837, 4803, 5147, 6558, 6927, 8011, 8878, 9561, 9951, 9978, 10136, 10163, 15990, 16017, 17763, 17790, 19372, 21930, 22552, 23347, 24059, 29588, 46452, 46472, 46667, 46689, 46848, 46859, 54448, 54758, 54775, 56340, 57403, 58996, 61350, 61926, 63285, 63293, 63301, 63309, 63582, 63768, 63784, 65912 ]
[ 2064, 2086, 2108, 3848, 4806, 5158, 6569, 6938, 8022, 8889, 9572, 9962, 9989, 10147, 10174, 16001, 16028, 17774, 17801, 19383, 21933, 22555, 23350, 24062, 29591, 46463, 46476, 46681, 46703, 46852, 46870, 54451, 54761, 54780, 56343, 57414, 59007, 61361, 61937, 63288, 63296, 63304, 63312, 63585, 63771, 63787, 65915 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_digest.py
# -*- coding: utf-8 -*- import datetime import mock import time from django.test import override_settings from django.utils.timezone import now as timezone_now from zerver.lib.actions import create_stream_if_needed, do_create_user from zerver.lib.digest import gather_new_streams, handle_digest_email, enqueue_emails, \ gather_new_users from zerver.lib.test_classes import ZulipTestCase from zerver.lib.test_helpers import queries_captured from zerver.models import get_client, get_realm, flush_per_request_caches, \ Realm, Message, UserActivity, UserProfile class TestDigestEmailMessages(ZulipTestCase): @mock.patch('zerver.lib.digest.enough_traffic') @mock.patch('zerver.lib.digest.send_future_email') def test_receive_digest_email_messages(self, mock_send_future_email: mock.MagicMock, mock_enough_traffic: mock.MagicMock) -> None: # build dummy messages for missed messages email reply # have Hamlet send Othello a PM. Othello will reply via email # Hamlet will receive the message. hamlet = self.example_user('hamlet') self.login(hamlet.email) result = self.client_post("/json/messages", {"type": "private", "content": "test_receive_missed_message_email_messages", "client": "test suite", "to": self.example_email('othello')}) self.assert_json_success(result) user_profile = self.example_user('othello') cutoff = time.mktime(datetime.datetime(year=2016, month=1, day=1).timetuple()) handle_digest_email(user_profile.id, cutoff) self.assertEqual(mock_send_future_email.call_count, 1) kwargs = mock_send_future_email.call_args[1] self.assertEqual(kwargs['to_user_id'], user_profile.id) html = kwargs['context']['unread_pms'][0]['header']['html'] expected_url = "'http://zulip.testserver/#narrow/pm-with/{id}-hamlet'".format(id=hamlet.id) self.assertIn(expected_url, html) @mock.patch('zerver.lib.digest.enough_traffic') @mock.patch('zerver.lib.digest.send_future_email') def test_huddle_urls(self, mock_send_future_email: mock.MagicMock, mock_enough_traffic: mock.MagicMock) -> None: email = self.example_email('hamlet') self.login(email) huddle_emails = [ self.example_email('cordelia'), self.example_email('othello'), ] payload = dict( type='private', content='huddle message', client='test suite', to=','.join(huddle_emails), ) result = self.client_post("/json/messages", payload) self.assert_json_success(result) user_profile = self.example_user('othello') cutoff = time.mktime(datetime.datetime(year=2016, month=1, day=1).timetuple()) handle_digest_email(user_profile.id, cutoff) self.assertEqual(mock_send_future_email.call_count, 1) kwargs = mock_send_future_email.call_args[1] self.assertEqual(kwargs['to_user_id'], user_profile.id) html = kwargs['context']['unread_pms'][0]['header']['html'] other_user_ids = sorted([ self.example_user('cordelia').id, self.example_user('hamlet').id, ]) slug = ','.join(str(user_id) for user_id in other_user_ids) + '-group' expected_url = "'http://zulip.testserver/#narrow/pm-with/" + slug + "'" self.assertIn(expected_url, html) @mock.patch('zerver.lib.digest.enough_traffic') @mock.patch('zerver.lib.digest.send_future_email') def test_multiple_stream_senders(self, mock_send_future_email: mock.MagicMock, mock_enough_traffic: mock.MagicMock) -> None: client = 'website' # this makes `sent_by_human` return True othello = self.example_user('othello') self.subscribe(othello, 'Verona') one_day_ago = timezone_now() - datetime.timedelta(days=1) Message.objects.all().update(pub_date=one_day_ago) one_sec_ago = timezone_now() - datetime.timedelta(seconds=1) cutoff = time.mktime(one_sec_ago.timetuple()) senders = ['hamlet', 'cordelia', 'iago', 'prospero', 'ZOE'] for sender_name in senders: email = self.example_email(sender_name) self.login(email) content = 'some content for ' + email payload = dict( type='stream', client=client, to='Verona', topic='lunch', content=content, ) result = self.client_post("/json/messages", payload) self.assert_json_success(result) flush_per_request_caches() with queries_captured() as queries: handle_digest_email(othello.id, cutoff) self.assertTrue(29 <= len(queries) <= 30) self.assertEqual(mock_send_future_email.call_count, 1) kwargs = mock_send_future_email.call_args[1] self.assertEqual(kwargs['to_user_id'], othello.id) hot_convo = kwargs['context']['hot_conversations'][0] expected_participants = { self.example_user(sender).full_name for sender in senders } self.assertEqual(set(hot_convo['participants']), expected_participants) self.assertEqual(hot_convo['count'], 5 - 2) # 5 messages, but 2 shown teaser_messages = hot_convo['first_few_messages'][0]['senders'] self.assertIn('some content', teaser_messages[0]['content'][0]['plain']) self.assertIn(teaser_messages[0]['sender'], expected_participants) @mock.patch('zerver.lib.digest.queue_digest_recipient') @mock.patch('zerver.lib.digest.timezone_now') @override_settings(SEND_DIGEST_EMAILS=True) def test_inactive_users_queued_for_digest(self, mock_django_timezone: mock.MagicMock, mock_queue_digest_recipient: mock.MagicMock) -> None: cutoff = timezone_now() # Test Tuesday mock_django_timezone.return_value = datetime.datetime(year=2016, month=1, day=5) all_user_profiles = UserProfile.objects.filter( is_active=True, is_bot=False, enable_digest_emails=True) # Check that all users without an a UserActivity entry are considered # inactive users and get enqueued. enqueue_emails(cutoff) self.assertEqual(mock_queue_digest_recipient.call_count, all_user_profiles.count()) mock_queue_digest_recipient.reset_mock() for realm in Realm.objects.filter(deactivated=False, digest_emails_enabled=True): user_profiles = all_user_profiles.filter(realm=realm) for user_profile in user_profiles: UserActivity.objects.create( last_visit=cutoff - datetime.timedelta(days=1), user_profile=user_profile, count=0, client=get_client('test_client')) # Check that inactive users are enqueued enqueue_emails(cutoff) self.assertEqual(mock_queue_digest_recipient.call_count, all_user_profiles.count()) @mock.patch('zerver.lib.digest.queue_digest_recipient') @mock.patch('zerver.lib.digest.timezone_now') def test_disabled(self, mock_django_timezone: mock.MagicMock, mock_queue_digest_recipient: mock.MagicMock) -> None: cutoff = timezone_now() # A Tuesday mock_django_timezone.return_value = datetime.datetime(year=2016, month=1, day=5) enqueue_emails(cutoff) mock_queue_digest_recipient.assert_not_called() @mock.patch('zerver.lib.digest.enough_traffic', return_value=True) @mock.patch('zerver.lib.digest.timezone_now') @override_settings(SEND_DIGEST_EMAILS=True) def test_active_users_not_enqueued(self, mock_django_timezone: mock.MagicMock, mock_enough_traffic: mock.MagicMock) -> None: cutoff = timezone_now() # A Tuesday mock_django_timezone.return_value = datetime.datetime(year=2016, month=1, day=5) realms = Realm.objects.filter(deactivated=False, digest_emails_enabled=True) for realm in realms: user_profiles = UserProfile.objects.filter(realm=realm) for counter, user_profile in enumerate(user_profiles, 1): UserActivity.objects.create( last_visit=cutoff + datetime.timedelta(days=1), user_profile=user_profile, count=0, client=get_client('test_client')) # Check that an active user is not enqueued with mock.patch('zerver.lib.digest.queue_digest_recipient') as mock_queue_digest_recipient: enqueue_emails(cutoff) self.assertEqual(mock_queue_digest_recipient.call_count, 0) @mock.patch('zerver.lib.digest.queue_digest_recipient') @mock.patch('zerver.lib.digest.timezone_now') @override_settings(SEND_DIGEST_EMAILS=True) def test_only_enqueue_on_valid_day(self, mock_django_timezone: mock.MagicMock, mock_queue_digest_recipient: mock.MagicMock) -> None: # Not a Tuesday mock_django_timezone.return_value = datetime.datetime(year=2016, month=1, day=6) # Check that digests are not sent on days other than Tuesday. cutoff = timezone_now() enqueue_emails(cutoff) self.assertEqual(mock_queue_digest_recipient.call_count, 0) @mock.patch('zerver.lib.digest.queue_digest_recipient') @mock.patch('zerver.lib.digest.timezone_now') @override_settings(SEND_DIGEST_EMAILS=True) def test_no_email_digest_for_bots(self, mock_django_timezone: mock.MagicMock, mock_queue_digest_recipient: mock.MagicMock) -> None: cutoff = timezone_now() # A Tuesday mock_django_timezone.return_value = datetime.datetime(year=2016, month=1, day=5) bot = do_create_user('some_bot@example.com', 'password', get_realm('zulip'), 'some_bot', '', bot_type=UserProfile.DEFAULT_BOT) UserActivity.objects.create( last_visit=cutoff - datetime.timedelta(days=1), user_profile=bot, count=0, client=get_client('test_client')) # Check that bots are not sent emails enqueue_emails(cutoff) for arg in mock_queue_digest_recipient.call_args_list: user = arg[0][0] self.assertNotEqual(user.id, bot.id) @mock.patch('zerver.lib.digest.timezone_now') @override_settings(SEND_DIGEST_EMAILS=True) def test_new_stream_link(self, mock_django_timezone: mock.MagicMock) -> None: cutoff = datetime.datetime(year=2017, month=11, day=1) mock_django_timezone.return_value = datetime.datetime(year=2017, month=11, day=5) cordelia = self.example_user('cordelia') stream_id = create_stream_if_needed(cordelia.realm, 'New stream')[0].id new_stream = gather_new_streams(cordelia, cutoff)[1] expected_html = "<a href='http://zulip.testserver/#narrow/stream/{stream_id}-New-stream'>New stream</a>".format(stream_id=stream_id) self.assertIn(expected_html, new_stream['html']) @mock.patch('zerver.lib.digest.timezone_now') def test_gather_new_users(self, mock_django_timezone: mock.MagicMock) -> None: cutoff = timezone_now() do_create_user('abc@example.com', password='abc', realm=get_realm('zulip'), full_name='abc', short_name='abc') # Normal users get info about new users user = self.example_user('aaron') gathered_no_of_user, _ = gather_new_users(user, cutoff) self.assertEqual(gathered_no_of_user, 1) # Definitely, admin users get info about new users user = self.example_user('iago') gathered_no_of_user, _ = gather_new_users(user, cutoff) self.assertEqual(gathered_no_of_user, 1) # Guest users don't get info about new users user = self.example_user('polonius') gathered_no_of_user, _ = gather_new_users(user, cutoff) self.assertEqual(gathered_no_of_user, 0) # Zephyr users also don't get info about new users in their realm user = self.mit_user('starnine') do_create_user('abc@mit.edu', password='abc', realm=user.realm, full_name='abc', short_name='abc') gathered_no_of_user, _ = gather_new_users(user, cutoff) self.assertEqual(gathered_no_of_user, 0)
[ "mock.MagicMock", "mock.MagicMock", "mock.MagicMock", "mock.MagicMock", "mock.MagicMock", "mock.MagicMock", "mock.MagicMock", "mock.MagicMock", "mock.MagicMock", "mock.MagicMock", "mock.MagicMock", "mock.MagicMock", "mock.MagicMock", "mock.MagicMock", "mock.MagicMock", "mock.MagicMock", "mock.MagicMock", "mock.MagicMock" ]
[ 798, 878, 2297, 2359, 3848, 3922, 6072, 6163, 7529, 7596, 8086, 8162, 9308, 9392, 9957, 10040, 10939, 11614 ]
[ 812, 892, 2311, 2373, 3862, 3936, 6086, 6177, 7543, 7610, 8100, 8176, 9322, 9406, 9971, 10054, 10953, 11628 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_docs.py
# -*- coding: utf-8 -*- import mock import os import subprocess from django.conf import settings from django.test import TestCase, override_settings from django.http import HttpResponse from typing import Any, Dict, List from zproject.settings import DEPLOY_ROOT from zerver.lib.integrations import INTEGRATIONS from zerver.lib.test_classes import ZulipTestCase from zerver.lib.test_helpers import HostRequestMock from zerver.lib.test_runner import slow from zerver.lib.utils import split_by from zerver.models import Realm, get_realm from zerver.views.integrations import ( add_api_uri_context, add_integrations_context, ) class DocPageTest(ZulipTestCase): def get_doc(self, url: str, subdomain: str) -> HttpResponse: if url[0:23] == "/integrations/doc-html/": return self.client_get(url, subdomain=subdomain, HTTP_X_REQUESTED_WITH='XMLHttpRequest') return self.client_get(url, subdomain=subdomain) def _test(self, url: str, expected_content: str, extra_strings: List[str]=[], landing_missing_strings: List[str]=[], landing_page: bool=True, doc_html_str: bool=False) -> None: # Test the URL on the "zephyr" subdomain result = self.get_doc(url, subdomain="zephyr") self.assertEqual(result.status_code, 200) self.assertIn(expected_content, str(result.content)) for s in extra_strings: self.assertIn(s, str(result.content)) if not doc_html_str: self.assert_in_success_response(['<meta name="robots" content="noindex,nofollow">'], result) # Test the URL on the root subdomain result = self.get_doc(url, subdomain="") self.assertEqual(result.status_code, 200) self.assertIn(expected_content, str(result.content)) if not doc_html_str: self.assert_in_success_response(['<meta name="robots" content="noindex,nofollow">'], result) for s in extra_strings: self.assertIn(s, str(result.content)) if not landing_page: return with self.settings(ROOT_DOMAIN_LANDING_PAGE=True): # Test the URL on the root subdomain with the landing page setting result = self.get_doc(url, subdomain="") self.assertEqual(result.status_code, 200) self.assertIn(expected_content, str(result.content)) for s in extra_strings: self.assertIn(s, str(result.content)) for s in landing_missing_strings: self.assertNotIn(s, str(result.content)) if not doc_html_str: self.assert_in_success_response(['<meta name="description" content="Zulip combines'], result) self.assert_not_in_success_response(['<meta name="robots" content="noindex,nofollow">'], result) # Test the URL on the "zephyr" subdomain with the landing page setting result = self.get_doc(url, subdomain="zephyr") self.assertEqual(result.status_code, 200) self.assertIn(expected_content, str(result.content)) for s in extra_strings: self.assertIn(s, str(result.content)) if not doc_html_str: self.assert_in_success_response(['<meta name="robots" content="noindex,nofollow">'], result) @slow("Tests dozens of endpoints, including generating lots of emails") def test_doc_endpoints(self) -> None: self._test('/api/', 'The Zulip API') self._test('/api/api-keys', 'be careful with it') self._test('/api/installation-instructions', 'No download required!') self._test('/api/send-message', 'steal away your hearts') self._test('/api/render-message', '**foo**') self._test('/api/get-all-streams', 'include_public') self._test('/api/get-stream-id', 'The name of the stream to retrieve the ID for.') self._test('/api/get-subscribed-streams', 'Get all streams that the user is subscribed to.') self._test('/api/get-all-users', 'client_gravatar') self._test('/api/register-queue', 'apply_markdown') self._test('/api/get-events-from-queue', 'dont_block') self._test('/api/delete-queue', 'Delete a previously registered queue') self._test('/api/update-message', 'propagate_mode') self._test('/api/get-profile', 'takes no arguments') self._test('/api/add-subscriptions', 'authorization_errors_fatal') self._test('/api/create-user', 'zuliprc-admin') self._test('/api/remove-subscriptions', 'not_subscribed') self._test('/team/', 'industry veterans') self._test('/history/', 'Cambridge, Massachusetts') # Test the i18n version of one of these pages. self._test('/en/history/', 'Cambridge, Massachusetts') self._test('/apps/', 'Apps for every platform.') self._test('/features/', 'Beautiful messaging') self._test('/hello/', 'productive team chat', landing_missing_strings=["Login"]) self._test('/why-zulip/', 'Why Zulip?') self._test('/for/open-source/', 'for open source projects') self._test('/for/companies/', 'in a company') self._test('/for/working-groups-and-communities/', 'standards bodies') self._test('/for/mystery-hunt/', 'four SIPB alums') self._test('/security/', 'TLS encryption') self._test('/devlogin/', 'Normal users', landing_page=False) self._test('/devtools/', 'Useful development URLs') self._test('/errors/404/', 'Page not found') self._test('/errors/5xx/', 'Internal server error') self._test('/emails/', 'manually generate most of the emails by clicking') result = self.client_get('/integrations/doc-html/nonexistent_integration', follow=True, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(result.status_code, 404) result = self.client_get('/new-user/') self.assertEqual(result.status_code, 301) self.assertIn('hello', result['Location']) result = self.client_get('/static/favicon.ico') self.assertEqual(result.status_code, 200) @slow("Tests dozens of endpoints, including all our integrations docs") def test_integration_doc_endpoints(self) -> None: self._test('/integrations/', 'native integrations.', extra_strings=[ 'And hundreds more through', 'Hubot', 'Zapier', 'IFTTT' ]) for integration in INTEGRATIONS.keys(): url = '/integrations/doc-html/{}'.format(integration) self._test(url, '', doc_html_str=True) def test_email_integration(self) -> None: self._test('/integrations/doc-html/email', 'support+abcdefg@testserver', doc_html_str=True) with self.settings(EMAIL_GATEWAY_PATTERN=''): result = self.get_doc('integrations/doc-html/email', subdomain='zulip') self.assertNotIn('support+abcdefg@testserver', str(result.content)) # if EMAIL_GATEWAY_PATTERN is empty, the main /integrations page should # be rendered instead self._test('/integrations/', 'native integrations.') def test_doc_html_str_non_ajax_call(self) -> None: # We don't need to test all the pages for 404 for integration in list(INTEGRATIONS.keys())[5]: with self.settings(ROOT_DOMAIN_LANDING_PAGE=True): url = '/en/integrations/doc-html/{}'.format(integration) result = self.client_get(url, subdomain="", follow=True) self.assertEqual(result.status_code, 404) result = self.client_get(url, subdomain="zephyr", follow=True) self.assertEqual(result.status_code, 404) url = '/en/integrations/doc-html/{}'.format(integration) result = self.client_get(url, subdomain="", follow=True) self.assertEqual(result.status_code, 404) result = self.client_get(url, subdomain="zephyr", follow=True) self.assertEqual(result.status_code, 404) result = self.client_get('/integrations/doc-html/nonexistent_integration', follow=True) self.assertEqual(result.status_code, 404) class HelpTest(ZulipTestCase): def test_help_settings_links(self) -> None: result = self.client_get('/help/change-the-time-format') self.assertIn('Go to <a href="/#settings/display-settings">Display settings</a>', str(result.content)) self.assertEqual(result.status_code, 200) with self.settings(ROOT_DOMAIN_LANDING_PAGE=True): result = self.client_get('/help/change-the-time-format', subdomain="") self.assertEqual(result.status_code, 200) self.assertIn('<strong>Display settings</strong>', str(result.content)) self.assertNotIn('/#settings', str(result.content)) def test_help_relative_links_for_gear(self) -> None: result = self.client_get('/help/analytics') self.assertIn('<a href="/stats">Statistics</a>', str(result.content)) self.assertEqual(result.status_code, 200) with self.settings(ROOT_DOMAIN_LANDING_PAGE=True): result = self.client_get('/help/analytics', subdomain="") self.assertEqual(result.status_code, 200) self.assertIn('<strong>Statistics</strong>', str(result.content)) self.assertNotIn('/stats', str(result.content)) def test_help_relative_links_for_stream(self) -> None: result = self.client_get('/help/message-a-stream-by-email') self.assertIn('<a href="/#streams/subscribed">Your streams</a>', str(result.content)) self.assertEqual(result.status_code, 200) with self.settings(ROOT_DOMAIN_LANDING_PAGE=True): result = self.client_get('/help/message-a-stream-by-email', subdomain="") self.assertEqual(result.status_code, 200) self.assertIn('<strong>Manage streams</strong>', str(result.content)) self.assertNotIn('/#streams', str(result.content)) class IntegrationTest(TestCase): def test_check_if_every_integration_has_logo_that_exists(self) -> None: for integration in INTEGRATIONS.values(): self.assertTrue(os.path.isfile(os.path.join(DEPLOY_ROOT, integration.logo))) def test_api_url_view_subdomains_base(self) -> None: context = dict() # type: Dict[str, Any] add_api_uri_context(context, HostRequestMock()) self.assertEqual(context["api_url_scheme_relative"], "testserver/api") self.assertEqual(context["api_url"], "http://testserver/api") self.assertTrue(context["html_settings_links"]) @override_settings(ROOT_DOMAIN_LANDING_PAGE=True) def test_api_url_view_subdomains_homepage_base(self) -> None: context = dict() # type: Dict[str, Any] add_api_uri_context(context, HostRequestMock()) self.assertEqual(context["api_url_scheme_relative"], "yourZulipDomain.testserver/api") self.assertEqual(context["api_url"], "http://yourZulipDomain.testserver/api") self.assertFalse(context["html_settings_links"]) def test_api_url_view_subdomains_full(self) -> None: context = dict() # type: Dict[str, Any] request = HostRequestMock(host="mysubdomain.testserver") add_api_uri_context(context, request) self.assertEqual(context["api_url_scheme_relative"], "mysubdomain.testserver/api") self.assertEqual(context["api_url"], "http://mysubdomain.testserver/api") self.assertTrue(context["html_settings_links"]) def test_html_settings_links(self) -> None: context = dict() # type: Dict[str, Any] with self.settings(ROOT_DOMAIN_LANDING_PAGE=True): add_api_uri_context(context, HostRequestMock()) self.assertEqual( context['settings_html'], 'Zulip settings page') self.assertEqual( context['subscriptions_html'], 'streams page') context = dict() with self.settings(ROOT_DOMAIN_LANDING_PAGE=True): add_api_uri_context(context, HostRequestMock(host="mysubdomain.testserver")) self.assertEqual( context['settings_html'], '<a href="/#settings">Zulip settings page</a>') self.assertEqual( context['subscriptions_html'], '<a target="_blank" href="/#streams">streams page</a>') context = dict() add_api_uri_context(context, HostRequestMock()) self.assertEqual( context['settings_html'], '<a href="/#settings">Zulip settings page</a>') self.assertEqual( context['subscriptions_html'], '<a target="_blank" href="/#streams">streams page</a>') class AboutPageTest(ZulipTestCase): def setUp(self) -> None: """ Manual installation which did not execute `tools/provision` would not have the `static/generated/github-contributors.json` fixture file. """ # This block has unreliable test coverage due to the implicit # caching here, so we exclude it from coverage. if not os.path.exists(settings.CONTRIBUTORS_DATA): # Copy the fixture file in `zerver/tests/fixtures` to `static/generated` update_script = os.path.join(os.path.dirname(__file__), '../../tools/update-authors-json') # nocoverage subprocess.check_call([update_script, '--use-fixture']) # nocoverage def test_endpoint(self) -> None: """ We can't check the contributors list since it is rendered client-side """ result = self.client_get('/team/') self.assert_in_success_response(['Our amazing community'], result) def test_split_by(self) -> None: """Utility function primarily used in authors page""" flat_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] expected_result = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] self.assertEqual(split_by(flat_list, 3, None), expected_result) class ConfigErrorTest(ZulipTestCase): @override_settings(GOOGLE_OAUTH2_CLIENT_ID=None) def test_google(self) -> None: result = self.client_get("/accounts/login/google/") self.assertEqual(result.status_code, 302) self.assertEqual(result.url, '/config-error/google') result = self.client_get(result.url) self.assert_in_success_response(["GOOGLE_OAUTH2_CLIENT_ID"], result) @override_settings(SOCIAL_AUTH_GITHUB_KEY=None) def test_github(self) -> None: result = self.client_get("/accounts/login/social/github") self.assertEqual(result.status_code, 302) self.assertEqual(result.url, '/config-error/github') result = self.client_get(result.url) self.assert_in_success_response(["SOCIAL_AUTH_GITHUB_KEY"], result) @override_settings(SOCIAL_AUTH_GITHUB_KEY=None) @override_settings(DEVELOPMENT=False) def test_github_production_error(self) -> None: """Test the !DEVELOPMENT code path of config-error.""" result = self.client_get("/accounts/login/social/github") self.assertEqual(result.status_code, 302) self.assertEqual(result.url, '/config-error/github') result = self.client_get(result.url) self.assert_in_success_response(["/etc/zulip/zulip-secrets.conf"], result) def test_smtp_error(self) -> None: result = self.client_get("/config-error/smtp") self.assertEqual(result.status_code, 200) self.assert_in_success_response(["email configuration"], result) def test_dev_direct_production_error(self) -> None: result = self.client_get("/config-error/dev") self.assertEqual(result.status_code, 200) self.assert_in_success_response(["DevAuthBackend"], result) class PlansPageTest(ZulipTestCase): def test_plans_auth(self) -> None: # Test root domain result = self.client_get("/plans/", subdomain="") self.assert_in_success_response(["Sign up now"], result) # Test non-existant domain result = self.client_get("/plans/", subdomain="moo") self.assert_in_success_response(["does not exist"], result) # Test valid domain, no login realm = get_realm("zulip") realm.plan_type = Realm.STANDARD_FREE realm.save(update_fields=["plan_type"]) result = self.client_get("/plans/", subdomain="zulip") self.assertEqual(result.status_code, 302) self.assertEqual(result["Location"], "/accounts/login?next=plans") # Test valid domain, with login self.login(self.example_email('hamlet')) result = self.client_get("/plans/", subdomain="zulip") self.assert_in_success_response(["Current plan"], result) # Test root domain, with login on different domain result = self.client_get("/plans/", subdomain="") # TODO: works in manual testing, but I suspect something is funny in # the test environment # self.assert_in_success_response(["Sign up now"], result) def test_CTA_text_by_plan_type(self) -> None: sign_up_now = "Sign up now" buy_standard = "Buy Standard" current_plan = "Current plan" # Root domain result = self.client_get("/plans/", subdomain="") self.assert_in_success_response([sign_up_now, buy_standard], result) self.assert_not_in_success_response([current_plan], result) realm = get_realm("zulip") realm.plan_type = Realm.SELF_HOSTED realm.save(update_fields=["plan_type"]) result = self.client_get("/plans/", subdomain="zulip") self.assertEqual(result.status_code, 302) self.assertEqual(result["Location"], "https://zulipchat.com/plans") self.login(self.example_email("iago")) # SELF_HOSTED should hide the local plans page, even if logged in result = self.client_get("/plans/", subdomain="zulip") self.assertEqual(result.status_code, 302) self.assertEqual(result["Location"], "https://zulipchat.com/plans") realm.plan_type = Realm.LIMITED realm.save(update_fields=["plan_type"]) result = self.client_get("/plans/", subdomain="zulip") self.assert_in_success_response([current_plan, buy_standard], result) self.assert_not_in_success_response([sign_up_now], result) realm.plan_type = Realm.STANDARD_FREE realm.save(update_fields=["plan_type"]) result = self.client_get("/plans/", subdomain="zulip") self.assert_in_success_response([current_plan], result) self.assert_not_in_success_response([sign_up_now, buy_standard], result) realm.plan_type = Realm.STANDARD realm.save(update_fields=["plan_type"]) result = self.client_get("/plans/", subdomain="zulip") self.assert_in_success_response([current_plan], result) self.assert_not_in_success_response([sign_up_now, buy_standard], result)
[ "str", "str", "str", "str" ]
[ 697, 713, 970, 993 ]
[ 700, 716, 973, 996 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_email_change.py
# -*- coding: utf-8 -*- import datetime from typing import Any from email.utils import parseaddr, formataddr import re import django import mock from django.conf import settings from django.core import mail from django.http import HttpResponse from django.urls import reverse from django.utils.timezone import now from confirmation.models import Confirmation, generate_key, confirmation_url from zerver.lib.actions import do_start_email_change_process, do_set_realm_property from zerver.lib.test_classes import ( ZulipTestCase, ) from zerver.lib.send_email import FromAddress from zerver.models import get_user, EmailChangeStatus, Realm, get_realm class EmailChangeTestCase(ZulipTestCase): def test_confirm_email_change_with_non_existent_key(self) -> None: self.login(self.example_email("hamlet")) key = generate_key() url = confirmation_url(key, 'testserver', Confirmation.EMAIL_CHANGE) response = self.client_get(url) self.assert_in_success_response(["Whoops. We couldn't find your confirmation link in the system."], response) def test_confirm_email_change_with_invalid_key(self) -> None: self.login(self.example_email("hamlet")) key = 'invalid key' url = confirmation_url(key, 'testserver', Confirmation.EMAIL_CHANGE) response = self.client_get(url) self.assert_in_success_response(["Whoops. The confirmation link is malformed."], response) def test_confirm_email_change_when_time_exceeded(self) -> None: user_profile = self.example_user('hamlet') old_email = user_profile.email new_email = 'hamlet-new@zulip.com' self.login(self.example_email("hamlet")) obj = EmailChangeStatus.objects.create(new_email=new_email, old_email=old_email, user_profile=user_profile, realm=user_profile.realm) key = generate_key() date_sent = now() - datetime.timedelta(days=2) Confirmation.objects.create(content_object=obj, date_sent=date_sent, confirmation_key=key, type=Confirmation.EMAIL_CHANGE) url = confirmation_url(key, user_profile.realm.host, Confirmation.EMAIL_CHANGE) response = self.client_get(url) self.assert_in_success_response(["The confirmation link has expired or been deactivated."], response) def test_confirm_email_change(self) -> None: user_profile = self.example_user('hamlet') old_email = user_profile.email new_email = 'hamlet-new@zulip.com' new_realm = get_realm('zulip') self.login(self.example_email('hamlet')) obj = EmailChangeStatus.objects.create(new_email=new_email, old_email=old_email, user_profile=user_profile, realm=user_profile.realm) key = generate_key() Confirmation.objects.create(content_object=obj, date_sent=now(), confirmation_key=key, type=Confirmation.EMAIL_CHANGE) url = confirmation_url(key, user_profile.realm.host, Confirmation.EMAIL_CHANGE) response = self.client_get(url) self.assertEqual(response.status_code, 200) self.assert_in_success_response(["This confirms that the email address for your Zulip"], response) user_profile = get_user(new_email, new_realm) self.assertTrue(bool(user_profile)) obj.refresh_from_db() self.assertEqual(obj.status, 1) def test_start_email_change_process(self) -> None: user_profile = self.example_user('hamlet') do_start_email_change_process(user_profile, 'hamlet-new@zulip.com') self.assertEqual(EmailChangeStatus.objects.count(), 1) def test_end_to_end_flow(self) -> None: data = {'email': 'hamlet-new@zulip.com'} email = self.example_email("hamlet") self.login(email) url = '/json/settings' self.assertEqual(len(mail.outbox), 0) result = self.client_patch(url, data) self.assertEqual(len(mail.outbox), 1) self.assert_in_success_response(['Check your email for a confirmation link.'], result) email_message = mail.outbox[0] self.assertEqual( email_message.subject, 'Verify your new email address' ) body = email_message.body from_email = email_message.from_email self.assertIn('We received a request to change the email', body) self.assertIn('Zulip Account Security', from_email) tokenized_no_reply_email = parseaddr(email_message.from_email)[1] self.assertTrue(re.search(self.TOKENIZED_NOREPLY_REGEX, tokenized_no_reply_email)) activation_url = [s for s in body.split('\n') if s][4] response = self.client_get(activation_url) self.assert_in_success_response(["This confirms that the email address"], response) # Now confirm trying to change your email back doesn't throw an immediate error result = self.client_patch(url, {"email": "hamlet@zulip.com"}) self.assert_in_success_response(['Check your email for a confirmation link.'], result) def test_unauthorized_email_change(self) -> None: data = {'email': 'hamlet-new@zulip.com'} user_profile = self.example_user('hamlet') email = user_profile.email self.login(email) do_set_realm_property(user_profile.realm, 'email_changes_disabled', True) url = '/json/settings' result = self.client_patch(url, data) self.assertEqual(len(mail.outbox), 0) self.assertEqual(result.status_code, 400) self.assert_in_response("Email address changes are disabled in this organization.", result) # Realm admins can change their email address even setting is disabled. data = {'email': 'iago-new@zulip.com'} self.login(self.example_email("iago")) url = '/json/settings' result = self.client_patch(url, data) self.assert_in_success_response(['Check your email for a confirmation link.'], result) def test_email_change_already_taken(self) -> None: data = {'email': 'cordelia@zulip.com'} user_profile = self.example_user('hamlet') email = user_profile.email self.login(email) url = '/json/settings' result = self.client_patch(url, data) self.assertEqual(len(mail.outbox), 0) self.assertEqual(result.status_code, 400) self.assert_in_response("Already has an account", result) def test_unauthorized_email_change_from_email_confirmation_link(self) -> None: data = {'email': 'hamlet-new@zulip.com'} user_profile = self.example_user('hamlet') email = user_profile.email self.login(email) url = '/json/settings' self.assertEqual(len(mail.outbox), 0) result = self.client_patch(url, data) self.assertEqual(len(mail.outbox), 1) self.assert_in_success_response(['Check your email for a confirmation link.'], result) email_message = mail.outbox[0] self.assertEqual( email_message.subject, 'Verify your new email address' ) body = email_message.body self.assertIn('We received a request to change the email', body) do_set_realm_property(user_profile.realm, 'email_changes_disabled', True) activation_url = [s for s in body.split('\n') if s][4] response = self.client_get(activation_url) self.assertEqual(response.status_code, 400) self.assert_in_response("Email address changes are disabled in this organization.", response) def test_post_invalid_email(self) -> None: data = {'email': 'hamlet-new'} email = self.example_email("hamlet") self.login(email) url = '/json/settings' result = self.client_patch(url, data) self.assert_in_response('Invalid address', result) def test_post_same_email(self) -> None: data = {'email': self.example_email("hamlet")} email = self.example_email("hamlet") self.login(email) url = '/json/settings' result = self.client_patch(url, data) self.assertEqual('success', result.json()['result']) self.assertEqual('', result.json()['msg'])
[]
[]
[]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_email_log.py
import os import mock from django.conf import settings from zerver.lib.test_classes import ZulipTestCase from zproject.email_backends import get_forward_address class EmailLogTest(ZulipTestCase): def test_generate_and_clear_email_log(self) -> None: with self.settings(EMAIL_BACKEND='zproject.email_backends.EmailLogBackEnd'), \ mock.patch('zproject.email_backends.EmailLogBackEnd.send_email_smtp'), \ mock.patch('logging.info', return_value=None), \ self.settings(DEVELOPMENT_LOG_EMAILS=True): result = self.client_get('/emails/generate/') self.assertEqual(result.status_code, 302) self.assertIn('emails', result['Location']) result = self.client_get("/emails/") self.assert_in_success_response(["All the emails sent in the Zulip"], result) result = self.client_get('/emails/clear/') self.assertEqual(result.status_code, 302) result = self.client_get(result['Location']) self.assertIn('manually generate most of the emails by clicking', str(result.content)) def test_forward_address_details(self) -> None: forward_address = "forward-to@example.com" result = self.client_post("/emails/", {"forward_address": forward_address}) self.assert_json_success(result) self.assertEqual(get_forward_address(), forward_address) with self.settings(EMAIL_BACKEND='zproject.email_backends.EmailLogBackEnd'), \ mock.patch('logging.info', return_value=None): with mock.patch('zproject.email_backends.EmailLogBackEnd.send_email_smtp'): result = self.client_get('/emails/generate/') self.assertEqual(result.status_code, 302) self.assertIn('emails', result['Location']) result = self.client_get(result['Location']) self.assert_in_success_response([forward_address], result) os.remove(settings.FORWARD_ADDRESS_CONFIG_FILE)
[]
[]
[]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_email_mirror.py
# -*- coding: utf-8 -*- import subprocess from django.http import HttpResponse from zerver.lib.test_helpers import ( most_recent_message, most_recent_usermessage, POSTRequestMock) from zerver.lib.test_classes import ( ZulipTestCase, ) from zerver.models import ( get_display_recipient, get_realm, get_stream, Recipient, ) from zerver.lib.actions import ( encode_email_address, ensure_stream, decode_email_address, ) from zerver.lib.email_mirror import ( process_message, process_stream_message, ZulipEmailForwardError, create_missed_message_address, get_missed_message_token_from_address, ) from zerver.lib.send_email import FromAddress from zerver.lib.notifications import ( handle_missedmessage_emails, ) from zerver.management.commands import email_mirror from email.mime.text import MIMEText import re import ujson import mock import os import sys from io import StringIO from django.conf import settings from typing import Any, Callable, Dict, Mapping, Union, Optional class TestEncodeDecode(ZulipTestCase): def test_encode_decode(self) -> None: realm = get_realm('zulip') stream_name = 'dev. help' stream = ensure_stream(realm, stream_name) email_address = encode_email_address(stream) self.assertTrue(email_address.startswith('dev%0046%0032help')) self.assertTrue(email_address.endswith('@testserver')) tup = decode_email_address(email_address) assert tup is not None (decoded_stream_name, token) = tup self.assertEqual(decoded_stream_name, stream_name) self.assertEqual(token, stream.email_token) email_address = email_address.replace('+', '.') tup = decode_email_address(email_address) assert tup is not None (decoded_stream_name, token) = tup self.assertEqual(decoded_stream_name, stream_name) self.assertEqual(token, stream.email_token) email_address = email_address.replace('@testserver', '@zulip.org') self.assertEqual(decode_email_address(email_address), None) with self.settings(EMAIL_GATEWAY_EXTRA_PATTERN_HACK='@zulip.org'): tup = decode_email_address(email_address) assert tup is not None (decoded_stream_name, token) = tup self.assertEqual(decoded_stream_name, stream_name) self.assertEqual(token, stream.email_token) self.assertEqual(decode_email_address('bogus'), None) class TestEmailMirrorLibrary(ZulipTestCase): def test_get_missed_message_token(self) -> None: def get_token(address: str) -> str: with self.settings(EMAIL_GATEWAY_PATTERN="%s@example.com"): return get_missed_message_token_from_address(address) address = 'mm' + ('x' * 32) + '@example.com' token = get_token(address) self.assertEqual(token, 'x' * 32) # This next section was a bug at one point--we'd treat ordinary # user addresses that happened to begin with "mm" as being # the special mm+32chars tokens. address = 'mmathers@example.com' with self.assertRaises(ZulipEmailForwardError): get_token(address) # Now test the case where we our address does not match the # EMAIL_GATEWAY_PATTERN. # This used to crash in an ugly way; we want to throw a proper # exception. address = 'alice@not-the-domain-we-were-expecting.com' with self.assertRaises(ZulipEmailForwardError): get_token(address) class TestStreamEmailMessagesSuccess(ZulipTestCase): def test_receive_stream_email_messages_success(self) -> None: # build dummy messages for stream # test valid incoming stream message is processed properly user_profile = self.example_user('hamlet') self.login(user_profile.email) self.subscribe(user_profile, "Denmark") stream = get_stream("Denmark", user_profile.realm) stream_to_address = encode_email_address(stream) incoming_valid_message = MIMEText('TestStreamEmailMessages Body') # type: Any # https://github.com/python/typeshed/issues/275 incoming_valid_message['Subject'] = 'TestStreamEmailMessages Subject' incoming_valid_message['From'] = self.example_email('hamlet') incoming_valid_message['To'] = stream_to_address incoming_valid_message['Reply-to'] = self.example_email('othello') process_message(incoming_valid_message) # Hamlet is subscribed to this stream so should see the email message from Othello. message = most_recent_message(user_profile) self.assertEqual(message.content, "TestStreamEmailMessages Body") self.assertEqual(get_display_recipient(message.recipient), stream.name) self.assertEqual(message.topic_name(), incoming_valid_message['Subject']) def test_receive_stream_email_messages_blank_subject_success(self) -> None: user_profile = self.example_user('hamlet') self.login(user_profile.email) self.subscribe(user_profile, "Denmark") stream = get_stream("Denmark", user_profile.realm) stream_to_address = encode_email_address(stream) incoming_valid_message = MIMEText('TestStreamEmailMessages Body') # type: Any # https://github.com/python/typeshed/issues/275 incoming_valid_message['Subject'] = '' incoming_valid_message['From'] = self.example_email('hamlet') incoming_valid_message['To'] = stream_to_address incoming_valid_message['Reply-to'] = self.example_email('othello') process_message(incoming_valid_message) # Hamlet is subscribed to this stream so should see the email message from Othello. message = most_recent_message(user_profile) self.assertEqual(message.content, "TestStreamEmailMessages Body") self.assertEqual(get_display_recipient(message.recipient), stream.name) self.assertEqual(message.topic_name(), "(no topic)") def test_receive_private_stream_email_messages_success(self) -> None: user_profile = self.example_user('hamlet') self.login(user_profile.email) self.make_stream("private_stream", invite_only=True) self.subscribe(user_profile, "private_stream") stream = get_stream("private_stream", user_profile.realm) stream_to_address = encode_email_address(stream) incoming_valid_message = MIMEText('TestStreamEmailMessages Body') # type: Any # https://github.com/python/typeshed/issues/275 incoming_valid_message['Subject'] = 'TestStreamEmailMessages Subject' incoming_valid_message['From'] = self.example_email('hamlet') incoming_valid_message['To'] = stream_to_address incoming_valid_message['Reply-to'] = self.example_email('othello') process_message(incoming_valid_message) # Hamlet is subscribed to this stream so should see the email message from Othello. message = most_recent_message(user_profile) self.assertEqual(message.content, "TestStreamEmailMessages Body") self.assertEqual(get_display_recipient(message.recipient), stream.name) self.assertEqual(message.topic_name(), incoming_valid_message['Subject']) class TestStreamEmailMessagesEmptyBody(ZulipTestCase): def test_receive_stream_email_messages_empty_body(self) -> None: # build dummy messages for stream # test message with empty body is not sent user_profile = self.example_user('hamlet') self.login(user_profile.email) self.subscribe(user_profile, "Denmark") stream = get_stream("Denmark", user_profile.realm) stream_to_address = encode_email_address(stream) headers = {} headers['Reply-To'] = self.example_email('othello') # empty body incoming_valid_message = MIMEText('') # type: Any # https://github.com/python/typeshed/issues/275 incoming_valid_message['Subject'] = 'TestStreamEmailMessages Subject' incoming_valid_message['From'] = self.example_email('hamlet') incoming_valid_message['To'] = stream_to_address incoming_valid_message['Reply-to'] = self.example_email('othello') exception_message = "" debug_info = {} # type: Dict[str, Any] # process_message eats the exception & logs an error which can't be parsed here # so calling process_stream_message directly try: process_stream_message(incoming_valid_message['To'], incoming_valid_message['Subject'], incoming_valid_message, debug_info) except ZulipEmailForwardError as e: # empty body throws exception exception_message = str(e) self.assertEqual(exception_message, "Unable to find plaintext or HTML message body") class TestMissedPersonalMessageEmailMessages(ZulipTestCase): def test_receive_missed_personal_message_email_messages(self) -> None: # build dummy messages for missed messages email reply # have Hamlet send Othello a PM. Othello will reply via email # Hamlet will receive the message. email = self.example_email('hamlet') self.login(email) result = self.client_post("/json/messages", {"type": "private", "content": "test_receive_missed_message_email_messages", "client": "test suite", "to": self.example_email('othello')}) self.assert_json_success(result) user_profile = self.example_user('othello') usermessage = most_recent_usermessage(user_profile) # we don't want to send actual emails but we do need to create and store the # token for looking up who did reply. mm_address = create_missed_message_address(user_profile, usermessage.message) incoming_valid_message = MIMEText('TestMissedMessageEmailMessages Body') # type: Any # https://github.com/python/typeshed/issues/275 incoming_valid_message['Subject'] = 'TestMissedMessageEmailMessages Subject' incoming_valid_message['From'] = self.example_email('othello') incoming_valid_message['To'] = mm_address incoming_valid_message['Reply-to'] = self.example_email('othello') process_message(incoming_valid_message) # self.login(self.example_email("hamlet")) # confirm that Hamlet got the message user_profile = self.example_user('hamlet') message = most_recent_message(user_profile) self.assertEqual(message.content, "TestMissedMessageEmailMessages Body") self.assertEqual(message.sender, self.example_user('othello')) self.assertEqual(message.recipient.id, user_profile.id) self.assertEqual(message.recipient.type, Recipient.PERSONAL) class TestMissedHuddleMessageEmailMessages(ZulipTestCase): def test_receive_missed_huddle_message_email_messages(self) -> None: # build dummy messages for missed messages email reply # have Othello send Iago and Cordelia a PM. Cordelia will reply via email # Iago and Othello will receive the message. email = self.example_email('othello') self.login(email) result = self.client_post("/json/messages", {"type": "private", "content": "test_receive_missed_message_email_messages", "client": "test suite", "to": ujson.dumps([self.example_email('cordelia'), self.example_email('iago')])}) self.assert_json_success(result) user_profile = self.example_user('cordelia') usermessage = most_recent_usermessage(user_profile) # we don't want to send actual emails but we do need to create and store the # token for looking up who did reply. mm_address = create_missed_message_address(user_profile, usermessage.message) incoming_valid_message = MIMEText('TestMissedHuddleMessageEmailMessages Body') # type: Any # https://github.com/python/typeshed/issues/275 incoming_valid_message['Subject'] = 'TestMissedHuddleMessageEmailMessages Subject' incoming_valid_message['From'] = self.example_email('cordelia') incoming_valid_message['To'] = mm_address incoming_valid_message['Reply-to'] = self.example_email('cordelia') process_message(incoming_valid_message) # Confirm Iago received the message. user_profile = self.example_user('iago') message = most_recent_message(user_profile) self.assertEqual(message.content, "TestMissedHuddleMessageEmailMessages Body") self.assertEqual(message.sender, self.example_user('cordelia')) self.assertEqual(message.recipient.type, Recipient.HUDDLE) # Confirm Othello received the message. user_profile = self.example_user('othello') message = most_recent_message(user_profile) self.assertEqual(message.content, "TestMissedHuddleMessageEmailMessages Body") self.assertEqual(message.sender, self.example_user('cordelia')) self.assertEqual(message.recipient.type, Recipient.HUDDLE) class TestEmptyGatewaySetting(ZulipTestCase): def test_missed_message(self) -> None: email = self.example_email('othello') self.login(email) result = self.client_post("/json/messages", {"type": "private", "content": "test_receive_missed_message_email_messages", "client": "test suite", "to": ujson.dumps([self.example_email('cordelia'), self.example_email('iago')])}) self.assert_json_success(result) user_profile = self.example_user('cordelia') usermessage = most_recent_usermessage(user_profile) with self.settings(EMAIL_GATEWAY_PATTERN=''): mm_address = create_missed_message_address(user_profile, usermessage.message) self.assertEqual(mm_address, FromAddress.NOREPLY) def test_encode_email_addr(self) -> None: stream = get_stream("Denmark", get_realm("zulip")) with self.settings(EMAIL_GATEWAY_PATTERN=''): test_address = encode_email_address(stream) self.assertEqual(test_address, '') class TestReplyExtraction(ZulipTestCase): def test_reply_is_extracted_from_plain(self) -> None: # build dummy messages for stream # test valid incoming stream message is processed properly email = self.example_email('hamlet') self.login(email) user_profile = self.example_user('hamlet') self.subscribe(user_profile, "Denmark") stream = get_stream("Denmark", user_profile.realm) stream_to_address = encode_email_address(stream) text = """Reply -----Original Message----- Quote""" incoming_valid_message = MIMEText(text) # type: Any # https://github.com/python/typeshed/issues/275 incoming_valid_message['Subject'] = 'TestStreamEmailMessages Subject' incoming_valid_message['From'] = self.example_email('hamlet') incoming_valid_message['To'] = stream_to_address incoming_valid_message['Reply-to'] = self.example_email('othello') process_message(incoming_valid_message) # Hamlet is subscribed to this stream so should see the email message from Othello. message = most_recent_message(user_profile) self.assertEqual(message.content, "Reply") def test_reply_is_extracted_from_html(self) -> None: # build dummy messages for stream # test valid incoming stream message is processed properly email = self.example_email('hamlet') self.login(email) user_profile = self.example_user('hamlet') self.subscribe(user_profile, "Denmark") stream = get_stream("Denmark", user_profile.realm) stream_to_address = encode_email_address(stream) html = """ <html> <body> <p>Reply</p> <blockquote> <div> On 11-Apr-2011, at 6:54 PM, Bob &lt;bob@example.com&gt; wrote: </div> <div> Quote </div> </blockquote> </body> </html> """ incoming_valid_message = MIMEText(html, 'html') # type: Any # https://github.com/python/typeshed/issues/275 incoming_valid_message['Subject'] = 'TestStreamEmailMessages Subject' incoming_valid_message['From'] = self.example_email('hamlet') incoming_valid_message['To'] = stream_to_address incoming_valid_message['Reply-to'] = self.example_email('othello') process_message(incoming_valid_message) # Hamlet is subscribed to this stream so should see the email message from Othello. message = most_recent_message(user_profile) self.assertEqual(message.content, 'Reply') class TestScriptMTA(ZulipTestCase): def test_success(self) -> None: script = os.path.join(os.path.dirname(__file__), '../../scripts/lib/email-mirror-postfix') sender = self.example_email('hamlet') stream = get_stream("Denmark", get_realm("zulip")) stream_to_address = encode_email_address(stream) mail_template = self.fixture_data('simple.txt', type='email') mail = mail_template.format(stream_to_address=stream_to_address, sender=sender) read_pipe, write_pipe = os.pipe() os.write(write_pipe, mail.encode()) os.close(write_pipe) subprocess.check_call( [script, '-r', stream_to_address, '-s', settings.SHARED_SECRET, '-t'], stdin=read_pipe) def test_error_no_recipient(self) -> None: script = os.path.join(os.path.dirname(__file__), '../../scripts/lib/email-mirror-postfix') sender = self.example_email('hamlet') stream = get_stream("Denmark", get_realm("zulip")) stream_to_address = encode_email_address(stream) mail_template = self.fixture_data('simple.txt', type='email') mail = mail_template.format(stream_to_address=stream_to_address, sender=sender) read_pipe, write_pipe = os.pipe() os.write(write_pipe, mail.encode()) os.close(write_pipe) success_call = True try: subprocess.check_output([script, '-s', settings.SHARED_SECRET, '-t'], stdin=read_pipe) except subprocess.CalledProcessError as e: self.assertEqual( e.output, b'5.1.1 Bad destination mailbox address: No missed message email address.\n' ) self.assertEqual(e.returncode, 67) success_call = False self.assertFalse(success_call) class TestEmailMirrorTornadoView(ZulipTestCase): def send_private_message(self) -> str: email = self.example_email('othello') self.login(email) result = self.client_post( "/json/messages", { "type": "private", "content": "test_receive_missed_message_email_messages", "client": "test suite", "to": ujson.dumps([self.example_email('cordelia'), self.example_email('iago')]) }) self.assert_json_success(result) user_profile = self.example_user('cordelia') user_message = most_recent_usermessage(user_profile) return create_missed_message_address(user_profile, user_message.message) @mock.patch('zerver.lib.email_mirror.queue_json_publish') def send_offline_message(self, to_address: str, sender: str, mock_queue_json_publish: mock.Mock) -> HttpResponse: mail_template = self.fixture_data('simple.txt', type='email') mail = mail_template.format(stream_to_address=to_address, sender=sender) def check_queue_json_publish(queue_name: str, event: Union[Mapping[str, Any], str], processor: Optional[Callable[[Any], None]]=None) -> None: self.assertEqual(queue_name, "email_mirror") self.assertEqual(event, {"rcpt_to": to_address, "message": mail}) mock_queue_json_publish.side_effect = check_queue_json_publish request_data = { "recipient": to_address, "msg_text": mail } post_data = dict( data=ujson.dumps(request_data), secret=settings.SHARED_SECRET ) return self.client_post('/email_mirror_message', post_data) def test_success_stream(self) -> None: stream = get_stream("Denmark", get_realm("zulip")) stream_to_address = encode_email_address(stream) result = self.send_offline_message(stream_to_address, self.example_email('hamlet')) self.assert_json_success(result) def test_error_to_stream_with_wrong_address(self) -> None: stream = get_stream("Denmark", get_realm("zulip")) stream_to_address = encode_email_address(stream) stream_to_address = stream_to_address.replace("Denmark", "Wrong_stream") result = self.send_offline_message(stream_to_address, self.example_email('hamlet')) self.assert_json_error( result, "5.1.1 Bad destination mailbox address: " "Please use the address specified in your Streams page.") def test_success_to_private(self) -> None: mm_address = self.send_private_message() result = self.send_offline_message(mm_address, self.example_email('cordelia')) self.assert_json_success(result) def test_using_mm_address_twice(self) -> None: mm_address = self.send_private_message() self.send_offline_message(mm_address, self.example_email('cordelia')) result = self.send_offline_message(mm_address, self.example_email('cordelia')) self.assert_json_error( result, "5.1.1 Bad destination mailbox address: Bad or expired missed message address.") def test_wrong_missed_email_private_message(self) -> None: self.send_private_message() mm_address = 'mm' + ('x' * 32) + '@testserver' result = self.send_offline_message(mm_address, self.example_email('cordelia')) self.assert_json_error( result, "5.1.1 Bad destination mailbox address: Bad or expired missed message address.")
[ "str", "str", "str", "mock.Mock", "str", "Union[Mapping[str, Any], str]" ]
[ 2629, 20237, 20250, 20309, 20538, 20587 ]
[ 2632, 20240, 20253, 20318, 20541, 20616 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_embedded_bot_system.py
# -*- coding: utf-8 -*- from unittest import mock from mock import patch from typing import Any, Dict, Tuple, Optional from zerver.lib.bot_lib import EmbeddedBotQuitException, EmbeddedBotHandler from zerver.lib.test_classes import ZulipTestCase from zerver.models import ( UserProfile, Recipient, get_display_recipient, get_service_profile, get_user, get_realm ) import ujson class TestEmbeddedBotMessaging(ZulipTestCase): def setUp(self) -> None: self.user_profile = self.example_user("othello") self.bot_profile = self.create_test_bot('embedded', self.user_profile, full_name='Embedded bot', bot_type=UserProfile.EMBEDDED_BOT, service_name='helloworld', config_data=ujson.dumps({'foo': 'bar'})) def test_pm_to_embedded_bot(self) -> None: assert self.bot_profile is not None self.send_personal_message(self.user_profile.email, self.bot_profile.email, content="help") last_message = self.get_last_message() self.assertEqual(last_message.content, "beep boop") self.assertEqual(last_message.sender_id, self.bot_profile.id) display_recipient = get_display_recipient(last_message.recipient) # The next two lines error on mypy because the display_recipient is of type Union[str, List[Dict[str, Any]]]. # In this case, we know that display_recipient will be of type List[Dict[str, Any]]. # Otherwise this test will error, which is wanted behavior anyway. self.assert_length(display_recipient, 1) # type: ignore self.assertEqual(display_recipient[0]['email'], self.user_profile.email) # type: ignore def test_stream_message_to_embedded_bot(self) -> None: assert self.bot_profile is not None self.send_stream_message(self.user_profile.email, "Denmark", content="@**{}** foo".format(self.bot_profile.full_name), topic_name="bar") last_message = self.get_last_message() self.assertEqual(last_message.content, "beep boop") self.assertEqual(last_message.sender_id, self.bot_profile.id) self.assertEqual(last_message.topic_name(), "bar") display_recipient = get_display_recipient(last_message.recipient) self.assertEqual(display_recipient, "Denmark") def test_stream_message_not_to_embedded_bot(self) -> None: self.send_stream_message(self.user_profile.email, "Denmark", content="foo", topic_name="bar") last_message = self.get_last_message() self.assertEqual(last_message.content, "foo") def test_message_to_embedded_bot_with_initialize(self) -> None: assert self.bot_profile is not None with patch('zulip_bots.bots.helloworld.helloworld.HelloWorldHandler.initialize', create=True) as mock_initialize: self.send_stream_message(self.user_profile.email, "Denmark", content="@**{}** foo".format(self.bot_profile.full_name), topic_name="bar") mock_initialize.assert_called_once() def test_embedded_bot_quit_exception(self) -> None: assert self.bot_profile is not None with patch('zulip_bots.bots.helloworld.helloworld.HelloWorldHandler.handle_message', side_effect=EmbeddedBotQuitException("I'm quitting!")): with patch('logging.warning') as mock_logging: self.send_stream_message(self.user_profile.email, "Denmark", content="@**{}** foo".format(self.bot_profile.full_name), topic_name="bar") mock_logging.assert_called_once_with("I'm quitting!") class TestEmbeddedBotFailures(ZulipTestCase): def test_message_embedded_bot_with_invalid_service(self) -> None: user_profile = self.example_user("othello") self.create_test_bot(short_name='embedded', user_profile=user_profile, bot_type=UserProfile.EMBEDDED_BOT, service_name='helloworld') bot_profile = get_user("embedded-bot@zulip.testserver", get_realm('zulip')) service_profile = get_service_profile(bot_profile.id, 'helloworld') service_profile.name = 'invalid' service_profile.save() with patch('logging.error') as logging_error_mock: self.send_stream_message(user_profile.email, "Denmark", content="@**{}** foo".format(bot_profile.full_name), topic_name="bar") logging_error_mock.assert_called_once_with( "Error: User {} has bot with invalid embedded bot service invalid".format(bot_profile.id))
[]
[]
[]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_event_queue.py
import mock import time import ujson from django.http import HttpRequest, HttpResponse from typing import Any, Callable, Dict, Tuple from zerver.lib.actions import do_mute_topic, do_change_subscription_property from zerver.lib.test_classes import ZulipTestCase from zerver.lib.test_helpers import POSTRequestMock from zerver.models import Recipient, Stream, Subscription, UserProfile, get_stream from zerver.tornado.event_queue import maybe_enqueue_notifications, \ allocate_client_descriptor, process_message_event, \ get_client_descriptor, missedmessage_hook, persistent_queue_filename from zerver.tornado.views import get_events class MissedMessageNotificationsTest(ZulipTestCase): """Tests the logic for when missed-message notifications should be triggered, based on user settings""" def check_will_notify(self, *args: Any, **kwargs: Any) -> Tuple[str, str]: email_notice = None mobile_notice = None with mock.patch("zerver.tornado.event_queue.queue_json_publish") as mock_queue_publish: notified = maybe_enqueue_notifications(*args, **kwargs) for entry in mock_queue_publish.call_args_list: args = entry[0] if args[0] == "missedmessage_mobile_notifications": mobile_notice = args[1] if args[0] == "missedmessage_emails": email_notice = args[1] # Now verify the return value matches the queue actions if email_notice: self.assertTrue(notified['email_notified']) else: self.assertFalse(notified.get('email_notified', False)) if mobile_notice: self.assertTrue(notified['push_notified']) else: self.assertFalse(notified.get('push_notified', False)) return email_notice, mobile_notice def test_enqueue_notifications(self) -> None: user_profile = self.example_user("hamlet") message_id = 32 # Boring message doesn't send a notice email_notice, mobile_notice = self.check_will_notify( user_profile.id, message_id, private_message=False, mentioned=False, stream_push_notify=False, stream_email_notify=False, stream_name=None, always_push_notify=False, idle=True, already_notified={}) self.assertTrue(email_notice is None) self.assertTrue(mobile_notice is None) # Private message sends a notice email_notice, mobile_notice = self.check_will_notify( user_profile.id, message_id, private_message=True, mentioned=False, stream_push_notify=False, stream_email_notify=True, stream_name=None, always_push_notify=False, idle=True, already_notified={}) self.assertTrue(email_notice is not None) self.assertTrue(mobile_notice is not None) # Private message won't double-send either notice if we've # already sent notices before. email_notice, mobile_notice = self.check_will_notify( user_profile.id, message_id, private_message=True, mentioned=False, stream_push_notify=False, stream_email_notify=False, stream_name=None, always_push_notify=False, idle=True, already_notified={ 'push_notified': True, 'email_notified': False, }) self.assertTrue(email_notice is not None) self.assertTrue(mobile_notice is None) email_notice, mobile_notice = self.check_will_notify( user_profile.id, message_id, private_message=True, mentioned=False, stream_push_notify=False, stream_email_notify=False, stream_name=None, always_push_notify=False, idle=True, already_notified={ 'push_notified': False, 'email_notified': True, }) self.assertTrue(email_notice is None) self.assertTrue(mobile_notice is not None) # Mention sends a notice email_notice, mobile_notice = self.check_will_notify( user_profile.id, message_id, private_message=False, mentioned=True, stream_push_notify=False, stream_email_notify=False, stream_name=None, always_push_notify=False, idle=True, already_notified={}) self.assertTrue(email_notice is not None) self.assertTrue(mobile_notice is not None) # stream_push_notify pushes but doesn't email email_notice, mobile_notice = self.check_will_notify( user_profile.id, message_id, private_message=False, mentioned=False, stream_push_notify=True, stream_email_notify=False, stream_name="Denmark", always_push_notify=False, idle=True, already_notified={}) self.assertTrue(email_notice is None) self.assertTrue(mobile_notice is not None) # stream_email_notify emails but doesn't push email_notice, mobile_notice = self.check_will_notify( user_profile.id, message_id, private_message=False, mentioned=False, stream_push_notify=False, stream_email_notify=True, stream_name="Denmark", always_push_notify=False, idle=True, already_notified={}) self.assertTrue(email_notice is not None) self.assertTrue(mobile_notice is None) # Private message doesn't send a notice if not idle email_notice, mobile_notice = self.check_will_notify( user_profile.id, message_id, private_message=True, mentioned=False, stream_push_notify=False, stream_email_notify=True, stream_name=None, always_push_notify=False, idle=False, already_notified={}) self.assertTrue(email_notice is None) self.assertTrue(mobile_notice is None) # Private message sends push but not email if not idle but always_push_notify email_notice, mobile_notice = self.check_will_notify( user_profile.id, message_id, private_message=True, mentioned=False, stream_push_notify=False, stream_email_notify=True, stream_name=None, always_push_notify=True, idle=False, already_notified={}) self.assertTrue(email_notice is None) self.assertTrue(mobile_notice is not None) def tornado_call(self, view_func: Callable[[HttpRequest, UserProfile], HttpResponse], user_profile: UserProfile, post_data: Dict[str, Any]) -> HttpResponse: request = POSTRequestMock(post_data, user_profile) return view_func(request, user_profile) def test_stream_watchers(self) -> None: ''' We used to have a bug with stream_watchers, where we set their flags to None. ''' cordelia = self.example_user('cordelia') hamlet = self.example_user('hamlet') realm = hamlet.realm stream_name = 'Denmark' self.unsubscribe(hamlet, stream_name) queue_data = dict( all_public_streams=True, apply_markdown=True, client_gravatar=True, client_type_name='home grown api program', event_types=['message'], last_connection_time=time.time(), queue_timeout=0, realm_id=realm.id, user_profile_id=hamlet.id, ) client = allocate_client_descriptor(queue_data) self.send_stream_message(cordelia.email, stream_name) self.assertEqual(len(client.event_queue.contents()), 1) # This next line of code should silently succeed and basically do # nothing under the covers. This test is here to prevent a bug # from re-appearing. missedmessage_hook( user_profile_id=hamlet.id, client=client, last_for_client=True, ) def test_end_to_end_missedmessage_hook(self) -> None: """Tests what arguments missedmessage_hook passes into maybe_enqueue_notifications. Combined with the previous test, this ensures that the missedmessage_hook is correct""" user_profile = self.example_user('hamlet') email = user_profile.email self.login(email) def change_subscription_properties(user_profile: UserProfile, stream: Stream, sub: Subscription, properties: Dict[str, bool]) -> None: for property_name, value in properties.items(): do_change_subscription_property(user_profile, sub, stream, property_name, value) result = self.tornado_call(get_events, user_profile, {"apply_markdown": ujson.dumps(True), "client_gravatar": ujson.dumps(True), "event_types": ujson.dumps(["message"]), "user_client": "website", "dont_block": ujson.dumps(True), }) self.assert_json_success(result) queue_id = ujson.loads(result.content)["queue_id"] client_descriptor = get_client_descriptor(queue_id) with mock.patch("zerver.tornado.event_queue.maybe_enqueue_notifications") as mock_enqueue: # To test the missed_message hook, we first need to send a message msg_id = self.send_stream_message(self.example_email("iago"), "Denmark") # Verify that nothing happens if you call it as not the # "last client descriptor", in which case the function # short-circuits, since the `missedmessage_hook` handler # for garbage-collection is only for the user's last queue. missedmessage_hook(user_profile.id, client_descriptor, False) mock_enqueue.assert_not_called() # Now verify that we called the appropriate enqueue function missedmessage_hook(user_profile.id, client_descriptor, True) mock_enqueue.assert_called_once() args_list = mock_enqueue.call_args_list[0][0] self.assertEqual(args_list, (user_profile.id, msg_id, False, False, False, False, "Denmark", False, True, {'email_notified': False, 'push_notified': False})) # Clear the event queue, before repeating with a private message client_descriptor.event_queue.pop() self.assertTrue(client_descriptor.event_queue.empty()) msg_id = self.send_personal_message(self.example_email("iago"), email) with mock.patch("zerver.tornado.event_queue.maybe_enqueue_notifications") as mock_enqueue: missedmessage_hook(user_profile.id, client_descriptor, True) mock_enqueue.assert_called_once() args_list = mock_enqueue.call_args_list[0][0] self.assertEqual(args_list, (user_profile.id, msg_id, True, False, False, False, None, False, True, {'email_notified': True, 'push_notified': True})) # Clear the event queue, now repeat with a mention client_descriptor.event_queue.pop() self.assertTrue(client_descriptor.event_queue.empty()) msg_id = self.send_stream_message(self.example_email("iago"), "Denmark", content="@**King Hamlet** what's up?") with mock.patch("zerver.tornado.event_queue.maybe_enqueue_notifications") as mock_enqueue: # Clear the event queue, before repeating with a private message missedmessage_hook(user_profile.id, client_descriptor, True) mock_enqueue.assert_called_once() args_list = mock_enqueue.call_args_list[0][0] self.assertEqual(args_list, (user_profile.id, msg_id, False, True, False, False, "Denmark", False, True, {'email_notified': True, 'push_notified': True})) stream = get_stream("Denmark", user_profile.realm) sub = Subscription.objects.get(user_profile=user_profile, recipient__type=Recipient.STREAM, recipient__type_id=stream.id) # Clear the event queue, now repeat with stream message with stream_push_notify change_subscription_properties(user_profile, stream, sub, {'push_notifications': True}) client_descriptor.event_queue.pop() self.assertTrue(client_descriptor.event_queue.empty()) msg_id = self.send_stream_message(self.example_email("iago"), "Denmark", content="what's up everyone?") with mock.patch("zerver.tornado.event_queue.maybe_enqueue_notifications") as mock_enqueue: # Clear the event queue, before repeating with a private message missedmessage_hook(user_profile.id, client_descriptor, True) mock_enqueue.assert_called_once() args_list = mock_enqueue.call_args_list[0][0] self.assertEqual(args_list, (user_profile.id, msg_id, False, False, True, False, "Denmark", False, True, {'email_notified': False, 'push_notified': False})) # Clear the event queue, now repeat with stream message with stream_email_notify change_subscription_properties(user_profile, stream, sub, {'push_notifications': False, 'email_notifications': True}) client_descriptor.event_queue.pop() self.assertTrue(client_descriptor.event_queue.empty()) msg_id = self.send_stream_message(self.example_email("iago"), "Denmark", content="what's up everyone?") with mock.patch("zerver.tornado.event_queue.maybe_enqueue_notifications") as mock_enqueue: # Clear the event queue, before repeating with a private message missedmessage_hook(user_profile.id, client_descriptor, True) mock_enqueue.assert_called_once() args_list = mock_enqueue.call_args_list[0][0] self.assertEqual(args_list, (user_profile.id, msg_id, False, False, False, True, "Denmark", False, True, {'email_notified': False, 'push_notified': False})) # Clear the event queue, now repeat with stream message with stream_push_notify # on a muted topic, which we should not push notify for change_subscription_properties(user_profile, stream, sub, {'push_notifications': True, 'email_notifications': False}) client_descriptor.event_queue.pop() self.assertTrue(client_descriptor.event_queue.empty()) do_mute_topic(user_profile, stream, sub.recipient, "mutingtest") msg_id = self.send_stream_message(self.example_email("iago"), "Denmark", content="what's up everyone?", topic_name="mutingtest") with mock.patch("zerver.tornado.event_queue.maybe_enqueue_notifications") as mock_enqueue: # Clear the event queue, before repeating with a private message missedmessage_hook(user_profile.id, client_descriptor, True) mock_enqueue.assert_called_once() args_list = mock_enqueue.call_args_list[0][0] self.assertEqual(args_list, (user_profile.id, msg_id, False, False, False, False, "Denmark", False, True, {'email_notified': False, 'push_notified': False})) # Clear the event queue, now repeat with stream message with stream_email_notify # on a muted stream, which we should not email notify for change_subscription_properties(user_profile, stream, sub, {'push_notifications': False, 'email_notifications': True}) client_descriptor.event_queue.pop() self.assertTrue(client_descriptor.event_queue.empty()) change_subscription_properties(user_profile, stream, sub, {'in_home_view': False}) msg_id = self.send_stream_message(self.example_email("iago"), "Denmark", content="what's up everyone?") with mock.patch("zerver.tornado.event_queue.maybe_enqueue_notifications") as mock_enqueue: # Clear the event queue, before repeating with a private message missedmessage_hook(user_profile.id, client_descriptor, True) mock_enqueue.assert_called_once() args_list = mock_enqueue.call_args_list[0][0] self.assertEqual(args_list, (user_profile.id, msg_id, False, False, False, False, "Denmark", False, True, {'email_notified': False, 'push_notified': False})) # Clean up the state we just changed (not necessary unless we add more test code below) change_subscription_properties(user_profile, stream, sub, {'push_notifications': True, 'in_home_view': True}) class FileReloadLogicTest(ZulipTestCase): def test_persistent_queue_filename(self) -> None: with self.settings(JSON_PERSISTENT_QUEUE_FILENAME_PATTERN="/var/tmp/event_queues%s.json"): self.assertEqual(persistent_queue_filename(9993), "/var/tmp/event_queues.json") self.assertEqual(persistent_queue_filename(9993, last=True), "/var/tmp/event_queues.json.last") with self.settings(JSON_PERSISTENT_QUEUE_FILENAME_PATTERN="/var/tmp/event_queues%s.json", TORNADO_PROCESSES=4): self.assertEqual(persistent_queue_filename(9993), "/var/tmp/event_queues.9993.json") self.assertEqual(persistent_queue_filename(9993, last=True), "/var/tmp/event_queues.9993.last.json")
[ "Any", "Any", "Callable[[HttpRequest, UserProfile], HttpResponse]", "UserProfile", "Dict[str, Any]", "UserProfile", "Stream", "Subscription", "Dict[str, bool]" ]
[ 847, 862, 6256, 6343, 6367, 8167, 8188, 8201, 8270 ]
[ 850, 865, 6306, 6354, 6381, 8178, 8194, 8213, 8285 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_events.py
# -*- coding: utf-8 -*- # See https://zulip.readthedocs.io/en/latest/subsystems/events-system.html for # high-level documentation on how this system works. from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union import os import shutil import sys from django.conf import settings from django.http import HttpRequest, HttpResponse from django.test import TestCase from django.utils.timezone import now as timezone_now from io import StringIO from zerver.models import ( get_client, get_realm, get_stream_recipient, get_stream, get_user, Message, RealmDomain, Recipient, UserMessage, UserPresence, UserProfile, Realm, Subscription, Stream, flush_per_request_caches, UserGroup, Service, Attachment, PreregistrationUser, ) from zerver.lib.actions import ( try_update_realm_custom_profile_field, bulk_add_subscriptions, bulk_remove_subscriptions, check_add_realm_emoji, check_send_message, check_send_typing_notification, do_add_alert_words, do_add_default_stream, do_add_reaction, do_add_reaction_legacy, do_add_realm_domain, do_add_realm_filter, do_add_streams_to_default_stream_group, do_add_submessage, do_change_avatar_fields, do_change_bot_owner, do_change_default_all_public_streams, do_change_default_events_register_stream, do_change_default_sending_stream, do_change_default_stream_group_description, do_change_default_stream_group_name, do_change_full_name, do_change_icon_source, do_change_is_admin, do_change_notification_settings, do_change_realm_domain, do_change_stream_description, do_change_subscription_property, do_create_user, do_create_default_stream_group, do_deactivate_stream, do_deactivate_user, do_delete_message, do_invite_users, do_mark_hotspot_as_read, do_mute_topic, do_reactivate_user, do_regenerate_api_key, do_remove_alert_words, do_remove_default_stream, do_remove_default_stream_group, do_remove_reaction, do_remove_reaction_legacy, do_remove_realm_domain, do_remove_realm_emoji, do_remove_realm_filter, do_remove_streams_from_default_stream_group, do_rename_stream, do_revoke_user_invite, do_set_realm_authentication_methods, do_set_realm_message_editing, do_set_realm_property, do_set_user_display_setting, do_set_realm_notifications_stream, do_set_realm_signup_notifications_stream, do_unmute_topic, do_update_embedded_data, do_update_message, do_update_message_flags, do_update_outgoing_webhook_service, do_update_pointer, do_update_user_presence, get_typing_user_profiles, log_event, lookup_default_stream_groups, notify_attachment_update, notify_realm_custom_profile_fields, check_add_user_group, do_update_user_group_name, do_update_user_group_description, bulk_add_members_to_user_group, remove_members_from_user_group, check_delete_user_group, do_update_user_custom_profile_data, ) from zerver.lib.events import ( apply_events, fetch_initial_state_data, ) from zerver.lib.message import ( aggregate_unread_data, get_raw_unread_data, render_markdown, UnreadMessagesResult, ) from zerver.lib.test_helpers import POSTRequestMock, get_subscription, \ get_test_image_file, stub_event_queue_user_events, queries_captured from zerver.lib.test_classes import ( ZulipTestCase, ) from zerver.lib.test_runner import slow from zerver.lib.topic import ( ORIG_TOPIC, TOPIC_NAME, TOPIC_LINKS, ) from zerver.lib.topic_mutes import ( add_topic_mute, ) from zerver.lib.validator import ( check_bool, check_dict, check_dict_only, check_float, check_int, check_list, check_string, equals, check_none_or, Validator, check_url ) from zerver.lib.upload import upload_backend, attachment_url_to_path_id from zerver.lib.users import get_api_key from zerver.views.events_register import _default_all_public_streams, _default_narrow from zerver.tornado.event_queue import ( allocate_client_descriptor, clear_client_event_queues_for_testing, get_client_info_for_message_event, process_message_event, EventQueue, ) from zerver.tornado.views import get_events from collections import OrderedDict import mock import time import ujson class LogEventsTest(ZulipTestCase): def test_with_missing_event_log_dir_setting(self) -> None: with self.settings(EVENT_LOG_DIR=None): log_event(dict()) def test_log_event_mkdir(self) -> None: dir_name = 'var/test-log-dir' try: shutil.rmtree(dir_name) except OSError: # nocoverage # assume it doesn't exist already pass self.assertFalse(os.path.exists(dir_name)) with self.settings(EVENT_LOG_DIR=dir_name): event = {} # type: Dict[str, int] log_event(event) self.assertTrue(os.path.exists(dir_name)) class EventsEndpointTest(ZulipTestCase): def test_events_register_endpoint(self) -> None: # This test is intended to get minimal coverage on the # events_register code paths email = self.example_email("hamlet") with mock.patch('zerver.views.events_register.do_events_register', return_value={}): result = self.api_post(email, '/json/register') self.assert_json_success(result) with mock.patch('zerver.lib.events.request_event_queue', return_value=None): result = self.api_post(email, '/json/register') self.assert_json_error(result, "Could not allocate event queue") return_event_queue = '15:11' return_user_events = [] # type: (List[Any]) # Test that call is made to deal with a returning soft deactivated user. with mock.patch('zerver.lib.events.maybe_catch_up_soft_deactivated_user') as fa: with stub_event_queue_user_events(return_event_queue, return_user_events): result = self.api_post(email, '/json/register', dict(event_types=ujson.dumps(['pointer']))) self.assertEqual(fa.call_count, 1) with stub_event_queue_user_events(return_event_queue, return_user_events): result = self.api_post(email, '/json/register', dict(event_types=ujson.dumps(['pointer']))) self.assert_json_success(result) result_dict = result.json() self.assertEqual(result_dict['last_event_id'], -1) self.assertEqual(result_dict['queue_id'], '15:11') return_event_queue = '15:12' return_user_events = [ { 'id': 6, 'type': 'pointer', 'pointer': 15, } ] with stub_event_queue_user_events(return_event_queue, return_user_events): result = self.api_post(email, '/json/register', dict(event_types=ujson.dumps(['pointer']))) self.assert_json_success(result) result_dict = result.json() self.assertEqual(result_dict['last_event_id'], 6) self.assertEqual(result_dict['pointer'], 15) self.assertEqual(result_dict['queue_id'], '15:12') # Now test with `fetch_event_types` not matching the event return_event_queue = '15:13' with stub_event_queue_user_events(return_event_queue, return_user_events): result = self.api_post(email, '/json/register', dict(event_types=ujson.dumps(['pointer']), fetch_event_types=ujson.dumps(['message']))) self.assert_json_success(result) result_dict = result.json() self.assertEqual(result_dict['last_event_id'], 6) # Check that the message event types data is in there self.assertIn('max_message_id', result_dict) # Check that the pointer event types data is not in there self.assertNotIn('pointer', result_dict) self.assertEqual(result_dict['queue_id'], '15:13') # Now test with `fetch_event_types` matching the event with stub_event_queue_user_events(return_event_queue, return_user_events): result = self.api_post(email, '/json/register', dict(fetch_event_types=ujson.dumps(['pointer']), event_types=ujson.dumps(['message']))) self.assert_json_success(result) result_dict = result.json() self.assertEqual(result_dict['last_event_id'], 6) # Check that we didn't fetch the messages data self.assertNotIn('max_message_id', result_dict) # Check that the pointer data is in there, and is correctly # updated (presering our atomicity guaranteed), though of # course any future pointer events won't be distributed self.assertIn('pointer', result_dict) self.assertEqual(result_dict['pointer'], 15) self.assertEqual(result_dict['queue_id'], '15:13') def test_tornado_endpoint(self) -> None: # This test is mostly intended to get minimal coverage on # the /notify_tornado endpoint, so we can have 100% URL coverage, # but it does exercise a little bit of the codepath. post_data = dict( data=ujson.dumps( dict( event=dict( type='other' ), users=[self.example_user('hamlet').id], ), ), ) req = POSTRequestMock(post_data, user_profile=None) req.META['REMOTE_ADDR'] = '127.0.0.1' result = self.client_post_request('/notify_tornado', req) self.assert_json_error(result, 'Access denied', status_code=403) post_data['secret'] = settings.SHARED_SECRET req = POSTRequestMock(post_data, user_profile=None) req.META['REMOTE_ADDR'] = '127.0.0.1' result = self.client_post_request('/notify_tornado', req) self.assert_json_success(result) class GetEventsTest(ZulipTestCase): def tornado_call(self, view_func: Callable[[HttpRequest, UserProfile], HttpResponse], user_profile: UserProfile, post_data: Dict[str, Any]) -> HttpResponse: request = POSTRequestMock(post_data, user_profile) return view_func(request, user_profile) def test_get_events(self) -> None: user_profile = self.example_user('hamlet') email = user_profile.email recipient_user_profile = self.example_user('othello') recipient_email = recipient_user_profile.email self.login(email) result = self.tornado_call(get_events, user_profile, {"apply_markdown": ujson.dumps(True), "client_gravatar": ujson.dumps(True), "event_types": ujson.dumps(["message"]), "user_client": "website", "dont_block": ujson.dumps(True), }) self.assert_json_success(result) queue_id = ujson.loads(result.content)["queue_id"] recipient_result = self.tornado_call(get_events, recipient_user_profile, {"apply_markdown": ujson.dumps(True), "client_gravatar": ujson.dumps(True), "event_types": ujson.dumps(["message"]), "user_client": "website", "dont_block": ujson.dumps(True), }) self.assert_json_success(recipient_result) recipient_queue_id = ujson.loads(recipient_result.content)["queue_id"] result = self.tornado_call(get_events, user_profile, {"queue_id": queue_id, "user_client": "website", "last_event_id": -1, "dont_block": ujson.dumps(True), }) events = ujson.loads(result.content)["events"] self.assert_json_success(result) self.assert_length(events, 0) local_id = '10.01' check_send_message( sender=user_profile, client=get_client('whatever'), message_type_name='private', message_to=[recipient_email], topic_name=None, message_content='hello', local_id=local_id, sender_queue_id=queue_id, ) result = self.tornado_call(get_events, user_profile, {"queue_id": queue_id, "user_client": "website", "last_event_id": -1, "dont_block": ujson.dumps(True), }) events = ujson.loads(result.content)["events"] self.assert_json_success(result) self.assert_length(events, 1) self.assertEqual(events[0]["type"], "message") self.assertEqual(events[0]["message"]["sender_email"], email) self.assertEqual(events[0]["local_message_id"], local_id) self.assertEqual(events[0]["message"]["display_recipient"][0]["is_mirror_dummy"], False) self.assertEqual(events[0]["message"]["display_recipient"][1]["is_mirror_dummy"], False) last_event_id = events[0]["id"] local_id = '10.02' check_send_message( sender=user_profile, client=get_client('whatever'), message_type_name='private', message_to=[recipient_email], topic_name=None, message_content='hello', local_id=local_id, sender_queue_id=queue_id, ) result = self.tornado_call(get_events, user_profile, {"queue_id": queue_id, "user_client": "website", "last_event_id": last_event_id, "dont_block": ujson.dumps(True), }) events = ujson.loads(result.content)["events"] self.assert_json_success(result) self.assert_length(events, 1) self.assertEqual(events[0]["type"], "message") self.assertEqual(events[0]["message"]["sender_email"], email) self.assertEqual(events[0]["local_message_id"], local_id) # Test that the received message in the receiver's event queue # exists and does not contain a local id recipient_result = self.tornado_call(get_events, recipient_user_profile, {"queue_id": recipient_queue_id, "user_client": "website", "last_event_id": -1, "dont_block": ujson.dumps(True), }) recipient_events = ujson.loads(recipient_result.content)["events"] self.assert_json_success(recipient_result) self.assertEqual(len(recipient_events), 2) self.assertEqual(recipient_events[0]["type"], "message") self.assertEqual(recipient_events[0]["message"]["sender_email"], email) self.assertTrue("local_message_id" not in recipient_events[0]) self.assertEqual(recipient_events[1]["type"], "message") self.assertEqual(recipient_events[1]["message"]["sender_email"], email) self.assertTrue("local_message_id" not in recipient_events[1]) def test_get_events_narrow(self) -> None: user_profile = self.example_user('hamlet') email = user_profile.email self.login(email) def get_message(apply_markdown: bool, client_gravatar: bool) -> Dict[str, Any]: result = self.tornado_call( get_events, user_profile, dict( apply_markdown=ujson.dumps(apply_markdown), client_gravatar=ujson.dumps(client_gravatar), event_types=ujson.dumps(["message"]), narrow=ujson.dumps([["stream", "denmark"]]), user_client="website", dont_block=ujson.dumps(True), ) ) self.assert_json_success(result) queue_id = ujson.loads(result.content)["queue_id"] result = self.tornado_call(get_events, user_profile, {"queue_id": queue_id, "user_client": "website", "last_event_id": -1, "dont_block": ujson.dumps(True), }) events = ujson.loads(result.content)["events"] self.assert_json_success(result) self.assert_length(events, 0) self.send_personal_message(email, self.example_email("othello"), "hello") self.send_stream_message(email, "Denmark", "**hello**") result = self.tornado_call(get_events, user_profile, {"queue_id": queue_id, "user_client": "website", "last_event_id": -1, "dont_block": ujson.dumps(True), }) events = ujson.loads(result.content)["events"] self.assert_json_success(result) self.assert_length(events, 1) self.assertEqual(events[0]["type"], "message") return events[0]['message'] message = get_message(apply_markdown=False, client_gravatar=False) self.assertEqual(message["display_recipient"], "Denmark") self.assertEqual(message["content"], "**hello**") self.assertIn('gravatar.com', message["avatar_url"]) message = get_message(apply_markdown=True, client_gravatar=False) self.assertEqual(message["display_recipient"], "Denmark") self.assertEqual(message["content"], "<p><strong>hello</strong></p>") self.assertIn('gravatar.com', message["avatar_url"]) message = get_message(apply_markdown=False, client_gravatar=True) self.assertEqual(message["display_recipient"], "Denmark") self.assertEqual(message["content"], "**hello**") self.assertEqual(message["avatar_url"], None) message = get_message(apply_markdown=True, client_gravatar=True) self.assertEqual(message["display_recipient"], "Denmark") self.assertEqual(message["content"], "<p><strong>hello</strong></p>") self.assertEqual(message["avatar_url"], None) class EventsRegisterTest(ZulipTestCase): def setUp(self) -> None: super().setUp() self.user_profile = self.example_user('hamlet') def create_bot(self, email: str, **extras: Any) -> Optional[UserProfile]: return self.create_test_bot(email, self.user_profile, **extras) def realm_bot_schema(self, field_name: str, check: Validator) -> Validator: return self.check_events_dict([ ('type', equals('realm_bot')), ('op', equals('update')), ('bot', check_dict_only([ ('email', check_string), ('user_id', check_int), (field_name, check), ])), ]) 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 run multiple tests within a single test function. ''' clear_client_event_queues_for_testing() client = allocate_client_descriptor( dict(user_profile_id = self.user_profile.id, user_profile_email = self.user_profile.email, realm_id = self.user_profile.realm_id, event_types = event_types, client_type_name = "website", apply_markdown = True, client_gravatar = client_gravatar, all_public_streams = False, queue_timeout = 600, last_connection_time = time.time(), narrow = []) ) # hybrid_state = initial fetch state + re-applying events triggered by our action # normal_state = do action then fetch at the end (the "normal" code path) hybrid_state = fetch_initial_state_data( self.user_profile, event_types, "", client_gravatar=True, include_subscribers=include_subscribers ) action() events = client.event_queue.contents() self.assertTrue(len(events) == num_events) before = ujson.dumps(hybrid_state) apply_events(hybrid_state, events, self.user_profile, client_gravatar=True, include_subscribers=include_subscribers) after = ujson.dumps(hybrid_state) if state_change_expected: if before == after: print(events) # nocoverage raise AssertionError('Test does not exercise enough code -- events do not change state.') else: if before != after: raise AssertionError('Test is invalid--state actually does change here.') normal_state = fetch_initial_state_data( self.user_profile, event_types, "", client_gravatar=True, include_subscribers=include_subscribers ) self.match_states(hybrid_state, normal_state, events) return events def assert_on_error(self, error: Optional[str]) -> None: if error: raise AssertionError(error) def match_states(self, state1: Dict[str, Any], state2: Dict[str, Any], events: List[Dict[str, Any]]) -> None: def normalize(state: Dict[str, Any]) -> None: for u in state['never_subscribed']: if 'subscribers' in u: u['subscribers'].sort() for u in state['subscriptions']: if 'subscribers' in u: u['subscribers'].sort() state['subscriptions'] = {u['name']: u for u in state['subscriptions']} state['unsubscribed'] = {u['name']: u for u in state['unsubscribed']} if 'realm_bots' in state: state['realm_bots'] = {u['email']: u for u in state['realm_bots']} normalize(state1) normalize(state2) # If this assertions fails, we have unusual problems. self.assertEqual(state1.keys(), state2.keys()) # The far more likely scenario is that some section of # our enormous payload does not get updated properly. We # want the diff here to be developer-friendly, hence # the somewhat tedious code to provide useful output. if state1 != state2: # nocoverage print('\n---States DO NOT MATCH---') print('\nEVENTS:\n') # Printing out the events is a big help to # developers. import json for event in events: print(json.dumps(event, indent=4)) print('\nMISMATCHES:\n') for k in state1: if state1[k] != state2[k]: print('\nkey = ' + k) try: self.assertEqual({k: state1[k]}, {k: state2[k]}) except AssertionError as e: print(e) print(''' NOTE: This is an advanced test that verifies how we apply events after fetching data. If you do not know how to debug it, you can ask for help on chat. ''') sys.stdout.flush() raise AssertionError('Mismatching states') def check_events_dict(self, required_keys: List[Tuple[str, Validator]]) -> Validator: required_keys.append(('id', check_int)) # Raise AssertionError if `required_keys` contains duplicate items. keys = [key[0] for key in required_keys] self.assertEqual(len(keys), len(set(keys)), 'Duplicate items found in required_keys.') return check_dict_only(required_keys) def test_mentioned_send_message_events(self) -> None: user = self.example_user('hamlet') for i in range(3): content = 'mentioning... @**' + user.full_name + '** hello ' + str(i) self.do_test( lambda: self.send_stream_message(self.example_email('cordelia'), "Verona", content) ) def test_pm_send_message_events(self) -> None: self.do_test( lambda: self.send_personal_message(self.example_email('cordelia'), self.example_email('hamlet'), 'hola') ) def test_huddle_send_message_events(self) -> None: huddle = [ self.example_email('hamlet'), self.example_email('othello'), ] self.do_test( lambda: self.send_huddle_message(self.example_email('cordelia'), huddle, 'hola') ) def test_stream_send_message_events(self) -> None: def check_none(var_name: str, val: Any) -> Optional[str]: assert(val is None) return None def get_checker(check_gravatar: Validator) -> Validator: schema_checker = self.check_events_dict([ ('type', equals('message')), ('flags', check_list(None)), ('message', self.check_events_dict([ ('avatar_url', check_gravatar), ('client', check_string), ('content', check_string), ('content_type', equals('text/html')), ('display_recipient', check_string), ('is_me_message', check_bool), ('reactions', check_list(None)), ('recipient_id', check_int), ('sender_realm_str', check_string), ('sender_email', check_string), ('sender_full_name', check_string), ('sender_id', check_int), ('sender_short_name', check_string), ('stream_id', check_int), (TOPIC_NAME, check_string), (TOPIC_LINKS, check_list(None)), ('submessages', check_list(None)), ('timestamp', check_int), ('type', check_string), ])), ]) return schema_checker events = self.do_test( lambda: self.send_stream_message(self.example_email("hamlet"), "Verona", "hello"), client_gravatar=False, ) schema_checker = get_checker(check_gravatar=check_string) error = schema_checker('events[0]', events[0]) self.assert_on_error(error) events = self.do_test( lambda: self.send_stream_message(self.example_email("hamlet"), "Verona", "hello"), client_gravatar=True, ) schema_checker = get_checker(check_gravatar=check_none) error = schema_checker('events[0]', events[0]) self.assert_on_error(error) # Verify message editing schema_checker = self.check_events_dict([ ('type', equals('update_message')), ('flags', check_list(None)), ('content', check_string), ('edit_timestamp', check_int), ('message_id', check_int), ('message_ids', check_list(check_int)), ('prior_mention_user_ids', check_list(check_int)), ('mention_user_ids', check_list(check_int)), ('presence_idle_user_ids', check_list(check_int)), ('stream_push_user_ids', check_list(check_int)), ('stream_email_user_ids', check_list(check_int)), ('push_notify_user_ids', check_list(check_int)), ('orig_content', check_string), ('orig_rendered_content', check_string), (ORIG_TOPIC, check_string), ('prev_rendered_content_version', check_int), ('propagate_mode', check_string), ('rendered_content', check_string), ('sender', check_string), ('stream_id', check_int), ('stream_name', check_string), (TOPIC_NAME, check_string), (TOPIC_LINKS, check_list(None)), ('user_id', check_int), ('is_me_message', check_bool), ]) message = Message.objects.order_by('-id')[0] topic = 'new_topic' propagate_mode = 'change_all' content = 'new content' rendered_content = render_markdown(message, content) prior_mention_user_ids = set() # type: Set[int] mentioned_user_ids = set() # type: Set[int] events = self.do_test( lambda: do_update_message(self.user_profile, message, topic, propagate_mode, content, rendered_content, prior_mention_user_ids, mentioned_user_ids), state_change_expected=True, ) error = schema_checker('events[0]', events[0]) self.assert_on_error(error) # Verify do_update_embedded_data schema_checker = self.check_events_dict([ ('type', equals('update_message')), ('flags', check_list(None)), ('content', check_string), ('message_id', check_int), ('message_ids', check_list(check_int)), ('rendered_content', check_string), ('sender', check_string), ]) events = self.do_test( lambda: do_update_embedded_data(self.user_profile, message, u"embed_content", "<p>embed_content</p>"), state_change_expected=False, ) error = schema_checker('events[0]', events[0]) self.assert_on_error(error) def test_update_message_flags(self) -> None: # Test message flag update events schema_checker = self.check_events_dict([ ('all', check_bool), ('type', equals('update_message_flags')), ('flag', check_string), ('messages', check_list(check_int)), ('operation', equals("add")), ]) message = self.send_personal_message( self.example_email("cordelia"), self.example_email("hamlet"), "hello", ) user_profile = self.example_user('hamlet') events = self.do_test( lambda: do_update_message_flags(user_profile, get_client("website"), 'add', 'starred', [message]), state_change_expected=True, ) error = schema_checker('events[0]', events[0]) self.assert_on_error(error) schema_checker = self.check_events_dict([ ('all', check_bool), ('type', equals('update_message_flags')), ('flag', check_string), ('messages', check_list(check_int)), ('operation', equals("remove")), ]) events = self.do_test( lambda: do_update_message_flags(user_profile, get_client("website"), 'remove', 'starred', [message]), state_change_expected=True, ) error = schema_checker('events[0]', events[0]) self.assert_on_error(error) def test_update_read_flag_removes_unread_msg_ids(self) -> None: user_profile = self.example_user('hamlet') mention = '@**' + user_profile.full_name + '**' for content in ['hello', mention]: message = self.send_stream_message( self.example_email('cordelia'), "Verona", content ) self.do_test( lambda: do_update_message_flags(user_profile, get_client("website"), 'add', 'read', [message]), state_change_expected=True, ) def test_send_message_to_existing_recipient(self) -> None: self.send_stream_message( self.example_email('cordelia'), "Verona", "hello 1" ) self.do_test( lambda: self.send_stream_message("cordelia@zulip.com", "Verona", "hello 2"), state_change_expected=True, ) def test_add_reaction_legacy(self) -> None: schema_checker = self.check_events_dict([ ('type', equals('reaction')), ('op', equals('add')), ('message_id', check_int), ('emoji_name', check_string), ('emoji_code', check_string), ('reaction_type', check_string), ('user', check_dict_only([ ('email', check_string), ('full_name', check_string), ('user_id', check_int) ])), ]) message_id = self.send_stream_message(self.example_email("hamlet"), "Verona", "hello") message = Message.objects.get(id=message_id) events = self.do_test( lambda: do_add_reaction_legacy( self.user_profile, message, "tada"), state_change_expected=False, ) error = schema_checker('events[0]', events[0]) self.assert_on_error(error) def test_remove_reaction_legacy(self) -> None: schema_checker = self.check_events_dict([ ('type', equals('reaction')), ('op', equals('remove')), ('message_id', check_int), ('emoji_name', check_string), ('emoji_code', check_string), ('reaction_type', check_string), ('user', check_dict_only([ ('email', check_string), ('full_name', check_string), ('user_id', check_int) ])), ]) message_id = self.send_stream_message(self.example_email("hamlet"), "Verona", "hello") message = Message.objects.get(id=message_id) do_add_reaction_legacy(self.user_profile, message, "tada") events = self.do_test( lambda: do_remove_reaction_legacy( self.user_profile, message, "tada"), state_change_expected=False, ) error = schema_checker('events[0]', events[0]) self.assert_on_error(error) def test_add_reaction(self) -> None: schema_checker = self.check_events_dict([ ('type', equals('reaction')), ('op', equals('add')), ('message_id', check_int), ('emoji_name', check_string), ('emoji_code', check_string), ('reaction_type', check_string), ('user', check_dict_only([ ('email', check_string), ('full_name', check_string), ('user_id', check_int) ])), ]) message_id = self.send_stream_message(self.example_email("hamlet"), "Verona", "hello") message = Message.objects.get(id=message_id) events = self.do_test( lambda: do_add_reaction( self.user_profile, message, "tada", "1f389", "unicode_emoji"), state_change_expected=False, ) error = schema_checker('events[0]', events[0]) self.assert_on_error(error) def test_add_submessage(self) -> None: schema_checker = self.check_events_dict([ ('type', equals('submessage')), ('message_id', check_int), ('submessage_id', check_int), ('sender_id', check_int), ('msg_type', check_string), ('content', check_string), ]) cordelia = self.example_user('cordelia') stream_name = 'Verona' message_id = self.send_stream_message( sender_email=cordelia.email, stream_name=stream_name, ) events = self.do_test( lambda: do_add_submessage( realm=cordelia.realm, sender_id=cordelia.id, message_id=message_id, msg_type='whatever', content='"stuff"', ), state_change_expected=False, ) error = schema_checker('events[0]', events[0]) self.assert_on_error(error) def test_remove_reaction(self) -> None: schema_checker = self.check_events_dict([ ('type', equals('reaction')), ('op', equals('remove')), ('message_id', check_int), ('emoji_name', check_string), ('emoji_code', check_string), ('reaction_type', check_string), ('user', check_dict_only([ ('email', check_string), ('full_name', check_string), ('user_id', check_int) ])), ]) message_id = self.send_stream_message(self.example_email("hamlet"), "Verona", "hello") message = Message.objects.get(id=message_id) do_add_reaction(self.user_profile, message, "tada", "1f389", "unicode_emoji") events = self.do_test( lambda: do_remove_reaction( self.user_profile, message, "1f389", "unicode_emoji"), state_change_expected=False, ) error = schema_checker('events[0]', events[0]) self.assert_on_error(error) def test_invite_user_event(self) -> None: schema_checker = self.check_events_dict([ ('type', equals('invites_changed')), ]) self.user_profile = self.example_user('iago') streams = [] for stream_name in ["Denmark", "Scotland"]: streams.append(get_stream(stream_name, self.user_profile.realm)) events = self.do_test( lambda: do_invite_users(self.user_profile, ["foo@zulip.com"], streams, False), state_change_expected=False, ) error = schema_checker('events[0]', events[0]) self.assert_on_error(error) def test_revoke_user_invite_event(self) -> None: schema_checker = self.check_events_dict([ ('type', equals('invites_changed')), ]) self.user_profile = self.example_user('iago') streams = [] for stream_name in ["Denmark", "Verona"]: streams.append(get_stream(stream_name, self.user_profile.realm)) do_invite_users(self.user_profile, ["foo@zulip.com"], streams, False) prereg_users = PreregistrationUser.objects.filter(referred_by__realm=self.user_profile.realm) events = self.do_test( lambda: do_revoke_user_invite(prereg_users[0]), state_change_expected=False, ) error = schema_checker('events[0]', events[0]) self.assert_on_error(error) def test_invitation_accept_invite_event(self) -> None: schema_checker = self.check_events_dict([ ('type', equals('invites_changed')), ]) self.user_profile = self.example_user('iago') streams = [] for stream_name in ["Denmark", "Scotland"]: streams.append(get_stream(stream_name, self.user_profile.realm)) do_invite_users(self.user_profile, ["foo@zulip.com"], streams, False) prereg_users = PreregistrationUser.objects.get(email="foo@zulip.com") events = self.do_test( lambda: do_create_user('foo@zulip.com', 'password', self.user_profile.realm, 'full name', 'short name', prereg_user=prereg_users), state_change_expected=True, num_events=5, ) error = schema_checker('events[4]', events[4]) self.assert_on_error(error) def test_typing_events(self) -> None: schema_checker = self.check_events_dict([ ('type', equals('typing')), ('op', equals('start')), ('sender', check_dict_only([ ('email', check_string), ('user_id', check_int)])), ('recipients', check_list(check_dict_only([ ('email', check_string), ('user_id', check_int), ]))), ]) events = self.do_test( lambda: check_send_typing_notification( self.user_profile, [self.example_email("cordelia")], "start"), state_change_expected=False, ) error = schema_checker('events[0]', events[0]) self.assert_on_error(error) def test_get_typing_user_profiles(self) -> None: """ Make sure we properly assert failures for recipient types that should not get typing... notifications. """ sender_profile = self.example_user('cordelia') stream = get_stream('Rome', sender_profile.realm) # Test stream with self.assertRaisesRegex(ValueError, 'not supported for streams'): recipient = Recipient.objects.get(type_id=stream.id, type=Recipient.STREAM) get_typing_user_profiles(recipient, sender_profile.id) # Test some other recipient type with self.assertRaisesRegex(ValueError, 'Bad recipient type'): recipient = Recipient(type=999) # invalid type get_typing_user_profiles(recipient, sender_profile.id) def test_custom_profile_fields_events(self) -> None: schema_checker = self.check_events_dict([ ('type', equals('custom_profile_fields')), ('op', equals('add')), ('fields', check_list(check_dict_only([ ('id', check_int), ('type', check_int), ('name', check_string), ('hint', check_string), ('field_data', check_string), ('order', check_int), ]))), ]) events = self.do_test( lambda: notify_realm_custom_profile_fields( self.user_profile.realm, 'add'), state_change_expected=False, ) error = schema_checker('events[0]', events[0]) self.assert_on_error(error) realm = self.user_profile.realm field = realm.customprofilefield_set.get(realm=realm, name='Biography') name = field.name hint = 'Biography of the user' try_update_realm_custom_profile_field(realm, field, name, hint=hint) events = self.do_test( lambda: notify_realm_custom_profile_fields( self.user_profile.realm, 'add'), state_change_expected=False, ) error = schema_checker('events[0]', events[0]) self.assert_on_error(error) def test_custom_profile_field_data_events(self) -> None: schema_checker = self.check_events_dict([ ('type', equals('realm_user')), ('op', equals('update')), ('person', check_dict_only([ ('user_id', check_int), ('custom_profile_field', check_dict_only([ ('id', check_int), ('value', check_none_or(check_string)), ])), ])), ]) realm = get_realm("zulip") field_id = realm.customprofilefield_set.get(realm=realm, name='Biography').id field = { "id": field_id, "value": "New value", } events = self.do_test(lambda: do_update_user_custom_profile_data(self.user_profile, [field])) error = schema_checker('events[0]', events[0]) self.assert_on_error(error) # Test we pass correct stringify value in custom-user-field data event field_id = realm.customprofilefield_set.get(realm=realm, name='Mentor').id field = { "id": field_id, "value": [self.example_user("ZOE").id], } events = self.do_test(lambda: do_update_user_custom_profile_data(self.user_profile, [field])) error = schema_checker('events[0]', events[0]) self.assert_on_error(error) def test_presence_events(self) -> None: schema_checker = self.check_events_dict([ ('type', equals('presence')), ('email', check_string), ('server_timestamp', check_float), ('presence', check_dict_only([ ('website', check_dict_only([ ('status', equals('active')), ('timestamp', check_int), ('client', check_string), ('pushable', check_bool), ])), ])), ]) events = self.do_test(lambda: do_update_user_presence( self.user_profile, get_client("website"), timezone_now(), UserPresence.ACTIVE)) error = schema_checker('events[0]', events[0]) self.assert_on_error(error) def test_presence_events_multiple_clients(self) -> None: schema_checker_android = self.check_events_dict([ ('type', equals('presence')), ('email', check_string), ('server_timestamp', check_float), ('presence', check_dict_only([ ('ZulipAndroid/1.0', check_dict_only([ ('status', equals('idle')), ('timestamp', check_int), ('client', check_string), ('pushable', check_bool), ])), ])), ]) self.api_post(self.user_profile.email, "/api/v1/users/me/presence", {'status': 'idle'}, HTTP_USER_AGENT="ZulipAndroid/1.0") self.do_test(lambda: do_update_user_presence( self.user_profile, get_client("website"), timezone_now(), UserPresence.ACTIVE)) events = self.do_test(lambda: do_update_user_presence( self.user_profile, get_client("ZulipAndroid/1.0"), timezone_now(), UserPresence.IDLE)) error = schema_checker_android('events[0]', events[0]) self.assert_on_error(error) def test_pointer_events(self) -> None: schema_checker = self.check_events_dict([ ('type', equals('pointer')), ('pointer', check_int) ]) events = self.do_test(lambda: do_update_pointer(self.user_profile, get_client("website"), 1500)) error = schema_checker('events[0]', events[0]) self.assert_on_error(error) def test_register_events(self) -> None: realm_user_add_checker = self.check_events_dict([ ('type', equals('realm_user')), ('op', equals('add')), ('person', check_dict_only([ ('user_id', check_int), ('email', check_string), ('avatar_url', check_none_or(check_string)), ('full_name', check_string), ('is_admin', check_bool), ('is_bot', check_bool), ('is_guest', check_bool), ('profile_data', check_dict_only([])), ('timezone', check_string), ('date_joined', check_string), ])), ]) events = self.do_test(lambda: self.register("test1@zulip.com", "test1")) self.assert_length(events, 1) error = realm_user_add_checker('events[0]', events[0]) self.assert_on_error(error) def test_alert_words_events(self) -> None: alert_words_checker = self.check_events_dict([ ('type', equals('alert_words')), ('alert_words', check_list(check_string)), ]) events = self.do_test(lambda: do_add_alert_words(self.user_profile, ["alert_word"])) error = alert_words_checker('events[0]', events[0]) self.assert_on_error(error) events = self.do_test(lambda: do_remove_alert_words(self.user_profile, ["alert_word"])) error = alert_words_checker('events[0]', events[0]) self.assert_on_error(error) def test_user_group_events(self) -> None: user_group_add_checker = self.check_events_dict([ ('type', equals('user_group')), ('op', equals('add')), ('group', check_dict_only([ ('id', check_int), ('name', check_string), ('members', check_list(check_int)), ('description', check_string), ])), ]) othello = self.example_user('othello') zulip = get_realm('zulip') events = self.do_test(lambda: check_add_user_group(zulip, 'backend', [othello], 'Backend team')) error = user_group_add_checker('events[0]', events[0]) self.assert_on_error(error) # Test name update user_group_update_checker = self.check_events_dict([ ('type', equals('user_group')), ('op', equals('update')), ('group_id', check_int), ('data', check_dict_only([ ('name', check_string), ])), ]) backend = UserGroup.objects.get(name='backend') events = self.do_test(lambda: do_update_user_group_name(backend, 'backendteam')) error = user_group_update_checker('events[0]', events[0]) self.assert_on_error(error) # Test description update user_group_update_checker = self.check_events_dict([ ('type', equals('user_group')), ('op', equals('update')), ('group_id', check_int), ('data', check_dict_only([ ('description', check_string), ])), ]) description = "Backend team to deal with backend code." events = self.do_test(lambda: do_update_user_group_description(backend, description)) error = user_group_update_checker('events[0]', events[0]) self.assert_on_error(error) # Test add members user_group_add_member_checker = self.check_events_dict([ ('type', equals('user_group')), ('op', equals('add_members')), ('group_id', check_int), ('user_ids', check_list(check_int)), ]) hamlet = self.example_user('hamlet') events = self.do_test(lambda: bulk_add_members_to_user_group(backend, [hamlet])) error = user_group_add_member_checker('events[0]', events[0]) self.assert_on_error(error) # Test remove members user_group_remove_member_checker = self.check_events_dict([ ('type', equals('user_group')), ('op', equals('remove_members')), ('group_id', check_int), ('user_ids', check_list(check_int)), ]) hamlet = self.example_user('hamlet') events = self.do_test(lambda: remove_members_from_user_group(backend, [hamlet])) error = user_group_remove_member_checker('events[0]', events[0]) self.assert_on_error(error) # Test delete event user_group_remove_checker = self.check_events_dict([ ('type', equals('user_group')), ('op', equals('remove')), ('group_id', check_int), ]) events = self.do_test(lambda: check_delete_user_group(backend.id, othello)) error = user_group_remove_checker('events[0]', events[0]) self.assert_on_error(error) def test_default_stream_groups_events(self) -> None: default_stream_groups_checker = self.check_events_dict([ ('type', equals('default_stream_groups')), ('default_stream_groups', check_list(check_dict_only([ ('name', check_string), ('id', check_int), ('description', check_string), ('streams', check_list(check_dict_only([ ('description', check_string), ('invite_only', check_bool), ('is_announcement_only', check_bool), ('name', check_string), ('stream_id', check_int), ('history_public_to_subscribers', check_bool)]))), ]))), ]) streams = [] for stream_name in ["Scotland", "Verona", "Denmark"]: streams.append(get_stream(stream_name, self.user_profile.realm)) events = self.do_test(lambda: do_create_default_stream_group( self.user_profile.realm, "group1", "This is group1", streams)) error = default_stream_groups_checker('events[0]', events[0]) self.assert_on_error(error) group = lookup_default_stream_groups(["group1"], self.user_profile.realm)[0] venice_stream = get_stream("Venice", self.user_profile.realm) events = self.do_test(lambda: do_add_streams_to_default_stream_group(self.user_profile.realm, group, [venice_stream])) error = default_stream_groups_checker('events[0]', events[0]) self.assert_on_error(error) events = self.do_test(lambda: do_remove_streams_from_default_stream_group(self.user_profile.realm, group, [venice_stream])) error = default_stream_groups_checker('events[0]', events[0]) self.assert_on_error(error) events = self.do_test(lambda: do_change_default_stream_group_description(self.user_profile.realm, group, "New description")) error = default_stream_groups_checker('events[0]', events[0]) self.assert_on_error(error) events = self.do_test(lambda: do_change_default_stream_group_name(self.user_profile.realm, group, "New Group Name")) error = default_stream_groups_checker('events[0]', events[0]) self.assert_on_error(error) events = self.do_test(lambda: do_remove_default_stream_group(self.user_profile.realm, group)) error = default_stream_groups_checker('events[0]', events[0]) self.assert_on_error(error) def test_default_streams_events(self) -> None: default_streams_checker = self.check_events_dict([ ('type', equals('default_streams')), ('default_streams', check_list(check_dict_only([ ('description', check_string), ('invite_only', check_bool), ('name', check_string), ('stream_id', check_int), ]))), ]) stream = get_stream("Scotland", self.user_profile.realm) events = self.do_test(lambda: do_add_default_stream(stream)) error = default_streams_checker('events[0]', events[0]) events = self.do_test(lambda: do_remove_default_stream(stream)) error = default_streams_checker('events[0]', events[0]) self.assert_on_error(error) def test_muted_topics_events(self) -> None: muted_topics_checker = self.check_events_dict([ ('type', equals('muted_topics')), ('muted_topics', check_list(check_list(check_string, 2))), ]) stream = get_stream('Denmark', self.user_profile.realm) recipient = get_stream_recipient(stream.id) events = self.do_test(lambda: do_mute_topic( self.user_profile, stream, recipient, "topic")) error = muted_topics_checker('events[0]', events[0]) self.assert_on_error(error) events = self.do_test(lambda: do_unmute_topic( self.user_profile, stream, "topic")) error = muted_topics_checker('events[0]', events[0]) self.assert_on_error(error) def test_change_avatar_fields(self) -> None: schema_checker = self.check_events_dict([ ('type', equals('realm_user')), ('op', equals('update')), ('person', check_dict_only([ ('email', check_string), ('user_id', check_int), ('avatar_url', check_string), ('avatar_url_medium', check_string), ('avatar_source', check_string), ])), ]) events = self.do_test( lambda: do_change_avatar_fields(self.user_profile, UserProfile.AVATAR_FROM_USER), ) error = schema_checker('events[0]', events[0]) self.assert_on_error(error) schema_checker = self.check_events_dict([ ('type', equals('realm_user')), ('op', equals('update')), ('person', check_dict_only([ ('email', check_string), ('user_id', check_int), ('avatar_url', check_none_or(check_string)), ('avatar_url_medium', check_none_or(check_string)), ('avatar_source', check_string), ])), ]) events = self.do_test( lambda: do_change_avatar_fields(self.user_profile, UserProfile.AVATAR_FROM_GRAVATAR), ) error = schema_checker('events[0]', events[0]) self.assert_on_error(error) def test_change_full_name(self) -> None: schema_checker = self.check_events_dict([ ('type', equals('realm_user')), ('op', equals('update')), ('person', check_dict_only([ ('email', check_string), ('full_name', check_string), ('user_id', check_int), ])), ]) events = self.do_test(lambda: do_change_full_name(self.user_profile, 'Sir Hamlet', self.user_profile)) error = schema_checker('events[0]', events[0]) self.assert_on_error(error) def do_set_realm_property_test(self, name: str) -> None: bool_tests = [True, False, True] # type: List[bool] test_values = dict( default_language=[u'es', u'de', u'en'], description=[u'Realm description', u'New description'], message_retention_days=[10, 20], name=[u'Zulip', u'New Name'], waiting_period_threshold=[10, 20], bot_creation_policy=[Realm.BOT_CREATION_EVERYONE], video_chat_provider=[u'Google Hangouts', u'Jitsi'], google_hangouts_domain=[u"zulip.com", u"zulip.org"], ) # type: Dict[str, Any] vals = test_values.get(name) property_type = Realm.property_types[name] if property_type is bool: validator = check_bool vals = bool_tests elif property_type is str: validator = check_string elif property_type is int: validator = check_int elif property_type == (int, type(None)): validator = check_int else: raise AssertionError("Unexpected property type %s" % (property_type,)) schema_checker = self.check_events_dict([ ('type', equals('realm')), ('op', equals('update')), ('property', equals(name)), ('value', validator), ]) if vals is None: raise AssertionError('No test created for %s' % (name)) do_set_realm_property(self.user_profile.realm, name, vals[0]) for val in vals[1:]: events = self.do_test( lambda: do_set_realm_property(self.user_profile.realm, name, val)) error = schema_checker('events[0]', events[0]) self.assert_on_error(error) @slow("Actually runs several full-stack fetching tests") def test_change_realm_property(self) -> None: for prop in Realm.property_types: self.do_set_realm_property_test(prop) @slow("Runs a large matrix of tests") def test_change_realm_authentication_methods(self) -> None: schema_checker = self.check_events_dict([ ('type', equals('realm')), ('op', equals('update_dict')), ('property', equals('default')), ('data', check_dict_only([ ('authentication_methods', check_dict([])) ])), ]) def fake_backends() -> Any: backends = ( 'zproject.backends.DevAuthBackend', 'zproject.backends.EmailAuthBackend', 'zproject.backends.GitHubAuthBackend', 'zproject.backends.GoogleMobileOauth2Backend', 'zproject.backends.ZulipLDAPAuthBackend', ) return self.settings(AUTHENTICATION_BACKENDS=backends) # Test transitions; any new backends should be tested with T/T/T/F/T for (auth_method_dict) in \ ({'Google': True, 'Email': True, 'GitHub': True, 'LDAP': False, 'Dev': False}, {'Google': True, 'Email': True, 'GitHub': False, 'LDAP': False, 'Dev': False}, {'Google': True, 'Email': False, 'GitHub': False, 'LDAP': False, 'Dev': False}, {'Google': True, 'Email': False, 'GitHub': True, 'LDAP': False, 'Dev': False}, {'Google': False, 'Email': False, 'GitHub': False, 'LDAP': False, 'Dev': True}, {'Google': False, 'Email': False, 'GitHub': True, 'LDAP': False, 'Dev': True}, {'Google': False, 'Email': True, 'GitHub': True, 'LDAP': True, 'Dev': False}): with fake_backends(): events = self.do_test( lambda: do_set_realm_authentication_methods( self.user_profile.realm, auth_method_dict)) error = schema_checker('events[0]', events[0]) self.assert_on_error(error) def test_change_pin_stream(self) -> None: schema_checker = self.check_events_dict([ ('type', equals('subscription')), ('op', equals('update')), ('property', equals('pin_to_top')), ('stream_id', check_int), ('value', check_bool), ('name', check_string), ('email', check_string), ]) stream = get_stream("Denmark", self.user_profile.realm) sub = get_subscription(stream.name, self.user_profile) do_change_subscription_property(self.user_profile, sub, stream, "pin_to_top", False) for pinned in (True, False): events = self.do_test(lambda: do_change_subscription_property(self.user_profile, sub, stream, "pin_to_top", pinned)) error = schema_checker('events[0]', events[0]) self.assert_on_error(error) @slow("Runs a matrix of 6 queries to the /home view") def test_change_realm_message_edit_settings(self) -> None: schema_checker = self.check_events_dict([ ('type', equals('realm')), ('op', equals('update_dict')), ('property', equals('default')), ('data', check_dict_only([ ('allow_message_editing', check_bool), ('message_content_edit_limit_seconds', check_int), ('allow_community_topic_editing', check_bool), ])), ]) # Test every transition among the four possibilities {T,F} x {0, non-0} for (allow_message_editing, message_content_edit_limit_seconds) in \ ((True, 0), (False, 0), (False, 1234), (True, 600), (False, 0), (True, 1234)): events = self.do_test( lambda: do_set_realm_message_editing(self.user_profile.realm, allow_message_editing, message_content_edit_limit_seconds, False)) error = schema_checker('events[0]', events[0]) self.assert_on_error(error) def test_change_realm_notifications_stream(self) -> None: schema_checker = self.check_events_dict([ ('type', equals('realm')), ('op', equals('update')), ('property', equals('notifications_stream_id')), ('value', check_int), ]) stream = get_stream("Rome", self.user_profile.realm) for notifications_stream, notifications_stream_id in ((stream, stream.id), (None, -1)): events = self.do_test( lambda: do_set_realm_notifications_stream(self.user_profile.realm, notifications_stream, notifications_stream_id)) error = schema_checker('events[0]', events[0]) self.assert_on_error(error) def test_change_realm_signup_notifications_stream(self) -> None: schema_checker = self.check_events_dict([ ('type', equals('realm')), ('op', equals('update')), ('property', equals('signup_notifications_stream_id')), ('value', check_int), ]) stream = get_stream("Rome", self.user_profile.realm) for signup_notifications_stream, signup_notifications_stream_id in ((stream, stream.id), (None, -1)): events = self.do_test( lambda: do_set_realm_signup_notifications_stream(self.user_profile.realm, signup_notifications_stream, signup_notifications_stream_id)) error = schema_checker('events[0]', events[0]) self.assert_on_error(error) def test_change_is_admin(self) -> None: schema_checker = self.check_events_dict([ ('type', equals('realm_user')), ('op', equals('update')), ('person', check_dict_only([ ('email', check_string), ('is_admin', check_bool), ('user_id', check_int), ])), ]) do_change_is_admin(self.user_profile, False) for is_admin in [True, False]: events = self.do_test(lambda: do_change_is_admin(self.user_profile, is_admin)) error = schema_checker('events[0]', events[0]) self.assert_on_error(error) def do_set_user_display_settings_test(self, setting_name: str) -> None: """Test updating each setting in UserProfile.property_types dict.""" test_changes = dict( emojiset = [u'apple', u'twitter'], default_language = [u'es', u'de', u'en'], timezone = [u'US/Mountain', u'US/Samoa', u'Pacific/Galapogos', u''] ) # type: Dict[str, Any] property_type = UserProfile.property_types[setting_name] if property_type is bool: validator = check_bool elif property_type is str: validator = check_string else: raise AssertionError("Unexpected property type %s" % (property_type,)) num_events = 1 if setting_name == "timezone": num_events = 2 values = test_changes.get(setting_name) if property_type is bool: if getattr(self.user_profile, setting_name) is False: values = [True, False, True] else: values = [False, True, False] if values is None: raise AssertionError('No test created for %s' % (setting_name)) for value in values: events = self.do_test(lambda: do_set_user_display_setting( self.user_profile, setting_name, value), num_events=num_events) schema_checker = self.check_events_dict([ ('type', equals('update_display_settings')), ('setting_name', equals(setting_name)), ('user', check_string), ('setting', validator), ]) language_schema_checker = self.check_events_dict([ ('type', equals('update_display_settings')), ('language_name', check_string), ('setting_name', equals(setting_name)), ('user', check_string), ('setting', validator), ]) if setting_name == "default_language": error = language_schema_checker('events[0]', events[0]) else: error = schema_checker('events[0]', events[0]) self.assert_on_error(error) timezone_schema_checker = self.check_events_dict([ ('type', equals('realm_user')), ('op', equals('update')), ('person', check_dict_only([ ('email', check_string), ('user_id', check_int), ('timezone', check_string), ])), ]) if setting_name == "timezone": error = timezone_schema_checker('events[1]', events[1]) @slow("Actually runs several full-stack fetching tests") def test_set_user_display_settings(self) -> None: for prop in UserProfile.property_types: self.do_set_user_display_settings_test(prop) @slow("Actually runs several full-stack fetching tests") def test_change_notification_settings(self) -> None: for notification_setting, v in self.user_profile.notification_setting_types.items(): schema_checker = self.check_events_dict([ ('type', equals('update_global_notifications')), ('notification_name', equals(notification_setting)), ('user', check_string), ('setting', check_bool), ]) do_change_notification_settings(self.user_profile, notification_setting, False) for setting_value in [True, False]: events = self.do_test(lambda: do_change_notification_settings( self.user_profile, notification_setting, setting_value, log=False)) error = schema_checker('events[0]', events[0]) self.assert_on_error(error) def test_realm_emoji_events(self) -> None: schema_checker = self.check_events_dict([ ('type', equals('realm_emoji')), ('op', equals('update')), ('realm_emoji', check_dict([])), ]) author = self.example_user('iago') with get_test_image_file('img.png') as img_file: events = self.do_test(lambda: check_add_realm_emoji(get_realm("zulip"), "my_emoji", author, img_file)) error = schema_checker('events[0]', events[0]) self.assert_on_error(error) events = self.do_test(lambda: do_remove_realm_emoji(get_realm("zulip"), "my_emoji")) error = schema_checker('events[0]', events[0]) self.assert_on_error(error) def test_realm_filter_events(self) -> None: schema_checker = self.check_events_dict([ ('type', equals('realm_filters')), ('realm_filters', check_list(None)), # TODO: validate tuples in the list ]) events = self.do_test(lambda: do_add_realm_filter(get_realm("zulip"), "#(?P<id>[123])", "https://realm.com/my_realm_filter/%(id)s")) error = schema_checker('events[0]', events[0]) self.assert_on_error(error) self.do_test(lambda: do_remove_realm_filter(get_realm("zulip"), "#(?P<id>[123])")) error = schema_checker('events[0]', events[0]) self.assert_on_error(error) def test_realm_domain_events(self) -> None: schema_checker = self.check_events_dict([ ('type', equals('realm_domains')), ('op', equals('add')), ('realm_domain', check_dict_only([ ('domain', check_string), ('allow_subdomains', check_bool), ])), ]) realm = get_realm('zulip') events = self.do_test(lambda: do_add_realm_domain(realm, 'zulip.org', False)) error = schema_checker('events[0]', events[0]) self.assert_on_error(error) schema_checker = self.check_events_dict([ ('type', equals('realm_domains')), ('op', equals('change')), ('realm_domain', check_dict_only([ ('domain', equals('zulip.org')), ('allow_subdomains', equals(True)), ])), ]) test_domain = RealmDomain.objects.get(realm=realm, domain='zulip.org') events = self.do_test(lambda: do_change_realm_domain(test_domain, True)) error = schema_checker('events[0]', events[0]) self.assert_on_error(error) schema_checker = self.check_events_dict([ ('type', equals('realm_domains')), ('op', equals('remove')), ('domain', equals('zulip.org')), ]) events = self.do_test(lambda: do_remove_realm_domain(test_domain)) error = schema_checker('events[0]', events[0]) self.assert_on_error(error) def test_create_bot(self) -> None: def get_bot_created_checker(bot_type: str) -> Validator: if bot_type == "GENERIC_BOT": check_services = check_list(sub_validator=None, length=0) elif bot_type == "OUTGOING_WEBHOOK_BOT": check_services = check_list(check_dict_only([ ('base_url', check_url), ('interface', check_int), ('token', check_string), ]), length=1) elif bot_type == "EMBEDDED_BOT": check_services = check_list(check_dict_only([ ('service_name', check_string), ('config_data', check_dict(value_validator=check_string)), ]), length=1) return self.check_events_dict([ ('type', equals('realm_bot')), ('op', equals('add')), ('bot', check_dict_only([ ('email', check_string), ('user_id', check_int), ('bot_type', check_int), ('full_name', check_string), ('is_active', check_bool), ('api_key', check_string), ('default_sending_stream', check_none_or(check_string)), ('default_events_register_stream', check_none_or(check_string)), ('default_all_public_streams', check_bool), ('avatar_url', check_string), ('owner', check_string), ('services', check_services), ])), ]) action = lambda: self.create_bot('test') events = self.do_test(action, num_events=3) error = get_bot_created_checker(bot_type="GENERIC_BOT")('events[1]', events[1]) self.assert_on_error(error) action = lambda: self.create_bot('test_outgoing_webhook', full_name='Outgoing Webhook Bot', payload_url=ujson.dumps('https://foo.bar.com'), interface_type=Service.GENERIC, bot_type=UserProfile.OUTGOING_WEBHOOK_BOT) events = self.do_test(action, num_events=3) # The third event is the second call of notify_created_bot, which contains additional # data for services (in contrast to the first call). error = get_bot_created_checker(bot_type="OUTGOING_WEBHOOK_BOT")('events[2]', events[2]) self.assert_on_error(error) action = lambda: self.create_bot('test_embedded', full_name='Embedded Bot', service_name='helloworld', config_data=ujson.dumps({'foo': 'bar'}), bot_type=UserProfile.EMBEDDED_BOT) events = self.do_test(action, num_events=3) error = get_bot_created_checker(bot_type="EMBEDDED_BOT")('events[2]', events[2]) self.assert_on_error(error) def test_change_bot_full_name(self) -> None: bot = self.create_bot('test') action = lambda: do_change_full_name(bot, 'New Bot Name', self.user_profile) events = self.do_test(action, num_events=2) error = self.realm_bot_schema('full_name', check_string)('events[1]', events[1]) self.assert_on_error(error) def test_regenerate_bot_api_key(self) -> None: bot = self.create_bot('test') action = lambda: do_regenerate_api_key(bot, self.user_profile) events = self.do_test(action) error = self.realm_bot_schema('api_key', check_string)('events[0]', events[0]) self.assert_on_error(error) def test_change_bot_avatar_source(self) -> None: bot = self.create_bot('test') action = lambda: do_change_avatar_fields(bot, bot.AVATAR_FROM_USER) events = self.do_test(action, num_events=2) error = self.realm_bot_schema('avatar_url', check_string)('events[0]', events[0]) self.assertEqual(events[1]['type'], 'realm_user') self.assert_on_error(error) def test_change_realm_icon_source(self) -> None: realm = get_realm('zulip') action = lambda: do_change_icon_source(realm, realm.ICON_FROM_GRAVATAR) events = self.do_test(action, state_change_expected=False) schema_checker = self.check_events_dict([ ('type', equals('realm')), ('op', equals('update_dict')), ('property', equals('icon')), ('data', check_dict_only([ ('icon_url', check_string), ('icon_source', check_string), ])), ]) error = schema_checker('events[0]', events[0]) self.assert_on_error(error) def test_change_bot_default_all_public_streams(self) -> None: bot = self.create_bot('test') action = lambda: do_change_default_all_public_streams(bot, True) events = self.do_test(action) error = self.realm_bot_schema('default_all_public_streams', check_bool)('events[0]', events[0]) self.assert_on_error(error) def test_change_bot_default_sending_stream(self) -> None: bot = self.create_bot('test') stream = get_stream("Rome", bot.realm) action = lambda: do_change_default_sending_stream(bot, stream) events = self.do_test(action) error = self.realm_bot_schema('default_sending_stream', check_string)('events[0]', events[0]) self.assert_on_error(error) action = lambda: do_change_default_sending_stream(bot, None) events = self.do_test(action) error = self.realm_bot_schema('default_sending_stream', equals(None))('events[0]', events[0]) self.assert_on_error(error) def test_change_bot_default_events_register_stream(self) -> None: bot = self.create_bot('test') stream = get_stream("Rome", bot.realm) action = lambda: do_change_default_events_register_stream(bot, stream) events = self.do_test(action) error = self.realm_bot_schema('default_events_register_stream', check_string)('events[0]', events[0]) self.assert_on_error(error) action = lambda: do_change_default_events_register_stream(bot, None) events = self.do_test(action) error = self.realm_bot_schema('default_events_register_stream', equals(None))('events[0]', events[0]) self.assert_on_error(error) def test_change_bot_owner(self) -> None: change_bot_owner_checker = self.check_events_dict([ ('type', equals('realm_bot')), ('op', equals('update')), ('bot', check_dict_only([ ('email', check_string), ('user_id', check_int), ('owner_id', check_int), ])), ]) self.user_profile = self.example_user('iago') owner = self.example_user('hamlet') bot = self.create_bot('test') action = lambda: do_change_bot_owner(bot, owner, self.user_profile) events = self.do_test(action) error = change_bot_owner_checker('events[0]', events[0]) self.assert_on_error(error) change_bot_owner_checker = self.check_events_dict([ ('type', equals('realm_bot')), ('op', equals('delete')), ('bot', check_dict_only([ ('email', check_string), ('user_id', check_int), ])), ]) self.user_profile = self.example_user('aaron') owner = self.example_user('hamlet') bot = self.create_bot('test1', full_name='Test1 Testerson') action = lambda: do_change_bot_owner(bot, owner, self.user_profile) events = self.do_test(action) error = change_bot_owner_checker('events[0]', events[0]) self.assert_on_error(error) check_services = check_list(sub_validator=None, length=0) change_bot_owner_checker = self.check_events_dict([ ('type', equals('realm_bot')), ('op', equals('add')), ('bot', check_dict_only([ ('email', check_string), ('user_id', check_int), ('bot_type', check_int), ('full_name', check_string), ('is_active', check_bool), ('api_key', check_string), ('default_sending_stream', check_none_or(check_string)), ('default_events_register_stream', check_none_or(check_string)), ('default_all_public_streams', check_bool), ('avatar_url', check_string), ('owner', check_string), ('services', check_services), ])), ]) previous_owner = self.example_user('aaron') self.user_profile = self.example_user('hamlet') bot = self.create_test_bot('test2', previous_owner, full_name='Test2 Testerson') action = lambda: do_change_bot_owner(bot, self.user_profile, previous_owner) events = self.do_test(action) error = change_bot_owner_checker('events[0]', events[0]) self.assert_on_error(error) def test_do_update_outgoing_webhook_service(self): # type: () -> None update_outgoing_webhook_service_checker = self.check_events_dict([ ('type', equals('realm_bot')), ('op', equals('update')), ('bot', check_dict_only([ ('email', check_string), ('user_id', check_int), ('services', check_list(check_dict_only([ ('base_url', check_url), ('interface', check_int), ('token', check_string), ]))), ])), ]) self.user_profile = self.example_user('iago') bot = self.create_test_bot('test', self.user_profile, full_name='Test Bot', bot_type=UserProfile.OUTGOING_WEBHOOK_BOT, payload_url=ujson.dumps('http://hostname.domain2.com'), interface_type=Service.GENERIC, ) action = lambda: do_update_outgoing_webhook_service(bot, 2, 'http://hostname.domain2.com') events = self.do_test(action) error = update_outgoing_webhook_service_checker('events[0]', events[0]) self.assert_on_error(error) def test_do_deactivate_user(self) -> None: bot_deactivate_checker = self.check_events_dict([ ('type', equals('realm_bot')), ('op', equals('remove')), ('bot', check_dict_only([ ('email', check_string), ('full_name', check_string), ('user_id', check_int), ])), ]) bot = self.create_bot('test') action = lambda: do_deactivate_user(bot) events = self.do_test(action, num_events=2) error = bot_deactivate_checker('events[1]', events[1]) self.assert_on_error(error) def test_do_reactivate_user(self) -> None: bot_reactivate_checker = self.check_events_dict([ ('type', equals('realm_bot')), ('op', equals('add')), ('bot', check_dict_only([ ('email', check_string), ('user_id', check_int), ('bot_type', check_int), ('full_name', check_string), ('is_active', check_bool), ('api_key', check_string), ('default_sending_stream', check_none_or(check_string)), ('default_events_register_stream', check_none_or(check_string)), ('default_all_public_streams', check_bool), ('avatar_url', check_string), ('owner', check_none_or(check_string)), ('services', check_list(check_dict_only([ ('base_url', check_url), ('interface', check_int), ]))), ])), ]) bot = self.create_bot('test') do_deactivate_user(bot) action = lambda: do_reactivate_user(bot) events = self.do_test(action, num_events=2) error = bot_reactivate_checker('events[1]', events[1]) self.assert_on_error(error) def test_do_mark_hotspot_as_read(self) -> None: self.user_profile.tutorial_status = UserProfile.TUTORIAL_WAITING self.user_profile.save(update_fields=['tutorial_status']) schema_checker = self.check_events_dict([ ('type', equals('hotspots')), ('hotspots', check_list(check_dict_only([ ('name', check_string), ('title', check_string), ('description', check_string), ('delay', check_float), ]))), ]) events = self.do_test(lambda: do_mark_hotspot_as_read(self.user_profile, 'intro_reply')) error = schema_checker('events[0]', events[0]) self.assert_on_error(error) def test_rename_stream(self) -> None: stream = self.make_stream('old_name') new_name = u'stream with a brand new name' self.subscribe(self.user_profile, stream.name) action = lambda: do_rename_stream(stream, new_name) events = self.do_test(action, num_events=2) schema_checker = self.check_events_dict([ ('type', equals('stream')), ('op', equals('update')), ('property', equals('email_address')), ('value', check_string), ('stream_id', check_int), ('name', equals('old_name')), ]) error = schema_checker('events[0]', events[0]) self.assert_on_error(error) schema_checker = self.check_events_dict([ ('type', equals('stream')), ('op', equals('update')), ('property', equals('name')), ('value', equals(new_name)), ('name', equals('old_name')), ('stream_id', check_int), ]) error = schema_checker('events[1]', events[1]) self.assert_on_error(error) def test_deactivate_stream_neversubscribed(self) -> None: stream = self.make_stream('old_name') action = lambda: do_deactivate_stream(stream) events = self.do_test(action) schema_checker = self.check_events_dict([ ('type', equals('stream')), ('op', equals('delete')), ('streams', check_list(check_dict([]))), ]) error = schema_checker('events[0]', events[0]) self.assert_on_error(error) def test_subscribe_other_user_never_subscribed(self) -> None: action = lambda: self.subscribe(self.example_user("othello"), u"test_stream") events = self.do_test(action, num_events=2) peer_add_schema_checker = self.check_events_dict([ ('type', equals('subscription')), ('op', equals('peer_add')), ('user_id', check_int), ('subscriptions', check_list(check_string)), ]) error = peer_add_schema_checker('events[1]', events[1]) self.assert_on_error(error) @slow("Actually several tests combined together") def test_subscribe_events(self) -> None: self.do_test_subscribe_events(include_subscribers=True) @slow("Actually several tests combined together") def test_subscribe_events_no_include_subscribers(self) -> None: self.do_test_subscribe_events(include_subscribers=False) def do_test_subscribe_events(self, include_subscribers: bool) -> None: subscription_fields = [ ('color', check_string), ('description', check_string), ('email_address', check_string), ('invite_only', check_bool), ('is_announcement_only', check_bool), ('in_home_view', check_bool), ('name', check_string), ('audible_notifications', check_bool), ('email_notifications', check_bool), ('desktop_notifications', check_bool), ('push_notifications', check_bool), ('stream_id', check_int), ('history_public_to_subscribers', check_bool), ('pin_to_top', check_bool), ('stream_weekly_traffic', check_none_or(check_int)), ('is_old_stream', check_bool), ] if include_subscribers: subscription_fields.append(('subscribers', check_list(check_int))) # type: ignore subscription_schema_checker = check_list( check_dict_only(subscription_fields), ) stream_create_schema_checker = self.check_events_dict([ ('type', equals('stream')), ('op', equals('create')), ('streams', check_list(check_dict_only([ ('name', check_string), ('stream_id', check_int), ('invite_only', check_bool), ('description', check_string), ]))), ]) add_schema_checker = self.check_events_dict([ ('type', equals('subscription')), ('op', equals('add')), ('subscriptions', subscription_schema_checker), ]) remove_schema_checker = self.check_events_dict([ ('type', equals('subscription')), ('op', equals('remove')), ('subscriptions', check_list( check_dict_only([ ('name', equals('test_stream')), ('stream_id', check_int), ]), )), ]) peer_add_schema_checker = self.check_events_dict([ ('type', equals('subscription')), ('op', equals('peer_add')), ('user_id', check_int), ('subscriptions', check_list(check_string)), ]) peer_remove_schema_checker = self.check_events_dict([ ('type', equals('subscription')), ('op', equals('peer_remove')), ('user_id', check_int), ('subscriptions', check_list(check_string)), ]) stream_update_schema_checker = self.check_events_dict([ ('type', equals('stream')), ('op', equals('update')), ('property', equals('description')), ('value', check_string), ('stream_id', check_int), ('name', check_string), ]) # Subscribe to a totally new stream, so it's just Hamlet on it action = lambda: self.subscribe(self.example_user("hamlet"), "test_stream") # type: Callable[[], Any] events = self.do_test(action, event_types=["subscription", "realm_user"], include_subscribers=include_subscribers) error = add_schema_checker('events[0]', events[0]) self.assert_on_error(error) # Add another user to that totally new stream action = lambda: self.subscribe(self.example_user("othello"), "test_stream") events = self.do_test(action, include_subscribers=include_subscribers, state_change_expected=include_subscribers, ) error = peer_add_schema_checker('events[0]', events[0]) self.assert_on_error(error) stream = get_stream("test_stream", self.user_profile.realm) # Now remove the first user, to test the normal unsubscribe flow action = lambda: bulk_remove_subscriptions( [self.example_user('othello')], [stream], get_client("website")) events = self.do_test(action, include_subscribers=include_subscribers, state_change_expected=include_subscribers, ) error = peer_remove_schema_checker('events[0]', events[0]) self.assert_on_error(error) # Now remove the second user, to test the 'vacate' event flow action = lambda: bulk_remove_subscriptions( [self.example_user('hamlet')], [stream], get_client("website")) events = self.do_test(action, include_subscribers=include_subscribers, num_events=3) error = remove_schema_checker('events[0]', events[0]) self.assert_on_error(error) # Now resubscribe a user, to make sure that works on a vacated stream action = lambda: self.subscribe(self.example_user("hamlet"), "test_stream") events = self.do_test(action, include_subscribers=include_subscribers, num_events=2) error = add_schema_checker('events[1]', events[1]) self.assert_on_error(error) action = lambda: do_change_stream_description(stream, u'new description') events = self.do_test(action, include_subscribers=include_subscribers) error = stream_update_schema_checker('events[0]', events[0]) self.assert_on_error(error) # Subscribe to a totally new invite-only stream, so it's just Hamlet on it stream = self.make_stream("private", get_realm("zulip"), invite_only=True) user_profile = self.example_user('hamlet') action = lambda: bulk_add_subscriptions([stream], [user_profile]) events = self.do_test(action, include_subscribers=include_subscribers, num_events=2) error = stream_create_schema_checker('events[0]', events[0]) error = add_schema_checker('events[1]', events[1]) self.assert_on_error(error) def test_do_delete_message_stream(self) -> None: schema_checker = self.check_events_dict([ ('type', equals('delete_message')), ('message_id', check_int), ('sender', check_string), ('message_type', equals("stream")), ('stream_id', check_int), ('topic', check_string), ]) msg_id = self.send_stream_message("hamlet@zulip.com", "Verona") message = Message.objects.get(id=msg_id) events = self.do_test( lambda: do_delete_message(self.user_profile, message), state_change_expected=True, ) error = schema_checker('events[0]', events[0]) self.assert_on_error(error) def test_do_delete_message_personal(self) -> None: schema_checker = self.check_events_dict([ ('type', equals('delete_message')), ('message_id', check_int), ('sender', check_string), ('message_type', equals("private")), ('recipient_user_ids', check_int), ]) msg_id = self.send_personal_message( self.example_email("cordelia"), self.user_profile.email, "hello", ) message = Message.objects.get(id=msg_id) events = self.do_test( lambda: do_delete_message(self.user_profile, message), state_change_expected=True, ) error = schema_checker('events[0]', events[0]) self.assert_on_error(error) def test_do_delete_message_no_max_id(self) -> None: user_profile = self.example_user('aaron') # Delete all historical messages for this user user_profile = self.example_user('hamlet') UserMessage.objects.filter(user_profile=user_profile).delete() msg_id = self.send_stream_message("hamlet@zulip.com", "Verona") message = Message.objects.get(id=msg_id) self.do_test( lambda: do_delete_message(self.user_profile, message), state_change_expected=True, ) result = fetch_initial_state_data(user_profile, None, "", client_gravatar=False) self.assertEqual(result['max_message_id'], -1) def test_add_attachment(self) -> None: schema_checker = self.check_events_dict([ ('type', equals('attachment')), ('op', equals('add')), ('attachment', check_dict_only([ ('id', check_int), ('name', check_string), ('size', check_int), ('path_id', check_string), ('create_time', check_float), ('messages', check_list(check_dict_only([ ('id', check_int), ('name', check_float), ]))), ])), ]) self.login(self.example_email("hamlet")) fp = StringIO("zulip!") fp.name = "zulip.txt" data = {'uri': None} def do_upload() -> None: result = self.client_post("/json/user_uploads", {'file': fp}) self.assert_json_success(result) self.assertIn("uri", result.json()) uri = result.json()["uri"] base = '/user_uploads/' self.assertEqual(base, uri[:len(base)]) data['uri'] = uri events = self.do_test( lambda: do_upload(), num_events=1, state_change_expected=False) error = schema_checker('events[0]', events[0]) self.assert_on_error(error) # Verify that the DB has the attachment marked as unclaimed entry = Attachment.objects.get(file_name='zulip.txt') self.assertEqual(entry.is_claimed(), False) # Now we send an actual message using this attachment. schema_checker = self.check_events_dict([ ('type', equals('attachment')), ('op', equals('update')), ('attachment', check_dict_only([ ('id', check_int), ('name', check_string), ('size', check_int), ('path_id', check_string), ('create_time', check_float), ('messages', check_list(check_dict_only([ ('id', check_int), ('name', check_float), ]))), ])), ]) self.subscribe(self.example_user("hamlet"), "Denmark") body = "First message ...[zulip.txt](http://localhost:9991" + data['uri'] + ")" events = self.do_test( lambda: self.send_stream_message(self.example_email("hamlet"), "Denmark", body, "test"), num_events=2) error = schema_checker('events[0]', events[0]) self.assert_on_error(error) # Now remove the attachment schema_checker = self.check_events_dict([ ('type', equals('attachment')), ('op', equals('remove')), ('attachment', check_dict_only([ ('id', check_int), ])), ]) events = self.do_test( lambda: self.client_delete("/json/attachments/%s" % (entry.id,)), num_events=1, state_change_expected=False) error = schema_checker('events[0]', events[0]) self.assert_on_error(error) class FetchInitialStateDataTest(ZulipTestCase): # Non-admin users don't have access to all bots def test_realm_bots_non_admin(self) -> None: user_profile = self.example_user('cordelia') self.assertFalse(user_profile.is_realm_admin) result = fetch_initial_state_data(user_profile, None, "", client_gravatar=False) self.assert_length(result['realm_bots'], 0) # additionally the API key for a random bot is not present in the data api_key = get_api_key(self.notification_bot()) self.assertNotIn(api_key, str(result)) # Admin users have access to all bots in the realm_bots field def test_realm_bots_admin(self) -> None: user_profile = self.example_user('hamlet') do_change_is_admin(user_profile, True) self.assertTrue(user_profile.is_realm_admin) result = fetch_initial_state_data(user_profile, None, "", client_gravatar=False) self.assertTrue(len(result['realm_bots']) > 5) def test_max_message_id_with_no_history(self) -> None: user_profile = self.example_user('aaron') # Delete all historical messages for this user UserMessage.objects.filter(user_profile=user_profile).delete() result = fetch_initial_state_data(user_profile, None, "", client_gravatar=False) self.assertEqual(result['max_message_id'], -1) class GetUnreadMsgsTest(ZulipTestCase): def mute_stream(self, user_profile: UserProfile, stream: Stream) -> None: recipient = Recipient.objects.get(type_id=stream.id, type=Recipient.STREAM) subscription = Subscription.objects.get( user_profile=user_profile, recipient=recipient ) subscription.in_home_view = False subscription.save() def mute_topic(self, user_profile: UserProfile, stream_name: str, topic_name: str) -> None: realm = user_profile.realm stream = get_stream(stream_name, realm) recipient = get_stream_recipient(stream.id) add_topic_mute( user_profile=user_profile, stream_id=stream.id, recipient_id=recipient.id, topic_name=topic_name, ) def test_raw_unread_stream(self) -> None: cordelia = self.example_user('cordelia') hamlet = self.example_user('hamlet') realm = hamlet.realm for stream_name in ['social', 'devel', 'test here']: self.subscribe(hamlet, stream_name) self.subscribe(cordelia, stream_name) all_message_ids = set() # type: Set[int] message_ids = dict() tups = [ ('social', 'lunch'), ('test here', 'bla'), ('devel', 'python'), ('devel', 'ruby'), ] for stream_name, topic_name in tups: message_ids[topic_name] = [ self.send_stream_message( sender_email=cordelia.email, stream_name=stream_name, topic_name=topic_name, ) for i in range(3) ] all_message_ids |= set(message_ids[topic_name]) self.assertEqual(len(all_message_ids), 12) # sanity check on test setup self.mute_stream( user_profile=hamlet, stream=get_stream('test here', realm), ) self.mute_topic( user_profile=hamlet, stream_name='devel', topic_name='ruby', ) raw_unread_data = get_raw_unread_data( user_profile=hamlet, ) stream_dict = raw_unread_data['stream_dict'] self.assertEqual( set(stream_dict.keys()), all_message_ids, ) self.assertEqual( raw_unread_data['unmuted_stream_msgs'], set(message_ids['python']) | set(message_ids['lunch']), ) self.assertEqual( stream_dict[message_ids['lunch'][0]], dict( sender_id=cordelia.id, stream_id=get_stream('social', realm).id, topic='lunch', ) ) def test_raw_unread_huddle(self) -> None: cordelia = self.example_user('cordelia') othello = self.example_user('othello') hamlet = self.example_user('hamlet') prospero = self.example_user('prospero') huddle1_message_ids = [ self.send_huddle_message( cordelia.email, [hamlet.email, othello.email] ) for i in range(3) ] huddle2_message_ids = [ self.send_huddle_message( cordelia.email, [hamlet.email, prospero.email] ) for i in range(3) ] raw_unread_data = get_raw_unread_data( user_profile=hamlet, ) huddle_dict = raw_unread_data['huddle_dict'] self.assertEqual( set(huddle_dict.keys()), set(huddle1_message_ids) | set(huddle2_message_ids) ) huddle_string = ','.join( str(uid) for uid in sorted([cordelia.id, hamlet.id, othello.id]) ) self.assertEqual( huddle_dict[huddle1_message_ids[0]], dict(user_ids_string=huddle_string), ) def test_raw_unread_personal(self) -> None: cordelia = self.example_user('cordelia') othello = self.example_user('othello') hamlet = self.example_user('hamlet') cordelia_pm_message_ids = [ self.send_personal_message(cordelia.email, hamlet.email) for i in range(3) ] othello_pm_message_ids = [ self.send_personal_message(othello.email, hamlet.email) for i in range(3) ] raw_unread_data = get_raw_unread_data( user_profile=hamlet, ) pm_dict = raw_unread_data['pm_dict'] self.assertEqual( set(pm_dict.keys()), set(cordelia_pm_message_ids) | set(othello_pm_message_ids) ) self.assertEqual( pm_dict[cordelia_pm_message_ids[0]], dict(sender_id=cordelia.id), ) def test_unread_msgs(self) -> None: cordelia = self.example_user('cordelia') sender_id = cordelia.id sender_email = cordelia.email user_profile = self.example_user('hamlet') othello = self.example_user('othello') # our tests rely on order assert(sender_email < user_profile.email) assert(user_profile.email < othello.email) pm1_message_id = self.send_personal_message(sender_email, user_profile.email, "hello1") pm2_message_id = self.send_personal_message(sender_email, user_profile.email, "hello2") muted_stream = self.subscribe(user_profile, 'Muted Stream') self.mute_stream(user_profile, muted_stream) self.mute_topic(user_profile, 'Denmark', 'muted-topic') stream_message_id = self.send_stream_message(sender_email, "Denmark", "hello") muted_stream_message_id = self.send_stream_message(sender_email, "Muted Stream", "hello") muted_topic_message_id = self.send_stream_message( sender_email, "Denmark", topic_name="muted-topic", content="hello", ) huddle_message_id = self.send_huddle_message( sender_email, [user_profile.email, othello.email], 'hello3', ) def get_unread_data() -> UnreadMessagesResult: raw_unread_data = get_raw_unread_data(user_profile) aggregated_data = aggregate_unread_data(raw_unread_data) return aggregated_data result = get_unread_data() # The count here reflects the count of unread messages that we will # report to users in the bankruptcy dialog, and for now it excludes unread messages # from muted treams, but it doesn't exclude unread messages from muted topics yet. self.assertEqual(result['count'], 4) unread_pm = result['pms'][0] self.assertEqual(unread_pm['sender_id'], sender_id) self.assertEqual(unread_pm['unread_message_ids'], [pm1_message_id, pm2_message_id]) self.assertTrue('sender_ids' not in unread_pm) unread_stream = result['streams'][0] self.assertEqual(unread_stream['stream_id'], get_stream('Denmark', user_profile.realm).id) self.assertEqual(unread_stream['topic'], 'muted-topic') self.assertEqual(unread_stream['unread_message_ids'], [muted_topic_message_id]) self.assertEqual(unread_stream['sender_ids'], [sender_id]) unread_stream = result['streams'][1] self.assertEqual(unread_stream['stream_id'], get_stream('Denmark', user_profile.realm).id) self.assertEqual(unread_stream['topic'], 'test') self.assertEqual(unread_stream['unread_message_ids'], [stream_message_id]) self.assertEqual(unread_stream['sender_ids'], [sender_id]) unread_stream = result['streams'][2] self.assertEqual(unread_stream['stream_id'], get_stream('Muted Stream', user_profile.realm).id) self.assertEqual(unread_stream['topic'], 'test') self.assertEqual(unread_stream['unread_message_ids'], [muted_stream_message_id]) self.assertEqual(unread_stream['sender_ids'], [sender_id]) huddle_string = ','.join(str(uid) for uid in sorted([sender_id, user_profile.id, othello.id])) unread_huddle = result['huddles'][0] self.assertEqual(unread_huddle['user_ids_string'], huddle_string) self.assertEqual(unread_huddle['unread_message_ids'], [huddle_message_id]) self.assertTrue('sender_ids' not in unread_huddle) self.assertEqual(result['mentions'], []) um = UserMessage.objects.get( user_profile_id=user_profile.id, message_id=stream_message_id ) um.flags |= UserMessage.flags.mentioned um.save() result = get_unread_data() self.assertEqual(result['mentions'], [stream_message_id]) class EventQueueTest(TestCase): def test_one_event(self) -> None: queue = EventQueue("1") queue.push({"type": "pointer", "pointer": 1, "timestamp": "1"}) self.assertFalse(queue.empty()) self.assertEqual(queue.contents(), [{'id': 0, 'type': 'pointer', "pointer": 1, "timestamp": "1"}]) def test_event_collapsing(self) -> None: queue = EventQueue("1") for pointer_val in range(1, 10): queue.push({"type": "pointer", "pointer": pointer_val, "timestamp": str(pointer_val)}) self.assertEqual(queue.contents(), [{'id': 8, 'type': 'pointer', "pointer": 9, "timestamp": "9"}]) queue = EventQueue("2") for pointer_val in range(1, 10): queue.push({"type": "pointer", "pointer": pointer_val, "timestamp": str(pointer_val)}) queue.push({"type": "unknown"}) queue.push({"type": "restart", "server_generation": "1"}) for pointer_val in range(11, 20): queue.push({"type": "pointer", "pointer": pointer_val, "timestamp": str(pointer_val)}) queue.push({"type": "restart", "server_generation": "2"}) self.assertEqual(queue.contents(), [{"type": "unknown", "id": 9}, {'id': 19, 'type': 'pointer', "pointer": 19, "timestamp": "19"}, {"id": 20, "type": "restart", "server_generation": "2"}]) for pointer_val in range(21, 23): queue.push({"type": "pointer", "pointer": pointer_val, "timestamp": str(pointer_val)}) self.assertEqual(queue.contents(), [{"type": "unknown", "id": 9}, {'id': 19, 'type': 'pointer', "pointer": 19, "timestamp": "19"}, {"id": 20, "type": "restart", "server_generation": "2"}, {'id': 22, 'type': 'pointer', "pointer": 22, "timestamp": "22"}, ]) def test_flag_add_collapsing(self) -> None: queue = EventQueue("1") queue.push({"type": "update_message_flags", "flag": "read", "operation": "add", "all": False, "messages": [1, 2, 3, 4], "timestamp": "1"}) queue.push({"type": "update_message_flags", "flag": "read", "all": False, "operation": "add", "messages": [5, 6], "timestamp": "1"}) self.assertEqual(queue.contents(), [{'id': 1, 'type': 'update_message_flags', "all": False, "flag": "read", "operation": "add", "messages": [1, 2, 3, 4, 5, 6], "timestamp": "1"}]) def test_flag_remove_collapsing(self) -> None: queue = EventQueue("1") queue.push({"type": "update_message_flags", "flag": "collapsed", "operation": "remove", "all": False, "messages": [1, 2, 3, 4], "timestamp": "1"}) queue.push({"type": "update_message_flags", "flag": "collapsed", "all": False, "operation": "remove", "messages": [5, 6], "timestamp": "1"}) self.assertEqual(queue.contents(), [{'id': 1, 'type': 'update_message_flags', "all": False, "flag": "collapsed", "operation": "remove", "messages": [1, 2, 3, 4, 5, 6], "timestamp": "1"}]) def test_collapse_event(self) -> None: queue = EventQueue("1") queue.push({"type": "pointer", "pointer": 1, "timestamp": "1"}) queue.push({"type": "unknown", "timestamp": "1"}) self.assertEqual(queue.contents(), [{'id': 0, 'type': 'pointer', "pointer": 1, "timestamp": "1"}, {'id': 1, 'type': 'unknown', "timestamp": "1"}]) class ClientDescriptorsTest(ZulipTestCase): def test_get_client_info_for_all_public_streams(self) -> None: hamlet = self.example_user('hamlet') realm = hamlet.realm queue_data = dict( all_public_streams=True, apply_markdown=True, client_gravatar=True, client_type_name='website', event_types=['message'], last_connection_time=time.time(), queue_timeout=0, realm_id=realm.id, user_profile_id=hamlet.id, ) client = allocate_client_descriptor(queue_data) message_event = dict( realm_id=realm.id, stream_name='whatever', ) client_info = get_client_info_for_message_event( message_event, users=[], ) self.assertEqual(len(client_info), 1) dct = client_info[client.event_queue.id] self.assertEqual(dct['client'].apply_markdown, True) self.assertEqual(dct['client'].client_gravatar, True) self.assertEqual(dct['client'].user_profile_id, hamlet.id) self.assertEqual(dct['flags'], []) self.assertEqual(dct['is_sender'], False) message_event = dict( realm_id=realm.id, stream_name='whatever', sender_queue_id=client.event_queue.id, ) client_info = get_client_info_for_message_event( message_event, users=[], ) dct = client_info[client.event_queue.id] self.assertEqual(dct['is_sender'], True) def test_get_client_info_for_normal_users(self) -> None: hamlet = self.example_user('hamlet') cordelia = self.example_user('cordelia') realm = hamlet.realm def test_get_info(apply_markdown: bool, client_gravatar: bool) -> None: clear_client_event_queues_for_testing() queue_data = dict( all_public_streams=False, apply_markdown=apply_markdown, client_gravatar=client_gravatar, client_type_name='website', event_types=['message'], last_connection_time=time.time(), queue_timeout=0, realm_id=realm.id, user_profile_id=hamlet.id, ) client = allocate_client_descriptor(queue_data) message_event = dict( realm_id=realm.id, stream_name='whatever', ) client_info = get_client_info_for_message_event( message_event, users=[ dict(id=cordelia.id), ], ) self.assertEqual(len(client_info), 0) client_info = get_client_info_for_message_event( message_event, users=[ dict(id=cordelia.id), dict(id=hamlet.id, flags=['mentioned']), ], ) self.assertEqual(len(client_info), 1) dct = client_info[client.event_queue.id] self.assertEqual(dct['client'].apply_markdown, apply_markdown) self.assertEqual(dct['client'].client_gravatar, client_gravatar) self.assertEqual(dct['client'].user_profile_id, hamlet.id) self.assertEqual(dct['flags'], ['mentioned']) self.assertEqual(dct['is_sender'], False) test_get_info(apply_markdown=False, client_gravatar=False) test_get_info(apply_markdown=True, client_gravatar=False) test_get_info(apply_markdown=False, client_gravatar=True) test_get_info(apply_markdown=True, client_gravatar=True) def test_process_message_event_with_mocked_client_info(self) -> None: hamlet = self.example_user("hamlet") class MockClient: def __init__(self, user_profile_id: int, apply_markdown: bool, client_gravatar: bool) -> None: self.user_profile_id = user_profile_id self.apply_markdown = apply_markdown self.client_gravatar = client_gravatar self.client_type_name = 'whatever' self.events = [] # type: List[Dict[str, Any]] def accepts_messages(self) -> bool: return True def accepts_event(self, event: Dict[str, Any]) -> bool: assert(event['type'] == 'message') return True def add_event(self, event: Dict[str, Any]) -> None: self.events.append(event) client1 = MockClient( user_profile_id=hamlet.id, apply_markdown=True, client_gravatar=False, ) client2 = MockClient( user_profile_id=hamlet.id, apply_markdown=False, client_gravatar=False, ) client3 = MockClient( user_profile_id=hamlet.id, apply_markdown=True, client_gravatar=True, ) client4 = MockClient( user_profile_id=hamlet.id, apply_markdown=False, client_gravatar=True, ) client_info = { 'client:1': dict( client=client1, flags=['starred'], ), 'client:2': dict( client=client2, flags=['has_alert_word'], ), 'client:3': dict( client=client3, flags=[], ), 'client:4': dict( client=client4, flags=[], ), } sender = hamlet message_event = dict( message_dict=dict( id=999, content='**hello**', rendered_content='<b>hello</b>', sender_id=sender.id, type='stream', client='website', # NOTE: Some of these fields are clutter, but some # will be useful when we let clients specify # that they can compute their own gravatar URLs. sender_email=sender.email, sender_realm_id=sender.realm_id, sender_avatar_source=UserProfile.AVATAR_FROM_GRAVATAR, sender_avatar_version=1, sender_is_mirror_dummy=None, raw_display_recipient=None, recipient_type=None, recipient_type_id=None, ), ) # Setting users to `[]` bypasses code we don't care about # for this test--we assume client_info is correct in our mocks, # and we are interested in how messages are put on event queue. users = [] # type: List[Any] with mock.patch('zerver.tornado.event_queue.get_client_info_for_message_event', return_value=client_info): process_message_event(message_event, users) # We are not closely examining avatar_url at this point, so # just sanity check them and then delete the keys so that # upcoming comparisons work. for client in [client1, client2]: message = client.events[0]['message'] self.assertIn('gravatar.com', message['avatar_url']) message.pop('avatar_url') self.assertEqual(client1.events, [ dict( type='message', message=dict( type='stream', sender_id=sender.id, sender_email=sender.email, id=999, content='<b>hello</b>', content_type='text/html', client='website', ), flags=['starred'], ), ]) self.assertEqual(client2.events, [ dict( type='message', message=dict( type='stream', sender_id=sender.id, sender_email=sender.email, id=999, content='**hello**', content_type='text/x-markdown', client='website', ), flags=['has_alert_word'], ), ]) self.assertEqual(client3.events, [ dict( type='message', message=dict( type='stream', sender_id=sender.id, sender_email=sender.email, avatar_url=None, id=999, content='<b>hello</b>', content_type='text/html', client='website', ), flags=[], ), ]) self.assertEqual(client4.events, [ dict( type='message', message=dict( type='stream', sender_id=sender.id, sender_email=sender.email, avatar_url=None, id=999, content='**hello**', content_type='text/x-markdown', client='website', ), flags=[], ), ]) class FetchQueriesTest(ZulipTestCase): def test_queries(self) -> None: user = self.example_user("hamlet") self.login(user.email) flush_per_request_caches() with queries_captured() as queries: with mock.patch('zerver.lib.events.always_want') as want_mock: fetch_initial_state_data( user_profile=user, event_types=None, queue_id='x', client_gravatar=False, ) self.assert_length(queries, 30) expected_counts = dict( alert_words=0, custom_profile_fields=1, default_streams=1, default_stream_groups=1, hotspots=0, message=1, muted_topics=1, pointer=0, presence=3, realm=0, realm_bot=1, realm_domains=1, realm_embedded_bots=0, realm_emoji=1, realm_filters=1, realm_user=3, realm_user_groups=2, starred_messages=1, stream=2, subscription=6, update_display_settings=0, update_global_notifications=0, update_message_flags=5, zulip_version=0, ) wanted_event_types = { item[0][0] for item in want_mock.call_args_list } self.assertEqual(wanted_event_types, set(expected_counts)) for event_type in sorted(wanted_event_types): count = expected_counts[event_type] flush_per_request_caches() with queries_captured() as queries: if event_type == 'update_message_flags': event_types = ['update_message_flags', 'message'] else: event_types = [event_type] fetch_initial_state_data( user_profile=user, event_types=event_types, queue_id='x', client_gravatar=False, ) self.assert_length(queries, count) class TestEventsRegisterAllPublicStreamsDefaults(ZulipTestCase): def setUp(self) -> None: self.user_profile = self.example_user('hamlet') self.email = self.user_profile.email def test_use_passed_all_public_true_default_false(self) -> None: self.user_profile.default_all_public_streams = False self.user_profile.save() result = _default_all_public_streams(self.user_profile, True) self.assertTrue(result) def test_use_passed_all_public_true_default(self) -> None: self.user_profile.default_all_public_streams = True self.user_profile.save() result = _default_all_public_streams(self.user_profile, True) self.assertTrue(result) def test_use_passed_all_public_false_default_false(self) -> None: self.user_profile.default_all_public_streams = False self.user_profile.save() result = _default_all_public_streams(self.user_profile, False) self.assertFalse(result) def test_use_passed_all_public_false_default_true(self) -> None: self.user_profile.default_all_public_streams = True self.user_profile.save() result = _default_all_public_streams(self.user_profile, False) self.assertFalse(result) def test_use_true_default_for_none(self) -> None: self.user_profile.default_all_public_streams = True self.user_profile.save() result = _default_all_public_streams(self.user_profile, None) self.assertTrue(result) def test_use_false_default_for_none(self) -> None: self.user_profile.default_all_public_streams = False self.user_profile.save() result = _default_all_public_streams(self.user_profile, None) self.assertFalse(result) class TestEventsRegisterNarrowDefaults(ZulipTestCase): def setUp(self) -> None: self.user_profile = self.example_user('hamlet') self.email = self.user_profile.email self.stream = get_stream('Verona', self.user_profile.realm) def test_use_passed_narrow_no_default(self) -> None: self.user_profile.default_events_register_stream_id = None self.user_profile.save() result = _default_narrow(self.user_profile, [[u'stream', u'my_stream']]) self.assertEqual(result, [[u'stream', u'my_stream']]) def test_use_passed_narrow_with_default(self) -> None: self.user_profile.default_events_register_stream_id = self.stream.id self.user_profile.save() result = _default_narrow(self.user_profile, [[u'stream', u'my_stream']]) self.assertEqual(result, [[u'stream', u'my_stream']]) def test_use_default_if_narrow_is_empty(self) -> None: self.user_profile.default_events_register_stream_id = self.stream.id self.user_profile.save() result = _default_narrow(self.user_profile, []) self.assertEqual(result, [[u'stream', u'Verona']]) def test_use_narrow_if_default_is_none(self) -> None: self.user_profile.default_events_register_stream_id = None self.user_profile.save() result = _default_narrow(self.user_profile, []) self.assertEqual(result, [])
[ "Callable[[HttpRequest, UserProfile], HttpResponse]", "UserProfile", "Dict[str, Any]", "bool", "bool", "str", "Any", "str", "Validator", "Callable[[], Any]", "Optional[str]", "Dict[str, Any]", "Dict[str, Any]", "List[Dict[str, Any]]", "Dict[str, Any]", "List[Tuple[str, Validator]]", "str", "Any", "Validator", "str", "str", "str", "bool", "UserProfile", "Stream", "UserProfile", "str", "str", "bool", "bool", "int", "bool", "bool", "Dict[str, Any]", "Dict[str, Any]" ]
[ 10093, 10180, 10225, 16003, 16026, 19196, 19211, 19358, 19370, 19731, 22210, 22328, 22352, 22397, 22457, 24525, 26104, 26114, 26234, 58479, 66919, 73847, 89428, 102214, 102235, 102576, 102602, 102638, 118021, 118044, 120121, 120167, 120215, 120628, 120772 ]
[ 10143, 10191, 10239, 16007, 16030, 19199, 19214, 19361, 19379, 19748, 22223, 22342, 22366, 22417, 22471, 24552, 26107, 26117, 26243, 58482, 66922, 73850, 89432, 102225, 102241, 102587, 102605, 102641, 118025, 118048, 120124, 120171, 120219, 120642, 120786 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_external.py
# -*- coding: utf-8 -*- from django.conf import settings from django.core.exceptions import ValidationError from django.http import HttpResponse from zerver.forms import email_is_not_mit_mailing_list from zerver.lib.rate_limiter import ( add_ratelimit_rule, clear_history, remove_ratelimit_rule, RateLimitedUser, ) from zerver.lib.zephyr import compute_mit_user_fullname from zerver.lib.test_classes import ( ZulipTestCase, ) import DNS import mock import time import urllib class MITNameTest(ZulipTestCase): def test_valid_hesiod(self) -> None: with mock.patch('DNS.dnslookup', return_value=[['starnine:*:84233:101:Athena Consulting Exchange User,,,:/mit/starnine:/bin/bash']]): self.assertEqual(compute_mit_user_fullname(self.mit_email("starnine")), "Athena Consulting Exchange User") with mock.patch('DNS.dnslookup', return_value=[['sipbexch:*:87824:101:Exch Sipb,,,:/mit/sipbexch:/bin/athena/bash']]): self.assertEqual(compute_mit_user_fullname("sipbexch@mit.edu"), "Exch Sipb") def test_invalid_hesiod(self) -> None: with mock.patch('DNS.dnslookup', side_effect=DNS.Base.ServerError('DNS query status: NXDOMAIN', 3)): self.assertEqual(compute_mit_user_fullname("1234567890@mit.edu"), "1234567890@mit.edu") with mock.patch('DNS.dnslookup', side_effect=DNS.Base.ServerError('DNS query status: NXDOMAIN', 3)): self.assertEqual(compute_mit_user_fullname("ec-discuss@mit.edu"), "ec-discuss@mit.edu") def test_mailinglist(self) -> None: with mock.patch('DNS.dnslookup', side_effect=DNS.Base.ServerError('DNS query status: NXDOMAIN', 3)): self.assertRaises(ValidationError, email_is_not_mit_mailing_list, "1234567890@mit.edu") with mock.patch('DNS.dnslookup', side_effect=DNS.Base.ServerError('DNS query status: NXDOMAIN', 3)): self.assertRaises(ValidationError, email_is_not_mit_mailing_list, "ec-discuss@mit.edu") def test_notmailinglist(self) -> None: with mock.patch('DNS.dnslookup', return_value=[['POP IMAP.EXCHANGE.MIT.EDU starnine']]): email_is_not_mit_mailing_list("sipbexch@mit.edu") class RateLimitTests(ZulipTestCase): def setUp(self) -> None: settings.RATE_LIMITING = True add_ratelimit_rule(1, 5) def tearDown(self) -> None: settings.RATE_LIMITING = False remove_ratelimit_rule(1, 5) def send_api_message(self, email: str, content: str) -> HttpResponse: return self.api_post(email, "/api/v1/messages", {"type": "stream", "to": "Verona", "client": "test suite", "content": content, "topic": "whatever"}) def test_headers(self) -> None: user = self.example_user('hamlet') email = user.email clear_history(RateLimitedUser(user)) result = self.send_api_message(email, "some stuff") self.assertTrue('X-RateLimit-Remaining' in result) self.assertTrue('X-RateLimit-Limit' in result) self.assertTrue('X-RateLimit-Reset' in result) def test_ratelimit_decrease(self) -> None: user = self.example_user('hamlet') email = user.email clear_history(RateLimitedUser(user)) result = self.send_api_message(email, "some stuff") limit = int(result['X-RateLimit-Remaining']) result = self.send_api_message(email, "some stuff 2") newlimit = int(result['X-RateLimit-Remaining']) self.assertEqual(limit, newlimit + 1) def test_hit_ratelimits(self) -> None: user = self.example_user('cordelia') email = user.email clear_history(RateLimitedUser(user)) start_time = time.time() for i in range(6): with mock.patch('time.time', return_value=(start_time + i * 0.1)): result = self.send_api_message(email, "some stuff %s" % (i,)) self.assertEqual(result.status_code, 429) json = result.json() self.assertEqual(json.get("result"), "error") self.assertIn("API usage exceeded rate limit", json.get("msg")) self.assertEqual(json.get('retry-after'), 0.5) self.assertTrue('Retry-After' in result) self.assertEqual(result['Retry-After'], '0.5') # We actually wait a second here, rather than force-clearing our history, # to make sure the rate-limiting code automatically forgives a user # after some time has passed. with mock.patch('time.time', return_value=(start_time + 1.0)): result = self.send_api_message(email, "Good message") self.assert_json_success(result)
[ "str", "str" ]
[ 2463, 2477 ]
[ 2466, 2480 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_feedback.py
from unittest.mock import patch, MagicMock from django.conf import settings from zerver.lib.test_classes import ZulipTestCase class TestFeedbackBot(ZulipTestCase): @patch('logging.info') def test_pm_to_feedback_bot(self, logging_info_mock: MagicMock) -> None: with self.settings(ENABLE_FEEDBACK=True): user_email = self.example_email("othello") self.send_personal_message(user_email, settings.FEEDBACK_BOT, content="I am a feedback message.") logging_info_mock.assert_called_once_with("Received feedback from {}".format(user_email))
[ "MagicMock" ]
[ 249 ]
[ 258 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_gitter_importer.py
# -*- coding: utf-8 -*- from django.conf import settings from django.utils.timezone import now as timezone_now from zerver.lib.import_realm import ( do_import_realm, ) from zerver.lib.test_classes import ( ZulipTestCase, ) from zerver.tests.test_import_export import ( rm_tree, ) from zerver.lib.test_helpers import ( get_test_image_file, ) from zerver.models import ( Realm, get_realm, UserProfile, Message, ) from zerver.data_import.gitter import ( do_convert_data, get_usermentions, ) import ujson import json import logging import shutil import os import mock from typing import Any, AnyStr, Dict, List, Optional, Set, Tuple class GitterImporter(ZulipTestCase): logger = logging.getLogger() # set logger to a higher level to suppress 'logger.INFO' outputs logger.setLevel(logging.WARNING) def _make_output_dir(self) -> str: output_dir = 'var/test-gitter-import' rm_tree(output_dir) os.makedirs(output_dir, exist_ok=True) return output_dir @mock.patch('zerver.data_import.gitter.process_avatars', return_value=[]) def test_gitter_import_data_conversion(self, mock_process_avatars: mock.Mock) -> None: output_dir = self._make_output_dir() gitter_file = os.path.join(os.path.dirname(__file__), 'fixtures/gitter_data.json') do_convert_data(gitter_file, output_dir) def read_file(output_file: str) -> Any: full_path = os.path.join(output_dir, output_file) with open(full_path) as f: return ujson.load(f) def get_set(data: List[Dict[str, Any]], field: str) -> Set[str]: values = set(r[field] for r in data) return values self.assertEqual(os.path.exists(os.path.join(output_dir, 'avatars')), True) self.assertEqual(os.path.exists(os.path.join(output_dir, 'emoji')), True) self.assertEqual(os.path.exists(os.path.join(output_dir, 'attachment.json')), True) realm = read_file('realm.json') # test realm self.assertEqual('Organization imported from Gitter!', realm['zerver_realm'][0]['description']) # test users exported_user_ids = get_set(realm['zerver_userprofile'], 'id') exported_user_full_name = get_set(realm['zerver_userprofile'], 'full_name') self.assertIn('User Full Name', exported_user_full_name) exported_user_email = get_set(realm['zerver_userprofile'], 'email') self.assertIn('username2@users.noreply.github.com', exported_user_email) # test stream self.assertEqual(len(realm['zerver_stream']), 1) self.assertEqual(realm['zerver_stream'][0]['name'], 'from gitter') self.assertEqual(realm['zerver_stream'][0]['deactivated'], False) self.assertEqual(realm['zerver_stream'][0]['realm'], realm['zerver_realm'][0]['id']) self.assertEqual(realm['zerver_defaultstream'][0]['stream'], realm['zerver_stream'][0]['id']) # test recipient exported_recipient_id = get_set(realm['zerver_recipient'], 'id') exported_recipient_type = get_set(realm['zerver_recipient'], 'type') self.assertEqual(set([1, 2]), exported_recipient_type) # test subscription exported_subscription_userprofile = get_set(realm['zerver_subscription'], 'user_profile') self.assertEqual(set([0, 1]), exported_subscription_userprofile) exported_subscription_recipient = get_set(realm['zerver_subscription'], 'recipient') self.assertEqual(len(exported_subscription_recipient), 3) self.assertIn(realm['zerver_subscription'][1]['recipient'], exported_recipient_id) messages = read_file('messages-000001.json') # test messages exported_messages_id = get_set(messages['zerver_message'], 'id') self.assertIn(messages['zerver_message'][0]['sender'], exported_user_ids) self.assertIn(messages['zerver_message'][1]['recipient'], exported_recipient_id) self.assertIn(messages['zerver_message'][0]['content'], 'test message') # test usermessages exported_usermessage_userprofile = get_set(messages['zerver_usermessage'], 'user_profile') self.assertEqual(exported_user_ids, exported_usermessage_userprofile) exported_usermessage_message = get_set(messages['zerver_usermessage'], 'message') self.assertEqual(exported_usermessage_message, exported_messages_id) @mock.patch('zerver.data_import.gitter.process_avatars', return_value=[]) def test_gitter_import_to_existing_database(self, mock_process_avatars: mock.Mock) -> None: output_dir = self._make_output_dir() gitter_file = os.path.join(os.path.dirname(__file__), 'fixtures/gitter_data.json') do_convert_data(gitter_file, output_dir) do_import_realm(output_dir, 'test-gitter-import') realm = get_realm('test-gitter-import') # test rendered_messages realm_users = UserProfile.objects.filter(realm=realm) messages = Message.objects.filter(sender__in=realm_users) for message in messages: self.assertIsNotNone(message.rendered_content, None) def test_get_usermentions(self) -> None: user_map = {'57124a4': 3, '57124b4': 5, '57124c4': 8} user_short_name_to_full_name = {'user': 'user name', 'user2': 'user2', 'user3': 'user name 3', 'user4': 'user 4'} messages = [{'text': 'hi @user', 'mentions': [{'screenName': 'user', 'userId': '57124a4'}]}, {'text': 'hi @user2 @user3', 'mentions': [{'screenName': 'user2', 'userId': '57124b4'}, {'screenName': 'user3', 'userId': '57124c4'}]}, {'text': 'hi @user4', 'mentions': [{'screenName': 'user4'}]}, {'text': 'hi @user5', 'mentions': [{'screenName': 'user', 'userId': '5712ds4'}]}] self.assertEqual(get_usermentions(messages[0], user_map, user_short_name_to_full_name), [3]) self.assertEqual(messages[0]['text'], 'hi @**user name**') self.assertEqual(get_usermentions(messages[1], user_map, user_short_name_to_full_name), [5, 8]) self.assertEqual(messages[1]['text'], 'hi @**user2** @**user name 3**') self.assertEqual(get_usermentions(messages[2], user_map, user_short_name_to_full_name), []) self.assertEqual(messages[2]['text'], 'hi @user4') self.assertEqual(get_usermentions(messages[3], user_map, user_short_name_to_full_name), []) self.assertEqual(messages[3]['text'], 'hi @user5')
[ "mock.Mock", "str", "List[Dict[str, Any]]", "str", "mock.Mock" ]
[ 1185, 1426, 1604, 1633, 4621 ]
[ 1194, 1429, 1624, 1636, 4630 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_hipchat_importer.py
from zerver.data_import.hipchat import ( get_hipchat_sender_id, ) from zerver.data_import.hipchat_user import ( UserHandler, ) from zerver.data_import.sequencer import ( IdMapper, ) from zerver.lib.test_classes import ( ZulipTestCase, ) from typing import Any, Dict class HipChatImporter(ZulipTestCase): def test_sender_ids(self) -> None: realm_id = 5 user_handler = UserHandler() user_id_mapper = IdMapper() user_id_mapper.has = lambda key: True # type: ignore # it's just a stub # Simulate a "normal" user first. user_with_id = dict( id=1, # other fields don't matter here ) user_handler.add_user(user=user_with_id) normal_message = dict( sender=dict( id=1, ) ) # type: Dict[str, Any] sender_id = get_hipchat_sender_id( realm_id=realm_id, message_dict=normal_message, user_id_mapper=user_id_mapper, user_handler=user_handler, ) self.assertEqual(sender_id, 1) bot_message = dict( sender='fred_bot', ) # Every message from fred_bot should # return the same sender_id. fred_bot_sender_id = 2 for i in range(3): sender_id = get_hipchat_sender_id( realm_id=realm_id, message_dict=bot_message, user_id_mapper=user_id_mapper, user_handler=user_handler, ) self.assertEqual(sender_id, fred_bot_sender_id) id_zero_message = dict( sender=dict( id=0, name='hal_bot', ), ) hal_bot_sender_id = 3 for i in range(3): sender_id = get_hipchat_sender_id( realm_id=realm_id, message_dict=id_zero_message, user_id_mapper=user_id_mapper, user_handler=user_handler, ) self.assertEqual(sender_id, hal_bot_sender_id)
[]
[]
[]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_home.py
import datetime import os import re import ujson from django.conf import settings from django.http import HttpResponse from django.test import override_settings from mock import MagicMock, patch import urllib from typing import Any, Dict, List from zerver.lib.actions import do_create_user from zerver.lib.test_classes import ZulipTestCase from zerver.lib.test_helpers import ( HostRequestMock, queries_captured, get_user_messages ) from zerver.lib.soft_deactivation import do_soft_deactivate_users from zerver.lib.test_runner import slow from zerver.models import ( get_realm, get_stream, get_user, UserProfile, UserMessage, Recipient, flush_per_request_caches, DefaultStream, Realm, ) from zerver.views.home import home, sent_time_in_epoch_seconds from corporate.models import Customer class HomeTest(ZulipTestCase): def test_home(self) -> None: # Keep this list sorted!!! html_bits = [ 'Compose your message here...', 'Exclude messages with topic', 'Keyboard shortcuts', 'Loading...', 'Manage streams', 'Narrow by topic', 'Next message', 'Search streams', 'Welcome to Zulip', # Verify that the app styles get included 'app-stubentry.js', 'var page_params', ] # Keep this list sorted!!! expected_keys = [ "alert_words", "avatar_source", "avatar_url", "avatar_url_medium", "bot_types", "can_create_streams", "can_subscribe_other_users", "cross_realm_bots", "custom_profile_field_types", "custom_profile_fields", "debug_mode", "default_language", "default_language_name", "delivery_email", "dense_mode", "development_environment", "email", "emojiset", "emojiset_choices", "enable_desktop_notifications", "enable_digest_emails", "enable_login_emails", "enable_offline_email_notifications", "enable_offline_push_notifications", "enable_online_push_notifications", "enable_sounds", "enable_stream_desktop_notifications", "enable_stream_email_notifications", "enable_stream_push_notifications", "enable_stream_sounds", "enter_sends", "first_in_realm", "full_name", "furthest_read_time", "has_mobile_devices", "have_initial_messages", "high_contrast_mode", "hotspots", "initial_servertime", "is_admin", "is_guest", "jitsi_server_url", "language_list", "language_list_dbl_col", "last_event_id", "left_side_userlist", "login_page", "max_avatar_file_size", "max_icon_file_size", "max_message_id", "maxfilesize", "message_content_in_email_notifications", "muted_topics", "narrow", "narrow_stream", "needs_tutorial", "never_subscribed", "night_mode", "password_min_guesses", "password_min_length", "pm_content_in_desktop_notifications", "pointer", "poll_timeout", "presences", "prompt_for_invites", "queue_id", "realm_add_emoji_by_admins_only", "realm_allow_community_topic_editing", "realm_allow_edit_history", "realm_allow_message_deleting", "realm_allow_message_editing", "realm_authentication_methods", "realm_available_video_chat_providers", "realm_bot_creation_policy", "realm_bot_domain", "realm_bots", "realm_create_stream_by_admins_only", "realm_default_language", "realm_default_stream_groups", "realm_default_streams", "realm_default_twenty_four_hour_time", "realm_description", "realm_digest_emails_enabled", "realm_disallow_disposable_email_addresses", "realm_domains", "realm_email_auth_enabled", "realm_email_changes_disabled", "realm_emails_restricted_to_domains", "realm_embedded_bots", "realm_emoji", "realm_filters", "realm_google_hangouts_domain", "realm_icon_source", "realm_icon_url", "realm_inline_image_preview", "realm_inline_url_embed_preview", "realm_invite_by_admins_only", "realm_invite_required", "realm_is_zephyr_mirror_realm", "realm_mandatory_topics", "realm_message_content_delete_limit_seconds", "realm_message_content_edit_limit_seconds", "realm_message_retention_days", "realm_name", "realm_name_changes_disabled", "realm_name_in_notifications", "realm_non_active_users", "realm_notifications_stream_id", "realm_password_auth_enabled", "realm_presence_disabled", "realm_push_notifications_enabled", "realm_send_welcome_emails", "realm_signup_notifications_stream_id", "realm_uri", "realm_user_groups", "realm_users", "realm_video_chat_provider", "realm_waiting_period_threshold", "root_domain_uri", "save_stacktraces", "search_pills_enabled", "server_generation", "server_inline_image_preview", "server_inline_url_embed_preview", "starred_message_counts", "starred_messages", "stream_description_max_length", "stream_name_max_length", "subscriptions", "test_suite", "timezone", "translate_emoticons", "translation_data", "twenty_four_hour_time", "two_fa_enabled", "two_fa_enabled_user", "unread_msgs", "unsubscribed", "use_websockets", "user_id", "warn_no_email", "zulip_version", ] email = self.example_email("hamlet") # Verify fails if logged-out result = self.client_get('/') self.assertEqual(result.status_code, 302) self.login(email) # Create bot for realm_bots testing. Must be done before fetching home_page. bot_info = { 'full_name': 'The Bot of Hamlet', 'short_name': 'hambot', } self.client_post("/json/bots", bot_info) # Verify succeeds once logged-in flush_per_request_caches() with queries_captured() as queries: with patch('zerver.lib.cache.cache_set') as cache_mock: result = self._get_home_page(stream='Denmark') self.assert_length(queries, 42) self.assert_length(cache_mock.call_args_list, 7) html = result.content.decode('utf-8') for html_bit in html_bits: if html_bit not in html: raise AssertionError('%s not in result' % (html_bit,)) page_params = self._get_page_params(result) actual_keys = sorted([str(k) for k in page_params.keys()]) self.assertEqual(actual_keys, expected_keys) # TODO: Inspect the page_params data further. # print(ujson.dumps(page_params, indent=2)) realm_bots_expected_keys = [ 'api_key', 'avatar_url', 'bot_type', 'default_all_public_streams', 'default_events_register_stream', 'default_sending_stream', 'email', 'full_name', 'is_active', 'owner', 'services', 'user_id', ] realm_bots_actual_keys = sorted([str(key) for key in page_params['realm_bots'][0].keys()]) self.assertEqual(realm_bots_actual_keys, realm_bots_expected_keys) def test_home_under_2fa_without_otp_device(self) -> None: with self.settings(TWO_FACTOR_AUTHENTICATION_ENABLED=True): self.login(self.example_email("iago")) result = self._get_home_page() # Should be successful because otp device is not configured. self.assertEqual(result.status_code, 200) def test_home_under_2fa_with_otp_device(self) -> None: with self.settings(TWO_FACTOR_AUTHENTICATION_ENABLED=True): user_profile = self.example_user('iago') self.create_default_device(user_profile) self.login(user_profile.email) result = self._get_home_page() # User should not log in because otp device is configured but # 2fa login function was not called. self.assertEqual(result.status_code, 302) self.login_2fa(user_profile) result = self._get_home_page() # Should be successful after calling 2fa login function. self.assertEqual(result.status_code, 200) def test_num_queries_for_realm_admin(self) -> None: # Verify number of queries for Realm admin isn't much higher than for normal users. self.login(self.example_email("iago")) flush_per_request_caches() with queries_captured() as queries: with patch('zerver.lib.cache.cache_set') as cache_mock: result = self._get_home_page() self.assertEqual(result.status_code, 200) self.assert_length(cache_mock.call_args_list, 6) self.assert_length(queries, 39) @slow("Creates and subscribes 10 users in a loop. Should use bulk queries.") def test_num_queries_with_streams(self) -> None: main_user = self.example_user('hamlet') other_user = self.example_user('cordelia') realm_id = main_user.realm_id self.login(main_user.email) # Try to make page-load do extra work for various subscribed # streams. for i in range(10): stream_name = 'test_stream_' + str(i) stream = self.make_stream(stream_name) DefaultStream.objects.create( realm_id=realm_id, stream_id=stream.id ) for user in [main_user, other_user]: self.subscribe(user, stream_name) # Simulate hitting the page the first time to avoid some noise # related to initial logins. self._get_home_page() # Then for the second page load, measure the number of queries. flush_per_request_caches() with queries_captured() as queries2: result = self._get_home_page() self.assert_length(queries2, 36) # Do a sanity check that our new streams were in the payload. html = result.content.decode('utf-8') self.assertIn('test_stream_7', html) def _get_home_page(self, **kwargs: Any) -> HttpResponse: with \ patch('zerver.lib.events.request_event_queue', return_value=42), \ patch('zerver.lib.events.get_user_events', return_value=[]): result = self.client_get('/', dict(**kwargs)) return result def _get_page_params(self, result: HttpResponse) -> Dict[str, Any]: html = result.content.decode('utf-8') lines = html.split('\n') page_params_line = [l for l in lines if re.match(r'^\s*var page_params', l)][0] page_params_json = page_params_line.split(' = ')[1].rstrip(';') page_params = ujson.loads(page_params_json) return page_params def _sanity_check(self, result: HttpResponse) -> None: ''' Use this for tests that are geared toward specific edge cases, but which still want the home page to load properly. ''' html = result.content.decode('utf-8') if 'Compose your message' not in html: raise AssertionError('Home page probably did not load.') def test_terms_of_service(self) -> None: user = self.example_user('hamlet') email = user.email self.login(email) for user_tos_version in [None, '1.1', '2.0.3.4']: user.tos_version = user_tos_version user.save() with \ self.settings(TERMS_OF_SERVICE='whatever'), \ self.settings(TOS_VERSION='99.99'): result = self.client_get('/', dict(stream='Denmark')) html = result.content.decode('utf-8') self.assertIn('There are new Terms of Service', html) def test_terms_of_service_first_time_template(self) -> None: user = self.example_user('hamlet') email = user.email self.login(email) user.tos_version = None user.save() with \ self.settings(FIRST_TIME_TOS_TEMPLATE='hello.html'), \ self.settings(TOS_VERSION='99.99'): result = self.client_post('/accounts/accept_terms/') self.assertEqual(result.status_code, 200) self.assert_in_response("I agree to the", result) self.assert_in_response("most productive team chat", result) def test_accept_terms_of_service(self) -> None: email = self.example_email("hamlet") self.login(email) result = self.client_post('/accounts/accept_terms/') self.assertEqual(result.status_code, 200) self.assert_in_response("I agree to the", result) result = self.client_post('/accounts/accept_terms/', {'terms': True}) self.assertEqual(result.status_code, 302) self.assertEqual(result['Location'], '/') def test_bad_narrow(self) -> None: email = self.example_email("hamlet") self.login(email) with patch('logging.exception') as mock: result = self._get_home_page(stream='Invalid Stream') mock.assert_called_once() self.assertEqual(mock.call_args_list[0][0][0], "Narrow parsing exception") self._sanity_check(result) def test_bad_pointer(self) -> None: user_profile = self.example_user('hamlet') email = user_profile.email user_profile.pointer = 999999 user_profile.save() self.login(email) with patch('logging.warning') as mock: result = self._get_home_page() mock.assert_called_once_with('hamlet@zulip.com has invalid pointer 999999') self._sanity_check(result) def test_topic_narrow(self) -> None: email = self.example_email("hamlet") self.login(email) result = self._get_home_page(stream='Denmark', topic='lunch') self._sanity_check(result) html = result.content.decode('utf-8') self.assertIn('lunch', html) def test_notifications_stream(self) -> None: email = self.example_email("hamlet") realm = get_realm('zulip') realm.notifications_stream_id = get_stream('Denmark', realm).id realm.save() self.login(email) result = self._get_home_page() page_params = self._get_page_params(result) self.assertEqual(page_params['realm_notifications_stream_id'], get_stream('Denmark', realm).id) def create_bot(self, owner: UserProfile, bot_email: str, bot_name: str) -> UserProfile: user = do_create_user( email=bot_email, password='123', realm=owner.realm, full_name=bot_name, short_name=bot_name, bot_type=UserProfile.DEFAULT_BOT, bot_owner=owner ) return user def create_non_active_user(self, realm: Realm, email: str, name: str) -> UserProfile: user = do_create_user( email=email, password='123', realm=realm, full_name=name, short_name=name, ) # Doing a full-stack deactivation would be expensive here, # and we really only need to flip the flag to get a valid # test. user.is_active = False user.save() return user def test_signup_notifications_stream(self) -> None: email = self.example_email("hamlet") realm = get_realm('zulip') realm.signup_notifications_stream = get_stream('Denmark', realm) realm.save() self.login(email) result = self._get_home_page() page_params = self._get_page_params(result) self.assertEqual(page_params['realm_signup_notifications_stream_id'], get_stream('Denmark', realm).id) @slow('creating users and loading home page') def test_people(self) -> None: hamlet = self.example_user('hamlet') realm = get_realm('zulip') self.login(hamlet.email) for i in range(3): self.create_bot( owner=hamlet, bot_email='bot-%d@zulip.com' % (i,), bot_name='Bot %d' % (i,), ) for i in range(3): self.create_non_active_user( realm=realm, email='defunct-%d@zulip.com' % (i,), name='Defunct User %d' % (i,), ) result = self._get_home_page() page_params = self._get_page_params(result) ''' We send three lists of users. The first two below are disjoint lists of users, and the records we send for them have identical structure. The realm_bots bucket is somewhat redundant, since all bots will be in one of the first two buckets. They do include fields, however, that normal users don't care about, such as default_sending_stream. ''' buckets = [ 'realm_users', 'realm_non_active_users', 'realm_bots', ] for field in buckets: users = page_params[field] self.assertTrue(len(users) >= 3, field) for rec in users: self.assertEqual(rec['user_id'], get_user(rec['email'], realm).id) if field == 'realm_bots': self.assertNotIn('is_bot', rec) self.assertIn('is_active', rec) self.assertIn('owner', rec) else: self.assertIn('is_bot', rec) self.assertNotIn('is_active', rec) active_emails = {p['email'] for p in page_params['realm_users']} non_active_emails = {p['email'] for p in page_params['realm_non_active_users']} bot_emails = {p['email'] for p in page_params['realm_bots']} self.assertIn(hamlet.email, active_emails) self.assertIn('defunct-1@zulip.com', non_active_emails) # Bots can show up in multiple buckets. self.assertIn('bot-2@zulip.com', bot_emails) self.assertIn('bot-2@zulip.com', active_emails) # Make sure nobody got mis-bucketed. self.assertNotIn(hamlet.email, non_active_emails) self.assertNotIn('defunct-1@zulip.com', active_emails) cross_bots = page_params['cross_realm_bots'] self.assertEqual(len(cross_bots), 5) cross_bots.sort(key=lambda d: d['email']) for cross_bot in cross_bots: # These are either nondeterministic or boring del cross_bot['timezone'] del cross_bot['avatar_url'] del cross_bot['date_joined'] notification_bot = self.notification_bot() by_email = lambda d: d['email'] self.assertEqual(sorted(cross_bots, key=by_email), sorted([ dict( user_id=get_user('new-user-bot@zulip.com', get_realm('zulip')).id, is_admin=False, email='new-user-bot@zulip.com', full_name='Zulip New User Bot', is_bot=True ), dict( user_id=get_user('emailgateway@zulip.com', get_realm('zulip')).id, is_admin=False, email='emailgateway@zulip.com', full_name='Email Gateway', is_bot=True ), dict( user_id=get_user('feedback@zulip.com', get_realm('zulip')).id, is_admin=False, email='feedback@zulip.com', full_name='Zulip Feedback Bot', is_bot=True ), dict( user_id=notification_bot.id, is_admin=False, email=notification_bot.email, full_name='Notification Bot', is_bot=True ), dict( user_id=get_user('welcome-bot@zulip.com', get_realm('zulip')).id, is_admin=False, email='welcome-bot@zulip.com', full_name='Welcome Bot', is_bot=True ), ], key=by_email)) def test_new_stream(self) -> None: user_profile = self.example_user("hamlet") stream_name = 'New stream' self.subscribe(user_profile, stream_name) self.login(user_profile.email) result = self._get_home_page(stream=stream_name) page_params = self._get_page_params(result) self.assertEqual(page_params['narrow_stream'], stream_name) self.assertEqual(page_params['narrow'], [dict(operator='stream', operand=stream_name)]) self.assertEqual(page_params['pointer'], -1) self.assertEqual(page_params['max_message_id'], -1) self.assertEqual(page_params['have_initial_messages'], False) def test_invites_by_admins_only(self) -> None: user_profile = self.example_user('hamlet') email = user_profile.email realm = user_profile.realm realm.invite_by_admins_only = True realm.save() self.login(email) self.assertFalse(user_profile.is_realm_admin) result = self._get_home_page() html = result.content.decode('utf-8') self.assertNotIn('Invite more users', html) user_profile.is_realm_admin = True user_profile.save() result = self._get_home_page() html = result.content.decode('utf-8') self.assertIn('Invite more users', html) def test_show_invites_for_guest_users(self) -> None: user_profile = self.example_user('polonius') email = user_profile.email realm = user_profile.realm realm.invite_by_admins_only = False realm.save() self.login(email) self.assertFalse(user_profile.is_realm_admin) self.assertFalse(get_realm('zulip').invite_by_admins_only) result = self._get_home_page() html = result.content.decode('utf-8') self.assertNotIn('Invite more users', html) def test_show_billing(self) -> None: customer = Customer.objects.create(realm=get_realm("zulip"), stripe_customer_id="cus_id") # realm admin, but no billing relationship -> no billing link user = self.example_user('iago') self.login(user.email) result_html = self._get_home_page().content.decode('utf-8') self.assertNotIn('Billing', result_html) # realm admin, with billing relationship -> show billing link customer.has_billing_relationship = True customer.save() result_html = self._get_home_page().content.decode('utf-8') self.assertIn('Billing', result_html) # billing admin, with billing relationship -> show billing link user.is_realm_admin = False user.is_billing_admin = True user.save(update_fields=['is_realm_admin', 'is_billing_admin']) result_html = self._get_home_page().content.decode('utf-8') self.assertIn('Billing', result_html) # billing admin, but no billing relationship -> no billing link customer.has_billing_relationship = False customer.save() result_html = self._get_home_page().content.decode('utf-8') self.assertNotIn('Billing', result_html) # billing admin, no customer object -> make sure it doesn't crash customer.delete() result = self._get_home_page() self.assertEqual(result.status_code, 200) def test_show_plans(self) -> None: realm = get_realm("zulip") self.login(self.example_email('hamlet')) # Show plans link to all users if plan_type is LIMITED realm.plan_type = Realm.LIMITED realm.save(update_fields=["plan_type"]) result_html = self._get_home_page().content.decode('utf-8') self.assertIn('Plans', result_html) # Show plans link to no one, including admins, if SELF_HOSTED or STANDARD realm.plan_type = Realm.SELF_HOSTED realm.save(update_fields=["plan_type"]) result_html = self._get_home_page().content.decode('utf-8') self.assertNotIn('Plans', result_html) realm.plan_type = Realm.STANDARD realm.save(update_fields=["plan_type"]) result_html = self._get_home_page().content.decode('utf-8') self.assertNotIn('Plans', result_html) def test_desktop_home(self) -> None: email = self.example_email("hamlet") self.login(email) result = self.client_get("/desktop_home") self.assertEqual(result.status_code, 301) self.assertTrue(result["Location"].endswith("/desktop_home/")) result = self.client_get("/desktop_home/") self.assertEqual(result.status_code, 302) path = urllib.parse.urlparse(result['Location']).path self.assertEqual(path, "/") def test_apps_view(self) -> None: result = self.client_get('/apps') self.assertEqual(result.status_code, 301) self.assertTrue(result['Location'].endswith('/apps/')) with self.settings(ZILENCER_ENABLED=False): result = self.client_get('/apps/') self.assertEqual(result.status_code, 301) self.assertTrue(result['Location'] == 'https://zulipchat.com/apps/') with self.settings(ZILENCER_ENABLED=True): result = self.client_get('/apps/') self.assertEqual(result.status_code, 200) html = result.content.decode('utf-8') self.assertIn('Apps for every platform.', html) def test_generate_204(self) -> None: email = self.example_email("hamlet") self.login(email) result = self.client_get("/api/v1/generate_204") self.assertEqual(result.status_code, 204) def test_message_sent_time(self) -> None: epoch_seconds = 1490472096 pub_date = datetime.datetime.fromtimestamp(epoch_seconds) user_message = MagicMock() user_message.message.pub_date = pub_date self.assertEqual(sent_time_in_epoch_seconds(user_message), epoch_seconds) def test_handlebars_compile_error(self) -> None: request = HostRequestMock() with self.settings(DEVELOPMENT=True, TEST_SUITE=False): with patch('os.path.exists', return_value=True): result = home(request) self.assertEqual(result.status_code, 500) self.assert_in_response('Error compiling handlebars templates.', result) def test_subdomain_homepage(self) -> None: email = self.example_email("hamlet") self.login(email) with self.settings(ROOT_DOMAIN_LANDING_PAGE=True): with patch('zerver.views.home.get_subdomain', return_value=""): result = self._get_home_page() self.assertEqual(result.status_code, 200) self.assert_in_response('most productive team chat', result) with patch('zerver.views.home.get_subdomain', return_value="subdomain"): result = self._get_home_page() self._sanity_check(result) def send_test_message(self, content: str, sender_name: str='iago', stream_name: str='Denmark', topic_name: str='foo') -> None: sender = self.example_email(sender_name) self.send_stream_message(sender, stream_name, content=content, topic_name=topic_name) def soft_activate_and_get_unread_count(self, stream: str='Denmark', topic: str='foo') -> int: stream_narrow = self._get_home_page(stream=stream, topic=topic) page_params = self._get_page_params(stream_narrow) return page_params['unread_msgs']['count'] def test_unread_count_user_soft_deactivation(self) -> None: # In this test we make sure if a soft deactivated user had unread # messages before deactivation they remain same way after activation. long_term_idle_user = self.example_user('hamlet') self.login(long_term_idle_user.email) message = 'Test Message 1' self.send_test_message(message) with queries_captured() as queries: self.assertEqual(self.soft_activate_and_get_unread_count(), 1) query_count = len(queries) user_msg_list = get_user_messages(long_term_idle_user) self.assertEqual(user_msg_list[-1].content, message) self.logout() do_soft_deactivate_users([long_term_idle_user]) self.login(long_term_idle_user.email) message = 'Test Message 2' self.send_test_message(message) idle_user_msg_list = get_user_messages(long_term_idle_user) self.assertNotEqual(idle_user_msg_list[-1].content, message) with queries_captured() as queries: self.assertEqual(self.soft_activate_and_get_unread_count(), 2) # Test here for query count to be at least 5 greater than previous count # This will assure indirectly that add_missing_messages() was called. self.assertGreaterEqual(len(queries) - query_count, 5) idle_user_msg_list = get_user_messages(long_term_idle_user) self.assertEqual(idle_user_msg_list[-1].content, message) @slow("Loads home page data several times testing different cases") def test_multiple_user_soft_deactivations(self) -> None: long_term_idle_user = self.example_user('hamlet') # We are sending this message to ensure that long_term_idle_user has # at least one UserMessage row. self.send_test_message('Testing', sender_name='hamlet') do_soft_deactivate_users([long_term_idle_user]) message = 'Test Message 1' self.send_test_message(message) self.login(long_term_idle_user.email) with queries_captured() as queries: self.assertEqual(self.soft_activate_and_get_unread_count(), 2) query_count = len(queries) long_term_idle_user.refresh_from_db() self.assertFalse(long_term_idle_user.long_term_idle) idle_user_msg_list = get_user_messages(long_term_idle_user) self.assertEqual(idle_user_msg_list[-1].content, message) message = 'Test Message 2' self.send_test_message(message) with queries_captured() as queries: self.assertEqual(self.soft_activate_and_get_unread_count(), 3) # Test here for query count to be at least 5 less than previous count. # This will assure add_missing_messages() isn't repeatedly called. self.assertGreaterEqual(query_count - len(queries), 5) idle_user_msg_list = get_user_messages(long_term_idle_user) self.assertEqual(idle_user_msg_list[-1].content, message) self.logout() do_soft_deactivate_users([long_term_idle_user]) message = 'Test Message 3' self.send_test_message(message) self.login(long_term_idle_user.email) with queries_captured() as queries: self.assertEqual(self.soft_activate_and_get_unread_count(), 4) query_count = len(queries) long_term_idle_user.refresh_from_db() self.assertFalse(long_term_idle_user.long_term_idle) idle_user_msg_list = get_user_messages(long_term_idle_user) self.assertEqual(idle_user_msg_list[-1].content, message) message = 'Test Message 4' self.send_test_message(message) with queries_captured() as queries: self.assertEqual(self.soft_activate_and_get_unread_count(), 5) self.assertGreaterEqual(query_count - len(queries), 5) idle_user_msg_list = get_user_messages(long_term_idle_user) self.assertEqual(idle_user_msg_list[-1].content, message) self.logout() def test_url_language(self) -> None: user = self.example_user("hamlet") user.default_language = 'es' user.save() self.login(user.email) result = self._get_home_page() self.assertEqual(result.status_code, 200) with \ patch('zerver.lib.events.request_event_queue', return_value=42), \ patch('zerver.lib.events.get_user_events', return_value=[]): result = self.client_get('/de/') page_params = self._get_page_params(result) self.assertEqual(page_params['default_language'], 'es') # TODO: Verify that the actual language we're using in the # translation data is German. def test_translation_data(self) -> None: user = self.example_user("hamlet") user.default_language = 'es' user.save() self.login(user.email) result = self._get_home_page() self.assertEqual(result.status_code, 200) page_params = self._get_page_params(result) self.assertEqual(page_params['default_language'], 'es') def test_emojiset(self) -> None: user = self.example_user("hamlet") user.emojiset = 'text' user.save() self.login(user.email) result = self._get_home_page() self.assertEqual(result.status_code, 200) html = result.content.decode('utf-8') self.assertIn('google-blob-sprite.css', html) self.assertNotIn('text-sprite.css', html)
[ "Any", "HttpResponse", "HttpResponse", "UserProfile", "str", "str", "Realm", "str", "str", "str" ]
[ 11306, 11623, 12011, 15621, 15645, 15660, 16014, 16028, 16039, 28168 ]
[ 11309, 11635, 12023, 15632, 15648, 15663, 16019, 16031, 16042, 28171 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_hotspots.py
# -*- coding: utf-8 -*- from zerver.lib.actions import do_mark_hotspot_as_read, do_create_user from zerver.lib.hotspots import ALL_HOTSPOTS, get_next_hotspots from zerver.lib.test_classes import ZulipTestCase from zerver.models import UserProfile, UserHotspot, get_realm from zerver.views.hotspots import mark_hotspot_as_read from django.conf import settings from typing import Any, Dict import ujson import mock # Splitting this out, since I imagine this will eventually have most of the # complicated hotspots logic. class TestGetNextHotspots(ZulipTestCase): def setUp(self) -> None: self.user = do_create_user( 'user@zulip.com', 'password', get_realm('zulip'), 'user', 'user') def test_first_hotspot(self) -> None: hotspots = get_next_hotspots(self.user) self.assertEqual(len(hotspots), 1) self.assertEqual(hotspots[0]['name'], 'intro_reply') def test_some_done_some_not(self) -> None: do_mark_hotspot_as_read(self.user, 'intro_reply') do_mark_hotspot_as_read(self.user, 'intro_compose') hotspots = get_next_hotspots(self.user) self.assertEqual(len(hotspots), 1) self.assertEqual(hotspots[0]['name'], 'intro_streams') def test_all_done(self) -> None: self.assertNotEqual(self.user.tutorial_status, UserProfile.TUTORIAL_FINISHED) for hotspot in ALL_HOTSPOTS: do_mark_hotspot_as_read(self.user, hotspot) self.assertEqual(self.user.tutorial_status, UserProfile.TUTORIAL_FINISHED) self.assertEqual(get_next_hotspots(self.user), []) def test_send_all(self) -> None: with self.settings(DEVELOPMENT=True, ALWAYS_SEND_ALL_HOTSPOTS = True): self.assertEqual(len(ALL_HOTSPOTS), len(get_next_hotspots(self.user))) class TestHotspots(ZulipTestCase): def test_do_mark_hotspot_as_read(self) -> None: user = self.example_user('hamlet') do_mark_hotspot_as_read(user, 'intro_compose') self.assertEqual(list(UserHotspot.objects.filter(user=user) .values_list('hotspot', flat=True)), ['intro_compose']) def test_hotspots_url_endpoint(self) -> None: user = self.example_user('hamlet') self.login(user.email) result = self.client_post('/json/users/me/hotspots', {'hotspot': ujson.dumps('intro_reply')}) self.assert_json_success(result) self.assertEqual(list(UserHotspot.objects.filter(user=user) .values_list('hotspot', flat=True)), ['intro_reply']) result = self.client_post('/json/users/me/hotspots', {'hotspot': ujson.dumps('invalid')}) self.assert_json_error(result, "Unknown hotspot: invalid") self.assertEqual(list(UserHotspot.objects.filter(user=user) .values_list('hotspot', flat=True)), ['intro_reply'])
[]
[]
[]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_i18n.py
# -*- coding: utf-8 -*- from typing import Any import django import mock from django.test import TestCase from django.utils import translation from django.conf import settings from django.http import HttpResponse from http.cookies import SimpleCookie from zerver.lib.test_classes import ( ZulipTestCase, ) from zerver.management.commands import makemessages class TranslationTestCase(ZulipTestCase): """ Tranlations strings should change with locale. URLs should be locale aware. """ def tearDown(self) -> None: translation.activate(settings.LANGUAGE_CODE) # e.g. self.client_post(url) if method is "post" def fetch(self, method: str, url: str, expected_status: int, **kwargs: Any) -> HttpResponse: response = getattr(self.client, method)(url, **kwargs) self.assertEqual(response.status_code, expected_status, msg="Expected %d, received %d for %s to %s" % ( expected_status, response.status_code, method, url)) return response def test_accept_language_header(self) -> None: languages = [('en', u'Sign up'), ('de', u'Registrieren'), ('sr', u'Упишите се'), ('zh-hans', u'注册'), ] for lang, word in languages: response = self.fetch('get', '/integrations/', 200, HTTP_ACCEPT_LANGUAGE=lang) self.assert_in_response(word, response) def test_cookie(self) -> None: languages = [('en', u'Sign up'), ('de', u'Registrieren'), ('sr', u'Упишите се'), ('zh-hans', u'注册'), ] for lang, word in languages: # Applying str function to LANGUAGE_COOKIE_NAME to convert unicode # into an ascii otherwise SimpleCookie will raise an exception self.client.cookies = SimpleCookie({str(settings.LANGUAGE_COOKIE_NAME): lang}) # type: ignore # https://github.com/python/typeshed/issues/1476 response = self.fetch('get', '/integrations/', 200) self.assert_in_response(word, response) def test_i18n_urls(self) -> None: languages = [('en', u'Sign up'), ('de', u'Registrieren'), ('sr', u'Упишите се'), ('zh-hans', u'注册'), ] for lang, word in languages: response = self.fetch('get', '/{}/integrations/'.format(lang), 200) self.assert_in_response(word, response) class JsonTranslationTestCase(ZulipTestCase): def tearDown(self) -> None: translation.activate(settings.LANGUAGE_CODE) @mock.patch('zerver.lib.request._') def test_json_error(self, mock_gettext: Any) -> None: dummy_value = "this arg is bad: '{var_name}' (translated to German)" mock_gettext.return_value = dummy_value email = self.example_email('hamlet') self.login(email) result = self.client_post("/json/invites", HTTP_ACCEPT_LANGUAGE='de') expected_error = u"this arg is bad: 'invitee_emails' (translated to German)" self.assert_json_error_contains(result, expected_error, status_code=400) @mock.patch('zerver.views.auth._') def test_jsonable_error(self, mock_gettext: Any) -> None: dummy_value = "Some other language" mock_gettext.return_value = dummy_value email = self.example_email('hamlet') self.login(email) result = self.client_get("/de/accounts/login/jwt/") self.assert_json_error_contains(result, dummy_value, status_code=400) class FrontendRegexTestCase(TestCase): def test_regexes(self) -> None: command = makemessages.Command() data = [ ('{{#tr context}}english text with __variable__{{/tr}}{{/tr}}', 'english text with __variable__'), ('{{t "english text" }}, "extra"}}', 'english text'), ("{{t 'english text' }}, 'extra'}}", 'english text'), ('i18n.t("english text"), "extra",)', 'english text'), ('i18n.t("english text", context), "extra",)', 'english text'), ("i18n.t('english text'), 'extra',)", 'english text'), ("i18n.t('english text', context), 'extra',)", 'english text'), ] for input_text, expected in data: result = command.extract_strings(input_text) self.assertEqual(len(result), 1) self.assertEqual(result[0], expected)
[ "str", "str", "int", "Any", "Any", "Any" ]
[ 677, 687, 709, 724, 2871, 3529 ]
[ 680, 690, 712, 727, 2874, 3532 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_import_export.py
# -*- coding: utf-8 -*- from django.conf import settings import os import shutil import ujson import io from PIL import Image from mock import patch, MagicMock from typing import Any, Dict, List, Set, Optional, Tuple, Callable, \ FrozenSet from boto.s3.connection import Location, S3Connection from zerver.lib.export import ( do_export_realm, export_files_from_s3, export_usermessages_batch, do_export_user, ) from zerver.lib.import_realm import ( do_import_realm, get_incoming_message_ids, ) from zerver.lib.avatar_hash import ( user_avatar_path, ) from zerver.lib.upload import ( claim_attachment, upload_message_file, upload_emoji_image, upload_avatar_image, ) from zerver.lib.utils import ( query_chunker, ) from zerver.lib.test_classes import ( ZulipTestCase, ) from zerver.lib.test_helpers import ( use_s3_backend, ) from zerver.lib.topic_mutes import ( add_topic_mute, ) from zerver.lib.bot_lib import ( StateHandler, ) from zerver.lib.bot_config import ( set_bot_config ) from zerver.lib.actions import ( do_create_user, ) from zerver.lib.test_runner import slow from zerver.models import ( Message, Realm, Stream, UserProfile, Subscription, Attachment, RealmEmoji, Recipient, UserMessage, CustomProfileField, CustomProfileFieldValue, RealmAuditLog, Huddle, UserHotspot, MutedTopic, UserGroup, UserGroupMembership, BotStorageData, BotConfigData, get_active_streams, get_realm, get_stream, get_stream_recipient, get_personal_recipient, get_huddle_hash, ) from zerver.lib.test_helpers import ( get_test_image_file, ) def rm_tree(path: str) -> None: if os.path.exists(path): shutil.rmtree(path) class QueryUtilTest(ZulipTestCase): def _create_messages(self) -> None: for email in [self.example_email('cordelia'), self.example_email('hamlet'), self.example_email('iago')]: for _ in range(5): self.send_personal_message(email, self.example_email('othello')) @slow('creates lots of data') def test_query_chunker(self) -> None: self._create_messages() cordelia = self.example_user('cordelia') hamlet = self.example_user('hamlet') def get_queries() -> List[Any]: queries = [ Message.objects.filter(sender_id=cordelia.id), Message.objects.filter(sender_id=hamlet.id), Message.objects.exclude(sender_id__in=[cordelia.id, hamlet.id]) ] return queries for query in get_queries(): # For our test to be meaningful, we want non-empty queries # at first assert len(list(query)) > 0 queries = get_queries() all_msg_ids = set() # type: Set[int] chunker = query_chunker( queries=queries, id_collector=all_msg_ids, chunk_size=20, ) all_row_ids = [] for chunk in chunker: for row in chunk: all_row_ids.append(row.id) self.assertEqual(all_row_ids, sorted(all_row_ids)) self.assertEqual(len(all_msg_ids), len(Message.objects.all())) # Now just search for cordelia/hamlet. Note that we don't really # need the order_by here, but it should be harmless. queries = [ Message.objects.filter(sender_id=cordelia.id).order_by('id'), Message.objects.filter(sender_id=hamlet.id), ] all_msg_ids = set() chunker = query_chunker( queries=queries, id_collector=all_msg_ids, chunk_size=7, # use a different size ) list(chunker) # exhaust the iterator self.assertEqual( len(all_msg_ids), len(Message.objects.filter(sender_id__in=[cordelia.id, hamlet.id])) ) # Try just a single query to validate chunking. queries = [ Message.objects.exclude(sender_id=cordelia.id), ] all_msg_ids = set() chunker = query_chunker( queries=queries, id_collector=all_msg_ids, chunk_size=11, # use a different size each time ) list(chunker) # exhaust the iterator self.assertEqual( len(all_msg_ids), len(Message.objects.exclude(sender_id=cordelia.id)) ) self.assertTrue(len(all_msg_ids) > 15) # Verify assertions about disjoint-ness. queries = [ Message.objects.exclude(sender_id=cordelia.id), Message.objects.filter(sender_id=hamlet.id), ] all_msg_ids = set() chunker = query_chunker( queries=queries, id_collector=all_msg_ids, chunk_size=13, # use a different size each time ) with self.assertRaises(AssertionError): list(chunker) # exercise the iterator # Try to confuse things with ids part of the query... queries = [ Message.objects.filter(id__lte=10), Message.objects.filter(id__gt=10), ] all_msg_ids = set() chunker = query_chunker( queries=queries, id_collector=all_msg_ids, chunk_size=11, # use a different size each time ) self.assertEqual(len(all_msg_ids), 0) # until we actually use the iterator list(chunker) # exhaust the iterator self.assertEqual(len(all_msg_ids), len(Message.objects.all())) # Verify that we can just get the first chunk with a next() call. queries = [ Message.objects.all(), ] all_msg_ids = set() chunker = query_chunker( queries=queries, id_collector=all_msg_ids, chunk_size=10, # use a different size each time ) first_chunk = next(chunker) # type: ignore self.assertEqual(len(first_chunk), 10) self.assertEqual(len(all_msg_ids), 10) expected_msg = Message.objects.all()[0:10][5] actual_msg = first_chunk[5] self.assertEqual(actual_msg.content, expected_msg.content) self.assertEqual(actual_msg.sender_id, expected_msg.sender_id) class ImportExportTest(ZulipTestCase): def setUp(self) -> None: rm_tree(settings.LOCAL_UPLOADS_DIR) def _make_output_dir(self) -> str: output_dir = 'var/test-export' rm_tree(output_dir) os.makedirs(output_dir, exist_ok=True) return output_dir def _export_realm(self, realm: Realm, exportable_user_ids: Optional[Set[int]]=None) -> Dict[str, Any]: output_dir = self._make_output_dir() with patch('logging.info'), patch('zerver.lib.export.create_soft_link'): do_export_realm( realm=realm, output_dir=output_dir, threads=0, exportable_user_ids=exportable_user_ids, ) # TODO: Process the second partial file, which can be created # for certain edge cases. export_usermessages_batch( input_path=os.path.join(output_dir, 'messages-000001.json.partial'), output_path=os.path.join(output_dir, 'messages-000001.json') ) def read_file(fn: str) -> Any: full_fn = os.path.join(output_dir, fn) with open(full_fn) as f: return ujson.load(f) result = {} result['realm'] = read_file('realm.json') result['attachment'] = read_file('attachment.json') result['message'] = read_file('messages-000001.json') result['uploads_dir'] = os.path.join(output_dir, 'uploads') result['uploads_dir_records'] = read_file(os.path.join('uploads', 'records.json')) result['emoji_dir'] = os.path.join(output_dir, 'emoji') result['emoji_dir_records'] = read_file(os.path.join('emoji', 'records.json')) result['avatar_dir'] = os.path.join(output_dir, 'avatars') result['avatar_dir_records'] = read_file(os.path.join('avatars', 'records.json')) return result def _setup_export_files(self) -> Tuple[str, str, str, bytes]: realm = Realm.objects.get(string_id='zulip') message = Message.objects.all()[0] user_profile = message.sender url = upload_message_file(u'dummy.txt', len(b'zulip!'), u'text/plain', b'zulip!', user_profile) attachment_path_id = url.replace('/user_uploads/', '') claim_attachment( user_profile=user_profile, path_id=attachment_path_id, message=message, is_message_realm_public=True ) avatar_path_id = user_avatar_path(user_profile) original_avatar_path_id = avatar_path_id + ".original" emoji_path = RealmEmoji.PATH_ID_TEMPLATE.format( realm_id=realm.id, emoji_file_name='1.png', ) with get_test_image_file('img.png') as img_file: upload_emoji_image(img_file, '1.png', user_profile) with get_test_image_file('img.png') as img_file: upload_avatar_image(img_file, user_profile, user_profile) test_image = open(get_test_image_file('img.png').name, 'rb').read() message.sender.avatar_source = 'U' message.sender.save() return attachment_path_id, emoji_path, original_avatar_path_id, test_image """ Tests for export """ def test_export_files_from_local(self) -> None: realm = Realm.objects.get(string_id='zulip') path_id, emoji_path, original_avatar_path_id, test_image = self._setup_export_files() full_data = self._export_realm(realm) data = full_data['attachment'] self.assertEqual(len(data['zerver_attachment']), 1) record = data['zerver_attachment'][0] self.assertEqual(record['path_id'], path_id) # Test uploads fn = os.path.join(full_data['uploads_dir'], path_id) with open(fn) as f: self.assertEqual(f.read(), 'zulip!') records = full_data['uploads_dir_records'] self.assertEqual(records[0]['path'], path_id) self.assertEqual(records[0]['s3_path'], path_id) # Test emojis fn = os.path.join(full_data['emoji_dir'], emoji_path) fn = fn.replace('1.png', '') self.assertEqual('1.png', os.listdir(fn)[0]) records = full_data['emoji_dir_records'] self.assertEqual(records[0]['file_name'], '1.png') self.assertEqual(records[0]['path'], '1/emoji/images/1.png') self.assertEqual(records[0]['s3_path'], '1/emoji/images/1.png') # Test avatars fn = os.path.join(full_data['avatar_dir'], original_avatar_path_id) fn_data = open(fn, 'rb').read() self.assertEqual(fn_data, test_image) records = full_data['avatar_dir_records'] record_path = [record['path'] for record in records] record_s3_path = [record['s3_path'] for record in records] self.assertIn(original_avatar_path_id, record_path) self.assertIn(original_avatar_path_id, record_s3_path) @use_s3_backend def test_export_files_from_s3(self) -> None: conn = S3Connection(settings.S3_KEY, settings.S3_SECRET_KEY) conn.create_bucket(settings.S3_AUTH_UPLOADS_BUCKET) conn.create_bucket(settings.S3_AVATAR_BUCKET) realm = Realm.objects.get(string_id='zulip') attachment_path_id, emoji_path, original_avatar_path_id, test_image = self._setup_export_files() full_data = self._export_realm(realm) data = full_data['attachment'] self.assertEqual(len(data['zerver_attachment']), 1) record = data['zerver_attachment'][0] self.assertEqual(record['path_id'], attachment_path_id) def check_variable_type(user_profile_id: int, realm_id: int) -> None: self.assertEqual(type(user_profile_id), int) self.assertEqual(type(realm_id), int) # Test uploads fields = attachment_path_id.split('/') fn = os.path.join(full_data['uploads_dir'], os.path.join(fields[0], fields[1], fields[2])) with open(fn) as f: self.assertEqual(f.read(), 'zulip!') records = full_data['uploads_dir_records'] self.assertEqual(records[0]['path'], os.path.join(fields[0], fields[1], fields[2])) self.assertEqual(records[0]['s3_path'], attachment_path_id) check_variable_type(records[0]['user_profile_id'], records[0]['realm_id']) # Test emojis fn = os.path.join(full_data['emoji_dir'], emoji_path) fn = fn.replace('1.png', '') self.assertIn('1.png', os.listdir(fn)) records = full_data['emoji_dir_records'] self.assertEqual(records[0]['file_name'], '1.png') self.assertTrue('last_modified' in records[0]) self.assertEqual(records[0]['path'], '1/emoji/images/1.png') self.assertEqual(records[0]['s3_path'], '1/emoji/images/1.png') check_variable_type(records[0]['user_profile_id'], records[0]['realm_id']) # Test avatars fn = os.path.join(full_data['avatar_dir'], original_avatar_path_id) fn_data = open(fn, 'rb').read() self.assertEqual(fn_data, test_image) records = full_data['avatar_dir_records'] record_path = [record['path'] for record in records] record_s3_path = [record['s3_path'] for record in records] self.assertIn(original_avatar_path_id, record_path) self.assertIn(original_avatar_path_id, record_s3_path) check_variable_type(records[0]['user_profile_id'], records[0]['realm_id']) def test_zulip_realm(self) -> None: realm = Realm.objects.get(string_id='zulip') realm_emoji = RealmEmoji.objects.get(realm=realm) realm_emoji.delete() full_data = self._export_realm(realm) realm_emoji.save() data = full_data['realm'] self.assertEqual(len(data['zerver_userprofile_crossrealm']), 0) self.assertEqual(len(data['zerver_userprofile_mirrordummy']), 0) def get_set(table: str, field: str) -> Set[str]: values = set(r[field] for r in data[table]) # print('set(%s)' % sorted(values)) return values def find_by_id(table: str, db_id: int) -> Dict[str, Any]: return [ r for r in data[table] if r['id'] == db_id][0] exported_user_emails = get_set('zerver_userprofile', 'email') self.assertIn(self.example_email('cordelia'), exported_user_emails) self.assertIn('default-bot@zulip.com', exported_user_emails) self.assertIn('emailgateway@zulip.com', exported_user_emails) exported_streams = get_set('zerver_stream', 'name') self.assertEqual( exported_streams, set([u'Denmark', u'Rome', u'Scotland', u'Venice', u'Verona']) ) data = full_data['message'] um = UserMessage.objects.all()[0] exported_um = find_by_id('zerver_usermessage', um.id) self.assertEqual(exported_um['message'], um.message_id) self.assertEqual(exported_um['user_profile'], um.user_profile_id) exported_message = find_by_id('zerver_message', um.message_id) self.assertEqual(exported_message['content'], um.message.content) # TODO, extract get_set/find_by_id, so we can split this test up # Now, restrict users cordelia = self.example_user('cordelia') hamlet = self.example_user('hamlet') user_ids = set([cordelia.id, hamlet.id]) realm_emoji = RealmEmoji.objects.get(realm=realm) realm_emoji.delete() full_data = self._export_realm(realm, exportable_user_ids=user_ids) realm_emoji.save() data = full_data['realm'] exported_user_emails = get_set('zerver_userprofile', 'email') self.assertIn(self.example_email('cordelia'), exported_user_emails) self.assertIn(self.example_email('hamlet'), exported_user_emails) self.assertNotIn('default-bot@zulip.com', exported_user_emails) self.assertNotIn(self.example_email('iago'), exported_user_emails) dummy_user_emails = get_set('zerver_userprofile_mirrordummy', 'email') self.assertIn(self.example_email('iago'), dummy_user_emails) self.assertNotIn(self.example_email('cordelia'), dummy_user_emails) def test_export_single_user(self) -> None: output_dir = self._make_output_dir() cordelia = self.example_user('cordelia') with patch('logging.info'): do_export_user(cordelia, output_dir) def read_file(fn: str) -> Any: full_fn = os.path.join(output_dir, fn) with open(full_fn) as f: return ujson.load(f) def get_set(data: List[Dict[str, Any]], field: str) -> Set[str]: values = set(r[field] for r in data) # print('set(%s)' % sorted(values)) return values messages = read_file('messages-000001.json') user = read_file('user.json') exported_user_id = get_set(user['zerver_userprofile'], 'id') self.assertEqual(exported_user_id, set([cordelia.id])) exported_user_email = get_set(user['zerver_userprofile'], 'email') self.assertEqual(exported_user_email, set([cordelia.email])) exported_recipient_type_id = get_set(user['zerver_recipient'], 'type_id') self.assertIn(cordelia.id, exported_recipient_type_id) exported_stream_id = get_set(user['zerver_stream'], 'id') self.assertIn(list(exported_stream_id)[0], exported_recipient_type_id) exported_recipient_id = get_set(user['zerver_recipient'], 'id') exported_subscription_recipient = get_set(user['zerver_subscription'], 'recipient') self.assertEqual(exported_recipient_id, exported_subscription_recipient) exported_messages_recipient = get_set(messages['zerver_message'], 'recipient') self.assertIn(list(exported_messages_recipient)[0], exported_recipient_id) """ Tests for import_realm """ def test_import_realm(self) -> None: original_realm = Realm.objects.get(string_id='zulip') RealmEmoji.objects.get(realm=original_realm).delete() # data to test import of huddles huddle = [ self.example_email('hamlet'), self.example_email('othello') ] self.send_huddle_message( self.example_email('cordelia'), huddle, 'test huddle message' ) # data to test import of hotspots sample_user = self.example_user('hamlet') UserHotspot.objects.create( user=sample_user, hotspot='intro_streams' ) # data to test import of muted topic stream = get_stream(u'Verona', original_realm) add_topic_mute( user_profile=sample_user, stream_id=stream.id, recipient_id=get_stream_recipient(stream.id).id, topic_name=u'Verona2') # data to test import of botstoragedata and botconfigdata bot_profile = do_create_user( email="bot-1@zulip.com", password="test", realm=original_realm, full_name="bot", short_name="bot", bot_type=UserProfile.EMBEDDED_BOT, bot_owner=sample_user) storage = StateHandler(bot_profile) storage.put('some key', 'some value') set_bot_config(bot_profile, 'entry 1', 'value 1') self._export_realm(original_realm) with patch('logging.info'): do_import_realm('var/test-export', 'test-zulip') # sanity checks # test realm self.assertTrue(Realm.objects.filter(string_id='test-zulip').exists()) imported_realm = Realm.objects.get(string_id='test-zulip') self.assertNotEqual(imported_realm.id, original_realm.id) def assert_realm_values(f: Callable[[Realm], Any], equal: bool=True) -> None: orig_realm_result = f(original_realm) imported_realm_result = f(imported_realm) # orig_realm_result should be truthy and have some values, otherwise # the test is kind of meaningless assert(orig_realm_result) if equal: self.assertEqual(orig_realm_result, imported_realm_result) else: self.assertNotEqual(orig_realm_result, imported_realm_result) # test users assert_realm_values( lambda r: {user.email for user in r.get_admin_users()} ) assert_realm_values( lambda r: {user.email for user in r.get_active_users()} ) # test stream assert_realm_values( lambda r: {stream.name for stream in get_active_streams(r)} ) # test recipients def get_recipient_stream(r: Realm) -> Stream: return get_stream_recipient( Stream.objects.get(name='Verona', realm=r).id ) def get_recipient_user(r: Realm) -> UserProfile: return get_personal_recipient( UserProfile.objects.get(full_name='Iago', realm=r).id ) assert_realm_values(lambda r: get_recipient_stream(r).type) assert_realm_values(lambda r: get_recipient_user(r).type) # test subscription def get_subscribers(recipient: Recipient) -> Set[str]: subscriptions = Subscription.objects.filter(recipient=recipient) users = {sub.user_profile.email for sub in subscriptions} return users assert_realm_values( lambda r: get_subscribers(get_recipient_stream(r)) ) assert_realm_values( lambda r: get_subscribers(get_recipient_user(r)) ) # test custom profile fields def get_custom_profile_field_names(r: Realm) -> Set[str]: custom_profile_fields = CustomProfileField.objects.filter(realm=r) custom_profile_field_names = {field.name for field in custom_profile_fields} return custom_profile_field_names assert_realm_values(get_custom_profile_field_names) def get_custom_profile_with_field_type_user(r: Realm) -> Tuple[Set[Any], Set[Any], Set[FrozenSet[str]]]: fields = CustomProfileField.objects.filter( field_type=CustomProfileField.USER, realm=r) def get_email(user_id: int) -> str: return UserProfile.objects.get(id=user_id).email def get_email_from_value(field_value: CustomProfileFieldValue) -> Set[str]: user_id_list = ujson.loads(field_value.value) return {get_email(user_id) for user_id in user_id_list} def custom_profile_field_values_for(fields: List[CustomProfileField]) -> Set[FrozenSet[str]]: user_emails = set() # type: Set[FrozenSet[str]] for field in fields: values = CustomProfileFieldValue.objects.filter(field=field) for value in values: user_emails.add(frozenset(get_email_from_value(value))) return user_emails field_names, field_hints = (set() for i in range(2)) for field in fields: field_names.add(field.name) field_hints.add(field.hint) return (field_hints, field_names, custom_profile_field_values_for(fields)) assert_realm_values(get_custom_profile_with_field_type_user) # test realmauditlog def get_realm_audit_log_event_type(r: Realm) -> Set[str]: realmauditlogs = RealmAuditLog.objects.filter(realm=r) realmauditlog_event_type = {log.event_type for log in realmauditlogs} return realmauditlog_event_type assert_realm_values(get_realm_audit_log_event_type) # test huddles def get_huddle_hashes(r: str) -> str: short_names = ['cordelia', 'hamlet', 'othello'] user_id_list = [UserProfile.objects.get(realm=r, short_name=name).id for name in short_names] huddle_hash = get_huddle_hash(user_id_list) return huddle_hash assert_realm_values(get_huddle_hashes, equal=False) def get_huddle_message(r: str) -> str: huddle_hash = get_huddle_hashes(r) huddle_id = Huddle.objects.get(huddle_hash=huddle_hash).id huddle_recipient = Recipient.objects.get(type_id=huddle_id, type=3) huddle_message = Message.objects.get(recipient=huddle_recipient) return huddle_message.content assert_realm_values(get_huddle_message) self.assertEqual(get_huddle_message(imported_realm), 'test huddle message') # test userhotspot def get_user_hotspots(r: str) -> Set[str]: user_profile = UserProfile.objects.get(realm=r, short_name='hamlet') hotspots = UserHotspot.objects.filter(user=user_profile) user_hotspots = {hotspot.hotspot for hotspot in hotspots} return user_hotspots assert_realm_values(get_user_hotspots) # test muted topics def get_muted_topics(r: Realm) -> Set[str]: user_profile = UserProfile.objects.get(realm=r, short_name='hamlet') muted_topics = MutedTopic.objects.filter(user_profile=user_profile) topic_names = {muted_topic.topic_name for muted_topic in muted_topics} return topic_names assert_realm_values(get_muted_topics) # test usergroups assert_realm_values( lambda r: {group.name for group in UserGroup.objects.filter(realm=r)} ) def get_user_membership(r: str) -> Set[str]: usergroup = UserGroup.objects.get(realm=r, name='hamletcharacters') usergroup_membership = UserGroupMembership.objects.filter(user_group=usergroup) users = {membership.user_profile.email for membership in usergroup_membership} return users assert_realm_values(get_user_membership) # test botstoragedata and botconfigdata def get_botstoragedata(r: Realm) -> Dict[str, Any]: bot_profile = UserProfile.objects.get(full_name="bot", realm=r) bot_storage_data = BotStorageData.objects.get(bot_profile=bot_profile) return {'key': bot_storage_data.key, 'data': bot_storage_data.value} assert_realm_values(get_botstoragedata) def get_botconfigdata(r: Realm) -> Dict[str, Any]: bot_profile = UserProfile.objects.get(full_name="bot", realm=r) bot_config_data = BotConfigData.objects.get(bot_profile=bot_profile) return {'key': bot_config_data.key, 'data': bot_config_data.value} assert_realm_values(get_botconfigdata) # test messages def get_stream_messages(r: Realm) -> Message: recipient = get_recipient_stream(r) messages = Message.objects.filter(recipient=recipient) return messages def get_stream_topics(r: Realm) -> Set[str]: messages = get_stream_messages(r) topics = {m.topic_name() for m in messages} return topics assert_realm_values(get_stream_topics) # test usermessages def get_usermessages_user(r: Realm) -> Set[Any]: messages = get_stream_messages(r).order_by('content') usermessage = UserMessage.objects.filter(message=messages[0]) usermessage_user = {um.user_profile.email for um in usermessage} return usermessage_user assert_realm_values(get_usermessages_user) def test_import_files_from_local(self) -> None: realm = Realm.objects.get(string_id='zulip') self._setup_export_files() self._export_realm(realm) with patch('logging.info'): do_import_realm('var/test-export', 'test-zulip') imported_realm = Realm.objects.get(string_id='test-zulip') # Test attachments uploaded_file = Attachment.objects.get(realm=imported_realm) self.assertEqual(len(b'zulip!'), uploaded_file.size) attachment_file_path = os.path.join(settings.LOCAL_UPLOADS_DIR, 'files', uploaded_file.path_id) self.assertTrue(os.path.isfile(attachment_file_path)) # Test emojis realm_emoji = RealmEmoji.objects.get(realm=imported_realm) emoji_path = RealmEmoji.PATH_ID_TEMPLATE.format( realm_id=imported_realm.id, emoji_file_name=realm_emoji.file_name, ) emoji_file_path = os.path.join(settings.LOCAL_UPLOADS_DIR, "avatars", emoji_path) self.assertTrue(os.path.isfile(emoji_file_path)) # Test avatars user_email = Message.objects.all()[0].sender.email user_profile = UserProfile.objects.get(email=user_email, realm=imported_realm) avatar_path_id = user_avatar_path(user_profile) + ".original" avatar_file_path = os.path.join(settings.LOCAL_UPLOADS_DIR, "avatars", avatar_path_id) self.assertTrue(os.path.isfile(avatar_file_path)) @use_s3_backend def test_import_files_from_s3(self) -> None: conn = S3Connection(settings.S3_KEY, settings.S3_SECRET_KEY) uploads_bucket = conn.create_bucket(settings.S3_AUTH_UPLOADS_BUCKET) avatar_bucket = conn.create_bucket(settings.S3_AVATAR_BUCKET) realm = Realm.objects.get(string_id='zulip') self._setup_export_files() self._export_realm(realm) with patch('logging.info'): do_import_realm('var/test-export', 'test-zulip') imported_realm = Realm.objects.get(string_id='test-zulip') test_image_data = open(get_test_image_file('img.png').name, 'rb').read() # Test attachments uploaded_file = Attachment.objects.get(realm=imported_realm) self.assertEqual(len(b'zulip!'), uploaded_file.size) attachment_content = uploads_bucket.get_key(uploaded_file.path_id).get_contents_as_string() self.assertEqual(b"zulip!", attachment_content) # Test emojis realm_emoji = RealmEmoji.objects.get(realm=imported_realm) emoji_path = RealmEmoji.PATH_ID_TEMPLATE.format( realm_id=imported_realm.id, emoji_file_name=realm_emoji.file_name, ) emoji_key = avatar_bucket.get_key(emoji_path) self.assertIsNotNone(emoji_key) self.assertEqual(emoji_key.key, emoji_path) # Test avatars user_email = Message.objects.all()[0].sender.email user_profile = UserProfile.objects.get(email=user_email, realm=imported_realm) avatar_path_id = user_avatar_path(user_profile) + ".original" original_image_key = avatar_bucket.get_key(avatar_path_id) self.assertEqual(original_image_key.key, avatar_path_id) image_data = original_image_key.get_contents_as_string() self.assertEqual(image_data, test_image_data) def test_get_incoming_message_ids(self) -> None: import_dir = os.path.join(settings.DEPLOY_ROOT, "zerver", "tests", "fixtures", "import_fixtures") message_ids = get_incoming_message_ids( import_dir=import_dir, sort_by_date=True, ) self.assertEqual(message_ids, [888, 999, 555]) message_ids = get_incoming_message_ids( import_dir=import_dir, sort_by_date=False, ) self.assertEqual(message_ids, [555, 888, 999]) def test_plan_type(self) -> None: realm = get_realm('zulip') realm.plan_type = Realm.STANDARD realm.save(update_fields=['plan_type']) self._setup_export_files() self._export_realm(realm) with patch('logging.info'): with self.settings(BILLING_ENABLED=True): realm = do_import_realm('var/test-export', 'test-zulip-1') self.assertTrue(realm.plan_type, Realm.LIMITED) with self.settings(BILLING_ENABLED=False): realm = do_import_realm('var/test-export', 'test-zulip-2') self.assertTrue(realm.plan_type, Realm.SELF_HOSTED)
[ "str", "Realm", "str", "int", "int", "str", "str", "str", "int", "str", "List[Dict[str, Any]]", "str", "Callable[[Realm], Any]", "Realm", "Realm", "Recipient", "Realm", "Realm", "int", "CustomProfileFieldValue", "List[CustomProfileField]", "Realm", "str", "str", "str", "Realm", "str", "Realm", "Realm", "Realm", "Realm", "Realm" ]
[ 1730, 6682, 7435, 11981, 11996, 14246, 14258, 14437, 14449, 16806, 16971, 17000, 20119, 21065, 21235, 21588, 22072, 22423, 22792, 22921, 23150, 23960, 24291, 24653, 25177, 25557, 26083, 26522, 26871, 27241, 27437, 27699 ]
[ 1733, 6687, 7438, 11984, 11999, 14249, 14261, 14440, 14452, 16809, 16991, 17003, 20141, 21070, 21240, 21597, 22077, 22428, 22795, 22944, 23174, 23965, 24294, 24656, 25180, 25562, 26086, 26527, 26876, 27246, 27442, 27704 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_json_encoder_for_html.py
import json from zerver.lib.json_encoder_for_html import JSONEncoderForHTML from zerver.lib.test_classes import ZulipTestCase class TestJSONEncoder(ZulipTestCase): # Test EncoderForHTML # Taken from # https://github.com/simplejson/simplejson/blob/8edc82afcf6f7512b05fba32baa536fe756bd273/simplejson/tests/test_encode_for_html.py # License: MIT decoder = json.JSONDecoder() encoder = JSONEncoderForHTML() def test_basic_encode(self) -> None: self.assertEqual(r'"\u0026"', self.encoder.encode('&')) self.assertEqual(r'"\u003c"', self.encoder.encode('<')) self.assertEqual(r'"\u003e"', self.encoder.encode('>')) def test_basic_roundtrip(self) -> None: for char in '&<>': self.assertEqual( char, self.decoder.decode( self.encoder.encode(char))) def test_prevent_script_breakout(self) -> None: bad_string = '</script><script>alert("gotcha")</script>' self.assertEqual( r'"\u003c/script\u003e\u003cscript\u003e' r'alert(\"gotcha\")\u003c/script\u003e"', self.encoder.encode(bad_string)) self.assertEqual( bad_string, self.decoder.decode( self.encoder.encode(bad_string)))
[]
[]
[]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_legacy_subject.py
from zerver.lib.test_classes import ( ZulipTestCase, ) class LegacySubjectTest(ZulipTestCase): def test_legacy_subject(self) -> None: self.login(self.example_email("hamlet")) payload = dict( type='stream', to='Verona', client='test suite', content='Test message', ) payload['subject'] = 'whatever' result = self.client_post("/json/messages", payload) self.assert_json_success(result) # You can't use both subject and topic. payload['topic'] = 'whatever' result = self.client_post("/json/messages", payload) self.assert_json_error(result, "Can't decide between 'topic' and 'subject' arguments")
[]
[]
[]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_link_embed.py
# -*- coding: utf-8 -*- import mock import ujson from typing import Any from requests.exceptions import ConnectionError from django.test import override_settings from zerver.models import Recipient, Message from zerver.lib.actions import queue_json_publish from zerver.lib.test_classes import ZulipTestCase from zerver.lib.test_helpers import MockPythonResponse from zerver.worker.queue_processors import FetchLinksEmbedData from zerver.lib.url_preview.preview import ( get_link_embed_data, link_embed_data_from_cache) from zerver.lib.url_preview.oembed import get_oembed_data from zerver.lib.url_preview.parsers import ( OpenGraphParser, GenericParser) from zerver.lib.cache import cache_set, NotFoundInCache, preview_url_cache_key TEST_CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'default', }, 'database': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'url-preview', } } @override_settings(INLINE_URL_EMBED_PREVIEW=True) class OembedTestCase(ZulipTestCase): @mock.patch('pyoembed.requests.get') def test_present_provider(self, get: Any) -> None: get.return_value = response = mock.Mock() response.headers = {'content-type': 'application/json'} response.ok = True response_data = { 'type': 'rich', 'thumbnail_url': 'https://scontent.cdninstagram.com/t51.2885-15/n.jpg', 'thumbnail_width': 640, 'thumbnail_height': 426, 'title': 'NASA', 'html': '<p>test</p>', 'version': '1.0', 'width': 658, 'height': None} response.text = ujson.dumps(response_data) url = 'http://instagram.com/p/BLtI2WdAymy' data = get_oembed_data(url) self.assertIsInstance(data, dict) self.assertIn('title', data) assert data is not None # allow mypy to infer data is indexable self.assertEqual(data['title'], response_data['title']) @mock.patch('pyoembed.requests.get') def test_error_request(self, get: Any) -> None: get.return_value = response = mock.Mock() response.ok = False url = 'http://instagram.com/p/BLtI2WdAymy' data = get_oembed_data(url) self.assertIsNone(data) class OpenGraphParserTestCase(ZulipTestCase): def test_page_with_og(self) -> None: html = """<html> <head> <meta property="og:title" content="The Rock" /> <meta property="og:type" content="video.movie" /> <meta property="og:url" content="http://www.imdb.com/title/tt0117500/" /> <meta property="og:image" content="http://ia.media-imdb.com/images/rock.jpg" /> <meta property="og:description" content="The Rock film" /> </head> </html>""" parser = OpenGraphParser(html) result = parser.extract_data() self.assertIn('title', result) self.assertEqual(result['title'], 'The Rock') self.assertEqual(result.get('description'), 'The Rock film') class GenericParserTestCase(ZulipTestCase): def test_parser(self) -> None: html = """ <html> <head><title>Test title</title></head> <body> <h1>Main header</h1> <p>Description text</p> </body> </html> """ parser = GenericParser(html) result = parser.extract_data() self.assertEqual(result.get('title'), 'Test title') self.assertEqual(result.get('description'), 'Description text') def test_extract_image(self) -> None: html = """ <html> <body> <h1>Main header</h1> <img src="http://test.com/test.jpg"> <div> <p>Description text</p> </div> </body> </html> """ parser = GenericParser(html) result = parser.extract_data() self.assertEqual(result.get('title'), 'Main header') self.assertEqual(result.get('description'), 'Description text') self.assertEqual(result.get('image'), 'http://test.com/test.jpg') def test_extract_description(self) -> None: html = """ <html> <body> <div> <div> <p>Description text</p> </div> </div> </body> </html> """ parser = GenericParser(html) result = parser.extract_data() self.assertEqual(result.get('description'), 'Description text') html = """ <html> <head><meta name="description" content="description 123"</head> <body></body> </html> """ parser = GenericParser(html) result = parser.extract_data() self.assertEqual(result.get('description'), 'description 123') html = "<html><body></body></html>" parser = GenericParser(html) result = parser.extract_data() self.assertIsNone(result.get('description')) class PreviewTestCase(ZulipTestCase): open_graph_html = """ <html> <head> <title>Test title</title> <meta property="og:title" content="The Rock" /> <meta property="og:type" content="video.movie" /> <meta property="og:url" content="http://www.imdb.com/title/tt0117500/" /> <meta property="og:image" content="http://ia.media-imdb.com/images/rock.jpg" /> </head> <body> <h1>Main header</h1> <p>Description text</p> </body> </html> """ @override_settings(INLINE_URL_EMBED_PREVIEW=True) def test_edit_message_history(self) -> None: email = self.example_email('hamlet') self.login(email) msg_id = self.send_stream_message(email, "Scotland", topic_name="editing", content="original") url = 'http://test.org/' response = MockPythonResponse(self.open_graph_html, 200) mocked_response = mock.Mock( side_effect=lambda k: {url: response}.get(k, MockPythonResponse('', 404))) with mock.patch('zerver.views.messages.queue_json_publish') as patched: result = self.client_patch("/json/messages/" + str(msg_id), { 'message_id': msg_id, 'content': url, }) self.assert_json_success(result) patched.assert_called_once() queue = patched.call_args[0][0] self.assertEqual(queue, "embed_links") event = patched.call_args[0][1] with self.settings(TEST_SUITE=False, CACHES=TEST_CACHES): with mock.patch('requests.get', mocked_response): FetchLinksEmbedData().consume(event) embedded_link = '<a href="{0}" target="_blank" title="The Rock">The Rock</a>'.format(url) msg = Message.objects.select_related("sender").get(id=msg_id) self.assertIn(embedded_link, msg.rendered_content) @override_settings(INLINE_URL_EMBED_PREVIEW=True) def _send_message_with_test_org_url(self, sender_email: str, queue_should_run: bool=True, relative_url: bool=False) -> Message: url = 'http://test.org/' with mock.patch('zerver.lib.actions.queue_json_publish') as patched: msg_id = self.send_personal_message( sender_email, self.example_email('cordelia'), content=url, ) if queue_should_run: patched.assert_called_once() queue = patched.call_args[0][0] self.assertEqual(queue, "embed_links") event = patched.call_args[0][1] else: patched.assert_not_called() # If we nothing was put in the queue, we don't need to # run the queue processor or any of the following code return Message.objects.select_related("sender").get(id=msg_id) # Verify the initial message doesn't have the embedded links rendered msg = Message.objects.select_related("sender").get(id=msg_id) self.assertNotIn( '<a href="{0}" target="_blank" title="The Rock">The Rock</a>'.format(url), msg.rendered_content) # Mock the network request result so the test can be fast without Internet response = MockPythonResponse(self.open_graph_html, 200) if relative_url is True: response = MockPythonResponse(self.open_graph_html.replace('http://ia.media-imdb.com', ''), 200) mocked_response = mock.Mock( side_effect=lambda k: {url: response}.get(k, MockPythonResponse('', 404))) # Run the queue processor to potentially rerender things with self.settings(TEST_SUITE=False, CACHES=TEST_CACHES): with mock.patch('requests.get', mocked_response): FetchLinksEmbedData().consume(event) msg = Message.objects.select_related("sender").get(id=msg_id) return msg @override_settings(INLINE_URL_EMBED_PREVIEW=True) def test_message_update_race_condition(self) -> None: email = self.example_email('hamlet') self.login(email) original_url = 'http://test.org/' edited_url = 'http://edited.org/' with mock.patch('zerver.lib.actions.queue_json_publish') as patched: msg_id = self.send_stream_message(email, "Scotland", topic_name="foo", content=original_url) patched.assert_called_once() queue = patched.call_args[0][0] self.assertEqual(queue, "embed_links") event = patched.call_args[0][1] def wrapped_queue_json_publish(*args: Any, **kwargs: Any) -> None: # Mock the network request result so the test can be fast without Internet response = MockPythonResponse(self.open_graph_html, 200) mocked_response_original = mock.Mock( side_effect=lambda k: {original_url: response}.get(k, MockPythonResponse('', 404))) mocked_response_edited = mock.Mock( side_effect=lambda k: {edited_url: response}.get(k, MockPythonResponse('', 404))) with self.settings(TEST_SUITE=False, CACHES=TEST_CACHES): with mock.patch('requests.get', mocked_response_original): # Run the queue processor. This will simulate the event for original_url being # processed after the message has been edited. FetchLinksEmbedData().consume(event) msg = Message.objects.select_related("sender").get(id=msg_id) # The content of the message has changed since the event for original_url has been created, # it should not be rendered. Another, up-to-date event will have been sent (edited_url). self.assertNotIn('<a href="{0}" target="_blank" title="The Rock">The Rock</a>'.format(original_url), msg.rendered_content) mocked_response_edited.assert_not_called() with self.settings(TEST_SUITE=False, CACHES=TEST_CACHES): with mock.patch('requests.get', mocked_response_edited): # Now proceed with the original queue_json_publish and call the # up-to-date event for edited_url. queue_json_publish(*args, **kwargs) msg = Message.objects.select_related("sender").get(id=msg_id) self.assertIn('<a href="{0}" target="_blank" title="The Rock">The Rock</a>'.format(edited_url), msg.rendered_content) with mock.patch('zerver.views.messages.queue_json_publish', wraps=wrapped_queue_json_publish) as patched: result = self.client_patch("/json/messages/" + str(msg_id), { 'message_id': msg_id, 'content': edited_url, }) self.assert_json_success(result) def test_get_link_embed_data(self) -> None: url = 'http://test.org/' embedded_link = '<a href="{0}" target="_blank" title="The Rock">The Rock</a>'.format(url) # When humans send, we should get embedded content. msg = self._send_message_with_test_org_url(sender_email=self.example_email('hamlet')) self.assertIn(embedded_link, msg.rendered_content) # We don't want embedded content for bots. msg = self._send_message_with_test_org_url(sender_email='webhook-bot@zulip.com', queue_should_run=False) self.assertNotIn(embedded_link, msg.rendered_content) # Try another human to make sure bot failure was due to the # bot sending the message and not some other reason. msg = self._send_message_with_test_org_url(sender_email=self.example_email('prospero')) self.assertIn(embedded_link, msg.rendered_content) def test_inline_url_embed_preview(self) -> None: with_preview = '<p><a href="http://test.org/" target="_blank" title="http://test.org/">http://test.org/</a></p>\n<div class="message_embed"><a class="message_embed_image" href="http://test.org/" style="background-image: url(http://ia.media-imdb.com/images/rock.jpg)" target="_blank"></a><div class="data-container"><div class="message_embed_title"><a href="http://test.org/" target="_blank" title="The Rock">The Rock</a></div><div class="message_embed_description">Description text</div></div></div>' without_preview = '<p><a href="http://test.org/" target="_blank" title="http://test.org/">http://test.org/</a></p>' msg = self._send_message_with_test_org_url(sender_email=self.example_email('hamlet')) self.assertEqual(msg.rendered_content, with_preview) realm = msg.get_realm() setattr(realm, 'inline_url_embed_preview', False) realm.save() msg = self._send_message_with_test_org_url(sender_email=self.example_email('prospero'), queue_should_run=False) self.assertEqual(msg.rendered_content, without_preview) @override_settings(INLINE_URL_EMBED_PREVIEW=True) def test_inline_relative_url_embed_preview(self) -> None: # Relative urls should not be sent for url preview. with mock.patch('zerver.lib.actions.queue_json_publish') as patched: self.send_personal_message( self.example_email('prospero'), self.example_email('cordelia'), content="http://zulip.testserver/api/", ) patched.assert_not_called() def test_inline_url_embed_preview_with_relative_image_url(self) -> None: with_preview_relative = '<p><a href="http://test.org/" target="_blank" title="http://test.org/">http://test.org/</a></p>\n<div class="message_embed"><a class="message_embed_image" href="http://test.org/" style="background-image: url(http://test.org/images/rock.jpg)" target="_blank"></a><div class="data-container"><div class="message_embed_title"><a href="http://test.org/" target="_blank" title="The Rock">The Rock</a></div><div class="message_embed_description">Description text</div></div></div>' # Try case where the opengraph image is a relative url. msg = self._send_message_with_test_org_url(sender_email=self.example_email('prospero'), relative_url=True) self.assertEqual(msg.rendered_content, with_preview_relative) def test_http_error_get_data(self) -> None: url = 'http://test.org/' msg_id = self.send_personal_message( self.example_email('hamlet'), self.example_email('cordelia'), content=url, ) msg = Message.objects.select_related("sender").get(id=msg_id) event = { 'message_id': msg_id, 'urls': [url], 'message_realm_id': msg.sender.realm_id, 'message_content': url} with self.settings(INLINE_URL_EMBED_PREVIEW=True, TEST_SUITE=False, CACHES=TEST_CACHES): with mock.patch('requests.get', mock.Mock(side_effect=ConnectionError())): with mock.patch('logging.error') as error_mock: FetchLinksEmbedData().consume(event) self.assertEqual(error_mock.call_count, 1) msg = Message.objects.get(id=msg_id) self.assertEqual( '<p><a href="http://test.org/" target="_blank" title="http://test.org/">http://test.org/</a></p>', msg.rendered_content) def test_invalid_link(self) -> None: with self.settings(INLINE_URL_EMBED_PREVIEW=True, TEST_SUITE=False, CACHES=TEST_CACHES): self.assertIsNone(get_link_embed_data('com.notvalidlink')) self.assertIsNone(get_link_embed_data(u'μένει.com.notvalidlink')) def test_link_embed_data_from_cache(self) -> None: url = 'http://test.org/' link_embed_data = 'test data' with self.assertRaises(NotFoundInCache): link_embed_data_from_cache(url) with self.settings(CACHES=TEST_CACHES): key = preview_url_cache_key(url) cache_set(key, link_embed_data, 'database') self.assertEqual(link_embed_data, link_embed_data_from_cache(url))
[ "Any", "Any", "str", "Any", "Any" ]
[ 1183, 2131, 7325, 9999, 10014 ]
[ 1186, 2134, 7328, 10002, 10017 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_logging_handlers.py
# -*- coding: utf-8 -*- import logging import sys from django.conf import settings from django.contrib.auth.models import AnonymousUser from django.http import HttpRequest, HttpResponse from django.test import RequestFactory, TestCase from django.utils.log import AdminEmailHandler from functools import wraps from mock import MagicMock, patch from mypy_extensions import NoReturn from typing import Any, Callable, Dict, Mapping, Optional, Iterator, Optional, Tuple, Type from types import TracebackType from zerver.lib.request import JsonableError from zerver.lib.types import ViewFuncT from zerver.lib.test_classes import ZulipTestCase from zerver.logging_handlers import AdminNotifyHandler from zerver.middleware import JsonErrorHandler from zerver.views.compatibility import check_compatibility from zerver.worker.queue_processors import QueueProcessingWorker captured_request = None # type: Optional[HttpRequest] captured_exc_info = None # type: Tuple[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]] def capture_and_throw(domain: Optional[str]=None) -> Callable[[ViewFuncT], ViewFuncT]: def wrapper(view_func: ViewFuncT) -> ViewFuncT: @wraps(view_func) def wrapped_view(request: HttpRequest, *args: Any, **kwargs: Any) -> NoReturn: global captured_request captured_request = request try: raise Exception("Request error") except Exception as e: global captured_exc_info captured_exc_info = sys.exc_info() raise e return wrapped_view # type: ignore # https://github.com/python/mypy/issues/1927 return wrapper class AdminNotifyHandlerTest(ZulipTestCase): logger = logging.getLogger('django') def setUp(self) -> None: self.handler = AdminNotifyHandler() # Prevent the exceptions we're going to raise from being printed # You may want to disable this when debugging tests settings.LOGGING_ENABLED = False global captured_exc_info global captured_request captured_request = None captured_exc_info = None def tearDown(self) -> None: settings.LOGGING_ENABLED = True def get_admin_zulip_handler(self) -> AdminNotifyHandler: return [ h for h in logging.getLogger('').handlers if isinstance(h, AdminNotifyHandler) ][0] @patch('zerver.logging_handlers.try_git_describe') def test_basic(self, mock_function: MagicMock) -> None: mock_function.return_value = None """A random exception passes happily through AdminNotifyHandler""" handler = self.get_admin_zulip_handler() try: raise Exception("Testing Error!") except Exception: exc_info = sys.exc_info() record = self.logger.makeRecord('name', logging.ERROR, 'function', 16, 'message', {}, exc_info) handler.emit(record) def simulate_error(self) -> logging.LogRecord: email = self.example_email('hamlet') self.login(email) with patch("zerver.decorator.rate_limit") as rate_limit_patch: rate_limit_patch.side_effect = capture_and_throw result = self.client_get("/json/users") self.assert_json_error(result, "Internal server error", status_code=500) rate_limit_patch.assert_called_once() record = self.logger.makeRecord('name', logging.ERROR, 'function', 15, 'message', {}, captured_exc_info) record.request = captured_request # type: ignore # this field is dynamically added return record def run_handler(self, record: logging.LogRecord) -> Dict[str, Any]: with patch('zerver.lib.error_notify.notify_server_error') as patched_notify: self.handler.emit(record) patched_notify.assert_called_once() return patched_notify.call_args[0][0] @patch('zerver.logging_handlers.try_git_describe') def test_long_exception_request(self, mock_function: MagicMock) -> None: mock_function.return_value = None """A request with no stack and multi-line report.getMessage() is handled properly""" record = self.simulate_error() record.exc_info = None record.msg = 'message\nmoremesssage\nmore' report = self.run_handler(record) self.assertIn("user_email", report) self.assertIn("message", report) self.assertIn("stack_trace", report) self.assertEqual(report['stack_trace'], 'message\nmoremesssage\nmore') self.assertEqual(report['message'], 'message') @patch('zerver.logging_handlers.try_git_describe') def test_request(self, mock_function: MagicMock) -> None: mock_function.return_value = None """A normal request is handled properly""" record = self.simulate_error() report = self.run_handler(record) self.assertIn("user_email", report) self.assertIn("message", report) self.assertIn("stack_trace", report) # Test that `add_request_metadata` throwing an exception is fine with patch("zerver.logging_handlers.traceback.print_exc"): with patch("zerver.logging_handlers.add_request_metadata", side_effect=Exception("Unexpected exception!")): report = self.run_handler(record) self.assertNotIn("user_email", report) self.assertIn("message", report) self.assertEqual(report["stack_trace"], "See /var/log/zulip/errors.log") # Check anonymous user is handled correctly record.request.user = AnonymousUser() # type: ignore # this field is dynamically added report = self.run_handler(record) self.assertIn("host", report) self.assertIn("user_email", report) self.assertIn("message", report) self.assertIn("stack_trace", report) # Now simulate a DisallowedHost exception 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 report = self.run_handler(record) record.request.get_host = orig_get_host # type: ignore # this field is dynamically added self.assertIn("host", report) self.assertIn("user_email", report) self.assertIn("message", report) self.assertIn("stack_trace", report) # Test an exception_filter exception with patch("zerver.logging_handlers.get_exception_reporter_filter", return_value=15): record.request.method = "POST" # type: ignore # this field is dynamically added report = self.run_handler(record) record.request.method = "GET" # type: ignore # this field is dynamically added self.assertIn("host", report) self.assertIn("user_email", report) self.assertIn("message", report) self.assertIn("stack_trace", report) # Test the catch-all exception handler doesn't throw with patch('zerver.lib.error_notify.notify_server_error', side_effect=Exception("queue error")): self.handler.emit(record) with self.settings(STAGING_ERROR_NOTIFICATIONS=False): with patch('zerver.logging_handlers.queue_json_publish', side_effect=Exception("queue error")): self.handler.emit(record) # Test no exc_info record.exc_info = None report = self.run_handler(record) self.assertIn("host", report) self.assertIn("user_email", report) self.assertIn("message", report) self.assertEqual(report["stack_trace"], 'No stack trace available') # Test arbitrary exceptions from request.user record.request.user = None # type: ignore # this field is dynamically added with patch("zerver.logging_handlers.traceback.print_exc"): report = self.run_handler(record) self.assertIn("host", report) self.assertIn("user_email", report) self.assertIn("message", report) self.assertIn("stack_trace", report) class LoggingConfigTest(TestCase): @staticmethod 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 for logger in loggerDict.values(): if not isinstance(logger, logging.Logger): continue yield logger def test_django_emails_disabled(self) -> None: for logger in self.all_loggers(): # The `handlers` attribute is undocumented, but see comment on # `all_loggers`. for handler in logger.handlers: assert not isinstance(handler, AdminEmailHandler) class ErrorFiltersTest(TestCase): def test_clean_data_from_query_parameters(self) -> None: from zerver.filters import clean_data_from_query_parameters self.assertEqual(clean_data_from_query_parameters("api_key=abcdz&stream=1"), "api_key=******&stream=******") self.assertEqual(clean_data_from_query_parameters("api_key=abcdz&stream=foo&topic=bar"), "api_key=******&stream=******&topic=******")
[ "ViewFuncT", "HttpRequest", "Any", "Any", "MagicMock", "logging.LogRecord", "MagicMock", "MagicMock" ]
[ 1158, 1243, 1263, 1278, 2526, 3753, 4125, 4806 ]
[ 1167, 1254, 1266, 1281, 2535, 3770, 4134, 4815 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_management_commands.py
# -*- coding: utf-8 -*- import glob import os import re from datetime import timedelta from email.utils import parseaddr from mock import MagicMock, patch, call from typing import List, Dict, Any, Optional from django.conf import settings from django.core.management import call_command from django.test import TestCase, override_settings from zerver.lib.actions import do_create_user from zerver.lib.management import ZulipBaseCommand, CommandError, check_config from zerver.lib.test_classes import ZulipTestCase from zerver.lib.test_helpers import stdout_suppressed from zerver.lib.test_runner import slow from zerver.models import get_user_profile_by_email from zerver.models import get_realm, UserProfile, Realm from confirmation.models import RealmCreationKey, generate_realm_creation_url class TestCheckConfig(ZulipTestCase): def test_check_config(self) -> None: with self.assertRaisesRegex(CommandError, "Error: You must set ZULIP_ADMINISTRATOR in /etc/zulip/settings.py."): check_config() with self.settings(REQUIRED_SETTINGS=[('asdf', 'not asdf')]): with self.assertRaisesRegex(CommandError, "Error: You must set asdf in /etc/zulip/settings.py."): check_config() @override_settings(WARN_NO_EMAIL=True) def test_check_send_email(self) -> None: with self.assertRaisesRegex(CommandError, "Outgoing email not yet configured, see"): call_command("send_test_email", 'test@example.com') class TestZulipBaseCommand(ZulipTestCase): def setUp(self) -> None: self.zulip_realm = get_realm("zulip") self.command = ZulipBaseCommand() def test_get_client(self) -> None: self.assertEqual(self.command.get_client().name, "ZulipServer") def test_get_realm(self) -> None: self.assertEqual(self.command.get_realm(dict(realm_id='zulip')), self.zulip_realm) self.assertEqual(self.command.get_realm(dict(realm_id=None)), None) self.assertEqual(self.command.get_realm(dict(realm_id='1')), self.zulip_realm) with self.assertRaisesRegex(CommandError, "There is no realm with id"): self.command.get_realm(dict(realm_id='17')) with self.assertRaisesRegex(CommandError, "There is no realm with id"): self.command.get_realm(dict(realm_id='mit')) def test_get_user(self) -> None: mit_realm = get_realm("zephyr") user_profile = self.example_user("hamlet") email = user_profile.email self.assertEqual(self.command.get_user(email, self.zulip_realm), user_profile) self.assertEqual(self.command.get_user(email, None), user_profile) error_message = "The realm '<Realm: zephyr 2>' does not contain a user with email" with self.assertRaisesRegex(CommandError, error_message): self.command.get_user(email, mit_realm) with self.assertRaisesRegex(CommandError, "server does not contain a user with email"): self.command.get_user('invalid_email@example.com', None) do_create_user(email, 'password', mit_realm, 'full_name', 'short_name') with self.assertRaisesRegex(CommandError, "server contains multiple users with that email"): self.command.get_user(email, None) def test_get_user_profile_by_email(self) -> None: user_profile = self.example_user("hamlet") email = user_profile.email self.assertEqual(get_user_profile_by_email(email), user_profile) def get_users_sorted(self, options: Dict[str, Any], realm: Optional[Realm]) -> List[UserProfile]: user_profiles = self.command.get_users(options, realm) return sorted(user_profiles, key = lambda x: x.email) def test_get_users(self) -> None: user_emails = self.example_email("hamlet") + "," + self.example_email("iago") expected_user_profiles = [self.example_user("hamlet"), self.example_user("iago")] user_profiles = self.get_users_sorted(dict(users=user_emails), self.zulip_realm) self.assertEqual(user_profiles, expected_user_profiles) user_profiles = self.get_users_sorted(dict(users=user_emails), None) self.assertEqual(user_profiles, expected_user_profiles) user_emails = self.example_email("iago") + "," + self.mit_email("sipbtest") expected_user_profiles = [self.example_user("iago"), self.mit_user("sipbtest")] user_profiles = self.get_users_sorted(dict(users=user_emails), None) self.assertEqual(user_profiles, expected_user_profiles) error_message = "The realm '<Realm: zulip 1>' does not contain a user with email" with self.assertRaisesRegex(CommandError, error_message): self.command.get_users(dict(users=user_emails), self.zulip_realm) self.assertEqual(self.command.get_users(dict(users=self.example_email("iago")), self.zulip_realm), [self.example_user("iago")]) self.assertEqual(self.command.get_users(dict(users=None), None), []) def test_get_users_with_all_users_argument_enabled(self) -> None: user_emails = self.example_email("hamlet") + "," + self.example_email("iago") expected_user_profiles = [self.example_user("hamlet"), self.example_user("iago")] user_profiles = self.get_users_sorted(dict(users=user_emails, all_users=False), self.zulip_realm) self.assertEqual(user_profiles, expected_user_profiles) error_message = "You can't use both -u/--users and -a/--all-users." with self.assertRaisesRegex(CommandError, error_message): self.command.get_users(dict(users=user_emails, all_users=True), None) expected_user_profiles = sorted(UserProfile.objects.filter(realm=self.zulip_realm), key = lambda x: x.email) user_profiles = self.get_users_sorted(dict(users=None, all_users=True), self.zulip_realm) self.assertEqual(user_profiles, expected_user_profiles) error_message = "You have to pass either -u/--users or -a/--all-users." with self.assertRaisesRegex(CommandError, error_message): self.command.get_users(dict(users=None, all_users=False), None) error_message = "The --all-users option requires a realm; please pass --realm." with self.assertRaisesRegex(CommandError, error_message): self.command.get_users(dict(users=None, all_users=True), None) class TestCommandsCanStart(TestCase): def setUp(self) -> None: self.commands = filter( lambda filename: filename != '__init__', map( lambda file: os.path.basename(file).replace('.py', ''), glob.iglob('*/management/commands/*.py') ) ) @slow("Aggregate of runs dozens of individual --help tests") def test_management_commands_show_help(self) -> None: with stdout_suppressed() as stdout: for command in self.commands: print('Testing management command: {}'.format(command), file=stdout) with self.assertRaises(SystemExit): call_command(command, '--help') # zerver/management/commands/runtornado.py sets this to True; # we need to reset it here. See #3685 for details. settings.RUNNING_INSIDE_TORNADO = False class TestSendWebhookFixtureMessage(TestCase): COMMAND_NAME = 'send_webhook_fixture_message' def setUp(self) -> None: self.fixture_path = os.path.join('some', 'fake', 'path.json') self.url = '/some/url/with/hook' @patch('zerver.management.commands.send_webhook_fixture_message.Command.print_help') def test_check_if_command_exits_when_fixture_param_is_empty(self, print_help_mock: MagicMock) -> None: with self.assertRaises(SystemExit): call_command(self.COMMAND_NAME, url=self.url) print_help_mock.assert_any_call('./manage.py', self.COMMAND_NAME) @patch('zerver.management.commands.send_webhook_fixture_message.Command.print_help') def test_check_if_command_exits_when_url_param_is_empty(self, print_help_mock: MagicMock) -> None: with self.assertRaises(SystemExit): call_command(self.COMMAND_NAME, fixture=self.fixture_path) print_help_mock.assert_any_call('./manage.py', self.COMMAND_NAME) @patch('zerver.management.commands.send_webhook_fixture_message.os.path.exists') def test_check_if_command_exits_when_fixture_path_does_not_exist( self, os_path_exists_mock: MagicMock) -> None: os_path_exists_mock.return_value = False with self.assertRaises(SystemExit): call_command(self.COMMAND_NAME, fixture=self.fixture_path, url=self.url) os_path_exists_mock.assert_any_call(os.path.join(settings.DEPLOY_ROOT, self.fixture_path)) @patch('zerver.management.commands.send_webhook_fixture_message.os.path.exists') @patch('zerver.management.commands.send_webhook_fixture_message.Client') @patch('zerver.management.commands.send_webhook_fixture_message.ujson') @patch("zerver.management.commands.send_webhook_fixture_message.open", create=True) def test_check_if_command_post_request_to_url_with_fixture(self, open_mock: MagicMock, ujson_mock: MagicMock, client_mock: MagicMock, os_path_exists_mock: MagicMock) -> None: ujson_mock.loads.return_value = '{}' ujson_mock.dumps.return_value = {} os_path_exists_mock.return_value = True client = client_mock() with self.assertRaises(SystemExit): call_command(self.COMMAND_NAME, fixture=self.fixture_path, url=self.url) self.assertTrue(ujson_mock.dumps.called) self.assertTrue(ujson_mock.loads.called) self.assertTrue(open_mock.called) client.post.assert_called_once_with(self.url, {}, content_type="application/json", HTTP_HOST="zulip.testserver") class TestGenerateRealmCreationLink(ZulipTestCase): COMMAND_NAME = "generate_realm_creation_link" @override_settings(OPEN_REALM_CREATION=False) def test_generate_link_and_create_realm(self) -> None: email = "user1@test.com" generated_link = generate_realm_creation_url(by_admin=True) # Get realm creation page result = self.client_get(generated_link) self.assert_in_success_response([u"Create a new Zulip organization"], result) # Enter email self.assertIsNone(get_realm('test')) result = self.client_post(generated_link, {'email': email}) self.assertEqual(result.status_code, 302) self.assertTrue(re.search(r'/accounts/do_confirm/\w+$', result["Location"])) # Bypass sending mail for confirmation, go straight to creation form result = self.client_get(result["Location"]) self.assert_in_response('action="/accounts/register/"', result) # Original link is now dead result = self.client_get(generated_link) self.assert_in_success_response(["The organization creation link has expired or is not valid."], result) @override_settings(OPEN_REALM_CREATION=False) def test_generate_link_confirm_email(self) -> None: email = "user1@test.com" generated_link = generate_realm_creation_url(by_admin=False) result = self.client_post(generated_link, {'email': email}) self.assertEqual(result.status_code, 302) self.assertTrue(re.search('/accounts/new/send_confirm/{}$'.format(email), result["Location"])) result = self.client_get(result["Location"]) self.assert_in_response("Check your email so we can get started", result) # Original link is now dead result = self.client_get(generated_link) self.assert_in_success_response(["The organization creation link has expired or is not valid."], result) @override_settings(OPEN_REALM_CREATION=False) def test_realm_creation_with_random_link(self) -> None: # Realm creation attempt with an invalid link should fail random_link = "/new/5e89081eb13984e0f3b130bf7a4121d153f1614b" result = self.client_get(random_link) self.assert_in_success_response(["The organization creation link has expired or is not valid."], result) @override_settings(OPEN_REALM_CREATION=False) def test_realm_creation_with_expired_link(self) -> None: generated_link = generate_realm_creation_url(by_admin=True) key = generated_link[-24:] # Manually expire the link by changing the date of creation obj = RealmCreationKey.objects.get(creation_key=key) obj.date_created = obj.date_created - timedelta(days=settings.REALM_CREATION_LINK_VALIDITY_DAYS + 1) obj.save() result = self.client_get(generated_link) self.assert_in_success_response(["The organization creation link has expired or is not valid."], result) class TestCalculateFirstVisibleMessageID(ZulipTestCase): COMMAND_NAME = 'calculate_first_visible_message_id' def test_check_if_command_calls_maybe_update_first_visible_message_id(self) -> None: with patch('zerver.lib.message.maybe_update_first_visible_message_id') as m: call_command(self.COMMAND_NAME, "--realm=zulip", "--lookback-hours=30") m.assert_called_with(get_realm("zulip"), 30) with patch('zerver.lib.message.maybe_update_first_visible_message_id') as m: call_command(self.COMMAND_NAME, "--lookback-hours=35") calls = [call(realm, 35) for realm in Realm.objects.all()] m.has_calls(calls, any_order=True) class TestPasswordRestEmail(ZulipTestCase): COMMAND_NAME = "send_password_reset_email" def test_if_command_sends_password_reset_email(self) -> None: call_command(self.COMMAND_NAME, users=self.example_email("iago")) from django.core.mail import outbox from_email = outbox[0].from_email self.assertIn("Zulip Account Security", from_email) tokenized_no_reply_email = parseaddr(from_email)[1] self.assertTrue(re.search(self.TOKENIZED_NOREPLY_REGEX, tokenized_no_reply_email)) self.assertIn("Psst. Word on the street is that you", outbox[0].body)
[ "Dict[str, Any]", "Optional[Realm]", "MagicMock", "MagicMock", "MagicMock", "MagicMock", "MagicMock", "MagicMock", "MagicMock" ]
[ 3510, 3533, 7748, 8118, 8523, 9292, 9378, 9465, 9560 ]
[ 3524, 3548, 7757, 8127, 8532, 9301, 9387, 9474, 9569 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_message_edit_notifications.py
# -*- coding: utf-8 -*- from typing import Any, Dict, Generator, Mapping, Union import mock from django.utils.timezone import now as timezone_now from zerver.lib.actions import ( get_client, ) from zerver.lib.test_classes import ( ZulipTestCase, ) from zerver.models import ( get_stream_recipient, Recipient, Subscription, UserPresence, ) from zerver.tornado.event_queue import ( maybe_enqueue_notifications, ) class EditMessageSideEffectsTest(ZulipTestCase): def _assert_update_does_not_notify_anybody(self, message_id: int, content: str) -> None: url = '/json/messages/' + str(message_id) request = dict( message_id=message_id, content=content, ) with mock.patch('zerver.tornado.event_queue.maybe_enqueue_notifications') as m: result = self.client_patch(url, request) self.assert_json_success(result) self.assertFalse(m.called) def test_updates_with_pm_mention(self) -> None: hamlet = self.example_user('hamlet') cordelia = self.example_user('cordelia') self.login(hamlet.email) message_id = self.send_personal_message( hamlet.email, cordelia.email, content='no mention' ) self._assert_update_does_not_notify_anybody( message_id=message_id, content='now we mention @**Cordelia Lear**', ) def _login_and_send_original_stream_message(self, content: str) -> int: ''' Note our conventions here: Hamlet is our logged in user (and sender). Cordelia is the receiver we care about. Scotland is the stream we send messages to. ''' hamlet = self.example_user('hamlet') cordelia = self.example_user('cordelia') self.login(hamlet.email) self.subscribe(hamlet, 'Scotland') self.subscribe(cordelia, 'Scotland') message_id = self.send_stream_message( hamlet.email, 'Scotland', content=content, ) return message_id def _get_queued_data_for_message_update(self, message_id: int, content: str, expect_short_circuit: bool=False) -> Dict[str, Any]: ''' This function updates a message with a post to /json/messages/(message_id). By using mocks, we are able to capture two pieces of data: enqueue_kwargs: These are the arguments passed in to maybe_enqueue_notifications. queue_messages: These are the messages that maybe_enqueue_notifications actually puts on the queue. Using this helper allows you to construct a test that goes pretty deep into the missed-messages codepath, without actually queuing the final messages. ''' url = '/json/messages/' + str(message_id) request = dict( message_id=message_id, content=content, ) with mock.patch('zerver.tornado.event_queue.maybe_enqueue_notifications') as m: result = self.client_patch(url, request) cordelia = self.example_user('cordelia') cordelia_calls = [ call_args for call_args in m.call_args_list if call_args[1]['user_profile_id'] == cordelia.id ] if expect_short_circuit: self.assertEqual(len(cordelia_calls), 0) return {} # Normally we expect maybe_enqueue_notifications to be # called for Cordelia, so continue on. self.assertEqual(len(cordelia_calls), 1) enqueue_kwargs = cordelia_calls[0][1] queue_messages = [] def fake_publish(queue_name: str, event: Union[Mapping[str, Any], str], *args: Any) -> None: queue_messages.append(dict( queue_name=queue_name, event=event, )) with mock.patch('zerver.tornado.event_queue.queue_json_publish') as m: m.side_effect = fake_publish maybe_enqueue_notifications(**enqueue_kwargs) self.assert_json_success(result) return dict( enqueue_kwargs=enqueue_kwargs, queue_messages=queue_messages ) def test_updates_with_stream_mention(self) -> None: message_id = self._login_and_send_original_stream_message( content='no mention', ) info = self._get_queued_data_for_message_update( message_id=message_id, content='now we mention @**Cordelia Lear**', ) cordelia = self.example_user('cordelia') expected_enqueue_kwargs = dict( user_profile_id=cordelia.id, message_id=message_id, private_message=False, mentioned=True, stream_push_notify=False, stream_email_notify=False, stream_name='Scotland', always_push_notify=False, idle=True, already_notified={}, ) self.assertEqual(info['enqueue_kwargs'], expected_enqueue_kwargs) queue_messages = info['queue_messages'] self.assertEqual(len(queue_messages), 2) self.assertEqual(queue_messages[0]['queue_name'], 'missedmessage_mobile_notifications') mobile_event = queue_messages[0]['event'] self.assertEqual(mobile_event['user_profile_id'], cordelia.id) self.assertEqual(mobile_event['trigger'], 'mentioned') self.assertEqual(queue_messages[1]['queue_name'], 'missedmessage_emails') email_event = queue_messages[1]['event'] self.assertEqual(email_event['user_profile_id'], cordelia.id) self.assertEqual(email_event['trigger'], 'mentioned') def test_second_mention_is_ignored(self) -> None: message_id = self._login_and_send_original_stream_message( content='hello @**Cordelia Lear**' ) self._get_queued_data_for_message_update( message_id=message_id, content='re-mention @**Cordelia Lear**', expect_short_circuit=True, ) def _turn_on_stream_push_for_cordelia(self) -> None: ''' conventions: Cordelia is the message receiver we care about. Scotland is our stream. ''' cordelia = self.example_user('cordelia') stream = self.subscribe(cordelia, 'Scotland') recipient = get_stream_recipient(stream.id) cordelia_subscription = Subscription.objects.get( user_profile_id=cordelia.id, recipient=recipient, ) cordelia_subscription.push_notifications = True cordelia_subscription.save() def test_updates_with_stream_push_notify(self) -> None: self._turn_on_stream_push_for_cordelia() message_id = self._login_and_send_original_stream_message( content='no mention' ) # Even though Cordelia configured this stream for pushes, # we short-ciruit the logic, assuming the original message # also did a push. self._get_queued_data_for_message_update( message_id=message_id, content='nothing special about updated message', expect_short_circuit=True, ) def _cordelia_connected_to_zulip(self) -> Any: ''' Right now the easiest way to make Cordelia look connected to Zulip is to mock the function below. This is a bit blunt, as it affects other users too, but we only really look at Cordelia's data, anyway. ''' return mock.patch( 'zerver.tornado.event_queue.receiver_is_off_zulip', return_value=False ) def test_stream_push_notify_for_sorta_present_user(self) -> None: self._turn_on_stream_push_for_cordelia() message_id = self._login_and_send_original_stream_message( content='no mention' ) # Simulate Cordelia still has an actively polling client, but # the lack of presence info should still mark her as offline. # # Despite Cordelia being offline, we still short circuit # offline notifications due to the her stream push setting. with self._cordelia_connected_to_zulip(): self._get_queued_data_for_message_update( message_id=message_id, content='nothing special about updated message', expect_short_circuit=True, ) def _make_cordelia_present_on_web(self) -> None: cordelia = self.example_user('cordelia') UserPresence.objects.create( user_profile_id=cordelia.id, status=UserPresence.ACTIVE, client=get_client('web'), timestamp=timezone_now(), ) def test_stream_push_notify_for_fully_present_user(self) -> None: self._turn_on_stream_push_for_cordelia() message_id = self._login_and_send_original_stream_message( content='no mention' ) self._make_cordelia_present_on_web() # Simulate Cordelia is FULLY present, not just in term of # browser activity, but also in terms of her client descriptors. with self._cordelia_connected_to_zulip(): self._get_queued_data_for_message_update( message_id=message_id, content='nothing special about updated message', expect_short_circuit=True, ) def test_always_push_notify_for_fully_present_mentioned_user(self) -> None: cordelia = self.example_user('cordelia') cordelia.enable_online_push_notifications = True cordelia.save() message_id = self._login_and_send_original_stream_message( content='no mention' ) self._make_cordelia_present_on_web() # Simulate Cordelia is FULLY present, not just in term of # browser activity, but also in terms of her client descriptors. with self._cordelia_connected_to_zulip(): info = self._get_queued_data_for_message_update( message_id=message_id, content='newly mention @**Cordelia Lear**', ) expected_enqueue_kwargs = dict( user_profile_id=cordelia.id, message_id=message_id, private_message=False, mentioned=True, stream_push_notify=False, stream_email_notify=False, stream_name='Scotland', always_push_notify=True, idle=False, already_notified={}, ) self.assertEqual(info['enqueue_kwargs'], expected_enqueue_kwargs) queue_messages = info['queue_messages'] self.assertEqual(len(queue_messages), 1) def test_always_push_notify_for_fully_present_boring_user(self) -> None: cordelia = self.example_user('cordelia') cordelia.enable_online_push_notifications = True cordelia.save() message_id = self._login_and_send_original_stream_message( content='no mention' ) self._make_cordelia_present_on_web() # Simulate Cordelia is FULLY present, not just in term of # browser activity, but also in terms of her client descriptors. with self._cordelia_connected_to_zulip(): info = self._get_queued_data_for_message_update( message_id=message_id, content='nothing special about updated message', ) expected_enqueue_kwargs = dict( user_profile_id=cordelia.id, message_id=message_id, private_message=False, mentioned=False, stream_push_notify=False, stream_email_notify=False, stream_name='Scotland', always_push_notify=True, idle=False, already_notified={}, ) self.assertEqual(info['enqueue_kwargs'], expected_enqueue_kwargs) queue_messages = info['queue_messages'] # Even though Cordelia has enable_online_push_notifications set # to True, we don't send her any offline notifications, since she # was not mentioned. self.assertEqual(len(queue_messages), 0) def test_updates_with_stream_mention_of_sorta_present_user(self) -> None: cordelia = self.example_user('cordelia') message_id = self._login_and_send_original_stream_message( content='no mention' ) # We will simulate that the user still has a an active client, # but they don't have UserPresence rows, so we will still # send offline notifications. with self._cordelia_connected_to_zulip(): info = self._get_queued_data_for_message_update( message_id=message_id, content='now we mention @**Cordelia Lear**', ) expected_enqueue_kwargs = dict( user_profile_id=cordelia.id, message_id=message_id, private_message=False, mentioned=True, stream_push_notify=False, stream_email_notify=False, stream_name='Scotland', always_push_notify=False, idle=True, already_notified={}, ) self.assertEqual(info['enqueue_kwargs'], expected_enqueue_kwargs) # She will get messages enqueued. (Other tests drill down on the # actual content of these messages.) self.assertEqual(len(info['queue_messages']), 2) def test_updates_with_stream_mention_of_fully_present_user(self) -> None: cordelia = self.example_user('cordelia') message_id = self._login_and_send_original_stream_message( content='no mention' ) self._make_cordelia_present_on_web() # Simulate Cordelia is FULLY present, not just in term of # browser activity, but also in terms of her client descriptors. with self._cordelia_connected_to_zulip(): info = self._get_queued_data_for_message_update( message_id=message_id, content='now we mention @**Cordelia Lear**', ) expected_enqueue_kwargs = dict( user_profile_id=cordelia.id, message_id=message_id, private_message=False, mentioned=True, stream_push_notify=False, stream_email_notify=False, stream_name='Scotland', always_push_notify=False, idle=False, already_notified={}, ) self.assertEqual(info['enqueue_kwargs'], expected_enqueue_kwargs) # Because Cordelia is FULLY present, we don't need to send any offline # push notifications or missed message emails. self.assertEqual(len(info['queue_messages']), 0)
[ "int", "str", "str", "int", "str", "str", "Union[Mapping[str, Any], str]", "Any" ]
[ 561, 575, 1505, 2200, 2214, 3858, 3895, 3958 ]
[ 564, 578, 1508, 2203, 2217, 3861, 3924, 3961 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_messages.py
# -*- coding: utf-8 -*- from django.db import IntegrityError from django.db.models import Q, Max from django.conf import settings from django.http import HttpResponse from django.test import TestCase, override_settings from django.utils.timezone import now as timezone_now from django.utils.timezone import utc as timezone_utc from zerver.lib import bugdown from zerver.decorator import JsonableError from zerver.lib.test_runner import slow from zerver.lib.cache import get_stream_cache_key, cache_delete from zerver.lib.message import estimate_recent_messages from zerver.lib.addressee import Addressee from zerver.lib.actions import ( check_message, check_send_stream_message, create_mirror_user_if_needed, do_add_alert_words, do_change_stream_invite_only, do_create_user, do_deactivate_user, do_send_messages, do_set_realm_property, extract_recipients, get_active_presence_idle_user_ids, get_client, get_last_message_id, get_user_info_for_message_updates, internal_prep_private_message, internal_prep_stream_message, internal_send_huddle_message, internal_send_message, internal_send_private_message, internal_send_stream_message, send_rate_limited_pm_notification_to_bot_owner, ) from zerver.lib.create_user import ( create_user_profile, ) from zerver.lib.message import ( MessageDict, bulk_access_messages, get_first_visible_message_id, get_raw_unread_data, maybe_update_first_visible_message_id, messages_for_ids, sew_messages_and_reactions, update_first_visible_message_id, ) from zerver.lib.test_helpers import ( get_user_messages, make_client, message_stream_count, most_recent_message, most_recent_usermessage, queries_captured, get_subscription, ) from zerver.lib.test_classes import ( ZulipTestCase, ) from zerver.lib.topic import ( LEGACY_PREV_TOPIC, DB_TOPIC_NAME, ) from zerver.lib.soft_deactivation import ( add_missing_messages, do_soft_activate_users, do_soft_deactivate_users, maybe_catch_up_soft_deactivated_user, ) from zerver.models import ( MAX_MESSAGE_LENGTH, MAX_TOPIC_NAME_LENGTH, Message, Realm, Recipient, Stream, UserMessage, UserProfile, Attachment, RealmAuditLog, RealmDomain, get_realm, UserPresence, Subscription, get_stream, get_stream_recipient, get_system_bot, get_user, Reaction, flush_per_request_caches, ScheduledMessage ) from zerver.lib.timestamp import convert_to_UTC, datetime_to_timestamp from zerver.lib.timezone import get_timezone from zerver.lib.upload import create_attachment from zerver.lib.url_encoding import near_message_url from zerver.views.messages import create_mirrored_message_users from analytics.lib.counts import CountStat, LoggingCountStat, COUNT_STATS from analytics.models import RealmCount import datetime import DNS import mock import time import ujson from typing import Any, Dict, List, Optional, Set from collections import namedtuple class MiscMessageTest(ZulipTestCase): def test_get_last_message_id(self) -> None: self.assertEqual( get_last_message_id(), Message.objects.latest('id').id ) Message.objects.all().delete() self.assertEqual(get_last_message_id(), -1) class TopicHistoryTest(ZulipTestCase): def test_topics_history_zephyr_mirror(self) -> None: user_profile = self.mit_user('sipbtest') stream_name = 'new_stream' # Send a message to this new stream from another user self.subscribe(self.mit_user("starnine"), stream_name) stream = get_stream(stream_name, user_profile.realm) self.send_stream_message(self.mit_email("starnine"), stream_name, topic_name="secret topic", sender_realm="zephyr") # Now subscribe this MIT user to the new stream and verify # that the new topic is not accessible self.login(user_profile.email, realm=user_profile.realm) self.subscribe(user_profile, stream_name) endpoint = '/json/users/me/%d/topics' % (stream.id,) result = self.client_get(endpoint, dict(), subdomain="zephyr") self.assert_json_success(result) history = result.json()['topics'] self.assertEqual(history, []) def test_topics_history(self) -> None: # verified: int(UserMessage.flags.read) == 1 user_profile = self.example_user('iago') email = user_profile.email stream_name = 'Verona' self.login(email) stream = get_stream(stream_name, user_profile.realm) recipient = get_stream_recipient(stream.id) def create_test_message(topic: str) -> int: # TODO: Clean this up to send messages the normal way. hamlet = self.example_user('hamlet') message = Message( sender=hamlet, recipient=recipient, content='whatever', pub_date=timezone_now(), sending_client=get_client('whatever'), ) message.set_topic_name(topic) message.save() UserMessage.objects.create( user_profile=user_profile, message=message, flags=0, ) return message.id # our most recent topics are topic0, topic1, topic2 # Create old messages with strange spellings. create_test_message('topic2') create_test_message('toPIc1') create_test_message('toPIc0') create_test_message('topic2') create_test_message('topic2') create_test_message('Topic2') # Create new messages topic2_msg_id = create_test_message('topic2') create_test_message('topic1') create_test_message('topic1') topic1_msg_id = create_test_message('topic1') topic0_msg_id = create_test_message('topic0') endpoint = '/json/users/me/%d/topics' % (stream.id,) result = self.client_get(endpoint, dict()) self.assert_json_success(result) history = result.json()['topics'] # We only look at the most recent three topics, because # the prior fixture data may be unreliable. history = history[:3] self.assertEqual([topic['name'] for topic in history], [ 'topic0', 'topic1', 'topic2', ]) self.assertEqual([topic['max_id'] for topic in history], [ topic0_msg_id, topic1_msg_id, topic2_msg_id, ]) # Now try as cordelia, who we imagine as a totally new user in # that she doesn't have UserMessage rows. We should see the # same results for a public stream. self.login(self.example_email("cordelia")) result = self.client_get(endpoint, dict()) self.assert_json_success(result) history = result.json()['topics'] # We only look at the most recent three topics, because # the prior fixture data may be unreliable. history = history[:3] self.assertEqual([topic['name'] for topic in history], [ 'topic0', 'topic1', 'topic2', ]) self.assertIn('topic0', [topic['name'] for topic in history]) self.assertEqual([topic['max_id'] for topic in history], [ topic0_msg_id, topic1_msg_id, topic2_msg_id, ]) # Now make stream private, but subscribe cordelia do_change_stream_invite_only(stream, True) self.subscribe(self.example_user("cordelia"), stream.name) result = self.client_get(endpoint, dict()) self.assert_json_success(result) history = result.json()['topics'] history = history[:3] # Cordelia doesn't have these recent history items when we # wasn't subscribed in her results. self.assertNotIn('topic0', [topic['name'] for topic in history]) self.assertNotIn('topic1', [topic['name'] for topic in history]) self.assertNotIn('topic2', [topic['name'] for topic in history]) def test_bad_stream_id(self) -> None: email = self.example_email("iago") self.login(email) # non-sensible stream id endpoint = '/json/users/me/9999999999/topics' result = self.client_get(endpoint, dict()) self.assert_json_error(result, 'Invalid stream id') # out of realm bad_stream = self.make_stream( 'mit_stream', realm=get_realm('zephyr') ) endpoint = '/json/users/me/%s/topics' % (bad_stream.id,) result = self.client_get(endpoint, dict()) self.assert_json_error(result, 'Invalid stream id') # private stream to which I am not subscribed private_stream = self.make_stream( 'private_stream', invite_only=True ) endpoint = '/json/users/me/%s/topics' % (private_stream.id,) result = self.client_get(endpoint, dict()) self.assert_json_error(result, 'Invalid stream id') class TestCrossRealmPMs(ZulipTestCase): def make_realm(self, domain: str) -> Realm: realm = Realm.objects.create(string_id=domain, invite_required=False) RealmDomain.objects.create(realm=realm, domain=domain) return realm def create_user(self, email: str) -> UserProfile: subdomain = email.split("@")[1] self.register(email, 'test', subdomain=subdomain) return get_user(email, get_realm(subdomain)) @slow("Sends a large number of messages") @override_settings(CROSS_REALM_BOT_EMAILS=['feedback@zulip.com', 'welcome-bot@zulip.com', 'support@3.example.com']) def test_realm_scenarios(self) -> None: self.make_realm('1.example.com') r2 = self.make_realm('2.example.com') self.make_realm('3.example.com') def assert_message_received(to_user: UserProfile, from_user: UserProfile) -> None: messages = get_user_messages(to_user) self.assertEqual(messages[-1].sender.id, from_user.id) def assert_invalid_email() -> Any: return self.assertRaisesRegex( JsonableError, 'Invalid email ') user1_email = 'user1@1.example.com' user1a_email = 'user1a@1.example.com' user2_email = 'user2@2.example.com' user3_email = 'user3@3.example.com' feedback_email = 'feedback@zulip.com' support_email = 'support@3.example.com' # note: not zulip.com user1 = self.create_user(user1_email) user1a = self.create_user(user1a_email) user2 = self.create_user(user2_email) self.create_user(user3_email) feedback_bot = get_system_bot(feedback_email) with self.settings(CROSS_REALM_BOT_EMAILS=['feedback@zulip.com', 'welcome-bot@zulip.com']): # HACK: We should probably be creating this "bot" user another # way, but since you can't register a user with a # cross-realm email, we need to hide this for now. support_bot = self.create_user(support_email) # Users can PM themselves self.send_personal_message(user1_email, user1_email, sender_realm="1.example.com") assert_message_received(user1, user1) # Users on the same realm can PM each other self.send_personal_message(user1_email, user1a_email, sender_realm="1.example.com") assert_message_received(user1a, user1) # Cross-realm bots in the zulip.com realm can PM any realm # (They need lower level APIs to do this.) internal_send_private_message( realm=r2, sender=get_system_bot(feedback_email), recipient_user=get_user(user2_email, r2), content='bla', ) assert_message_received(user2, feedback_bot) # All users can PM cross-realm bots in the zulip.com realm self.send_personal_message(user1_email, feedback_email, sender_realm="1.example.com") assert_message_received(feedback_bot, user1) # Users can PM cross-realm bots on non-zulip realms. # (The support bot represents some theoretical bot that we may # create in the future that does not have zulip.com as its realm.) self.send_personal_message(user1_email, support_email, sender_realm="1.example.com") assert_message_received(support_bot, user1) # Allow sending PMs to two different cross-realm bots simultaneously. # (We don't particularly need this feature, but since users can # already individually send PMs to cross-realm bots, we shouldn't # prevent them from sending multiple bots at once. We may revisit # this if it's a nuisance for huddles.) self.send_huddle_message(user1_email, [feedback_email, support_email], sender_realm="1.example.com") assert_message_received(feedback_bot, user1) assert_message_received(support_bot, user1) # Prevent old loophole where I could send PMs to other users as long # as I copied a cross-realm bot from the same realm. with assert_invalid_email(): self.send_huddle_message(user1_email, [user3_email, support_email], sender_realm="1.example.com") # Users on three different realms can't PM each other, # even if one of the users is a cross-realm bot. with assert_invalid_email(): self.send_huddle_message(user1_email, [user2_email, feedback_email], sender_realm="1.example.com") with assert_invalid_email(): self.send_huddle_message(feedback_email, [user1_email, user2_email]) # Users on the different realms cannot PM each other with assert_invalid_email(): self.send_personal_message(user1_email, user2_email, sender_realm="1.example.com") # Users on non-zulip realms can't PM "ordinary" Zulip users with assert_invalid_email(): self.send_personal_message(user1_email, "hamlet@zulip.com", sender_realm="1.example.com") # Users on three different realms cannot PM each other with assert_invalid_email(): self.send_huddle_message(user1_email, [user2_email, user3_email], sender_realm="1.example.com") class InternalPrepTest(ZulipTestCase): def test_returns_for_internal_sends(self) -> None: # For our internal_send_* functions we return # if the prep stages fail. This is mostly defensive # code, since we are generally creating the messages # ourselves, but we want to make sure that the functions # won't actually explode if we give them bad content. bad_content = '' realm = get_realm('zulip') cordelia = self.example_user('cordelia') hamlet = self.example_user('hamlet') othello = self.example_user('othello') stream_name = 'Verona' with mock.patch('logging.exception') as m: internal_send_private_message( realm=realm, sender=cordelia, recipient_user=hamlet, content=bad_content, ) arg = m.call_args_list[0][0][0] self.assertIn('Message must not be empty', arg) with mock.patch('logging.exception') as m: internal_send_huddle_message( realm=realm, sender=cordelia, emails=[hamlet.email, othello.email], content=bad_content, ) arg = m.call_args_list[0][0][0] self.assertIn('Message must not be empty', arg) with mock.patch('logging.exception') as m: internal_send_stream_message( realm=realm, sender=cordelia, stream_name=stream_name, topic='whatever', content=bad_content, ) arg = m.call_args_list[0][0][0] self.assertIn('Message must not be empty', arg) with mock.patch('logging.exception') as m: internal_send_message( realm=realm, sender_email=settings.ERROR_BOT, recipient_type_name='stream', recipients=stream_name, topic_name='whatever', content=bad_content, ) arg = m.call_args_list[0][0][0] self.assertIn('Message must not be empty', arg) def test_error_handling(self) -> None: realm = get_realm('zulip') sender = self.example_user('cordelia') recipient_user = self.example_user('hamlet') content = 'x' * 15000 result = internal_prep_private_message( realm=realm, sender=sender, recipient_user=recipient_user, content=content) message = result['message'] self.assertIn('message was too long', message.content) with self.assertRaises(RuntimeError): internal_prep_private_message( realm=None, # should cause error sender=sender, recipient_user=recipient_user, content=content) # Simulate sending a message to somebody not in the # realm of the sender. recipient_user = self.mit_user('starnine') with mock.patch('logging.exception') as logging_mock: result = internal_prep_private_message( realm=realm, sender=sender, recipient_user=recipient_user, content=content) arg = logging_mock.call_args_list[0][0][0] prefix = "Error queueing internal message by cordelia@zulip.com: You can't send private messages outside of your organization." self.assertTrue(arg.startswith(prefix)) def test_ensure_stream_gets_called(self) -> None: realm = get_realm('zulip') sender = self.example_user('cordelia') stream_name = 'test_stream' topic = 'whatever' content = 'hello' internal_prep_stream_message( realm=realm, sender=sender, stream_name=stream_name, topic=topic, content=content) # This would throw an error if the stream # wasn't automatically created. Stream.objects.get(name=stream_name, realm_id=realm.id) class ExtractedRecipientsTest(TestCase): def test_extract_recipients(self) -> None: # JSON list w/dups, empties, and trailing whitespace s = ujson.dumps([' alice@zulip.com ', ' bob@zulip.com ', ' ', 'bob@zulip.com']) self.assertEqual(sorted(extract_recipients(s)), ['alice@zulip.com', 'bob@zulip.com']) # simple string with one name s = 'alice@zulip.com ' self.assertEqual(extract_recipients(s), ['alice@zulip.com']) # JSON-encoded string s = '"alice@zulip.com"' self.assertEqual(extract_recipients(s), ['alice@zulip.com']) # bare comma-delimited string s = 'bob@zulip.com, alice@zulip.com' self.assertEqual(sorted(extract_recipients(s)), ['alice@zulip.com', 'bob@zulip.com']) # JSON-encoded, comma-delimited string s = '"bob@zulip.com,alice@zulip.com"' self.assertEqual(sorted(extract_recipients(s)), ['alice@zulip.com', 'bob@zulip.com']) # Invalid data s = ujson.dumps(dict(color='red')) with self.assertRaisesRegex(ValueError, 'Invalid data type for recipients'): extract_recipients(s) class PersonalMessagesTest(ZulipTestCase): def test_near_pm_message_url(self) -> None: realm = get_realm('zulip') message = dict( type='personal', id=555, display_recipient=[ dict(id=77), dict(id=80), ], ) url = near_message_url( realm=realm, message=message, ) self.assertEqual(url, 'http://zulip.testserver/#narrow/pm-with/77,80-pm/near/555') def test_is_private_flag_not_leaked(self) -> None: """ Make sure `is_private` flag is not leaked to the API. """ self.login(self.example_email("hamlet")) self.send_personal_message(self.example_email("hamlet"), self.example_email("cordelia"), "test") for msg in self.get_messages(): self.assertNotIn('is_private', msg['flags']) def test_auto_subbed_to_personals(self) -> None: """ Newly created users are auto-subbed to the ability to receive personals. """ test_email = self.nonreg_email('test') self.register(test_email, "test") user_profile = self.nonreg_user('test') old_messages_count = message_stream_count(user_profile) self.send_personal_message(test_email, test_email) new_messages_count = message_stream_count(user_profile) self.assertEqual(new_messages_count, old_messages_count + 1) recipient = Recipient.objects.get(type_id=user_profile.id, type=Recipient.PERSONAL) message = most_recent_message(user_profile) self.assertEqual(message.recipient, recipient) with mock.patch('zerver.models.get_display_recipient', return_value='recip'): self.assertEqual(str(message), '<Message: recip / / ' '<UserProfile: test@zulip.com <Realm: zulip 1>>>') user_message = most_recent_usermessage(user_profile) self.assertEqual(str(user_message), '<UserMessage: recip / test@zulip.com ([])>' ) @slow("checks several profiles") def test_personal_to_self(self) -> None: """ If you send a personal to yourself, only you see it. """ old_user_profiles = list(UserProfile.objects.all()) test_email = self.nonreg_email('test1') self.register(test_email, "test1") old_messages = [] for user_profile in old_user_profiles: old_messages.append(message_stream_count(user_profile)) self.send_personal_message(test_email, test_email) new_messages = [] for user_profile in old_user_profiles: new_messages.append(message_stream_count(user_profile)) self.assertEqual(old_messages, new_messages) user_profile = self.nonreg_user('test1') recipient = Recipient.objects.get(type_id=user_profile.id, type=Recipient.PERSONAL) self.assertEqual(most_recent_message(user_profile).recipient, recipient) def assert_personal(self, sender_email: str, receiver_email: str, content: str="testcontent") -> None: """ Send a private message from `sender_email` to `receiver_email` and check that only those two parties actually received the message. """ realm = get_realm('zulip') # Assume realm is always 'zulip' sender = get_user(sender_email, realm) receiver = get_user(receiver_email, realm) sender_messages = message_stream_count(sender) receiver_messages = message_stream_count(receiver) other_user_profiles = UserProfile.objects.filter(~Q(email=sender_email) & ~Q(email=receiver_email)) old_other_messages = [] for user_profile in other_user_profiles: old_other_messages.append(message_stream_count(user_profile)) self.send_personal_message(sender_email, receiver_email, content) # Users outside the conversation don't get the message. new_other_messages = [] for user_profile in other_user_profiles: new_other_messages.append(message_stream_count(user_profile)) self.assertEqual(old_other_messages, new_other_messages) # The personal message is in the streams of both the sender and receiver. self.assertEqual(message_stream_count(sender), sender_messages + 1) self.assertEqual(message_stream_count(receiver), receiver_messages + 1) recipient = Recipient.objects.get(type_id=receiver.id, type=Recipient.PERSONAL) self.assertEqual(most_recent_message(sender).recipient, recipient) self.assertEqual(most_recent_message(receiver).recipient, recipient) def test_personal(self) -> None: """ If you send a personal, only you and the recipient see it. """ self.login(self.example_email("hamlet")) self.assert_personal(self.example_email("hamlet"), self.example_email("othello")) def test_non_ascii_personal(self) -> None: """ Sending a PM containing non-ASCII characters succeeds. """ self.login(self.example_email("hamlet")) self.assert_personal(self.example_email("hamlet"), self.example_email("othello"), u"hümbüǵ") class StreamMessagesTest(ZulipTestCase): def assert_stream_message(self, stream_name: str, topic_name: str="test topic", content: str="test content") -> None: """ Check that messages sent to a stream reach all subscribers to that stream. """ realm = get_realm('zulip') subscribers = self.users_subscribed_to_stream(stream_name, realm) # Outgoing webhook bots don't store UserMessage rows; they will be processed later. subscribers = [subscriber for subscriber in subscribers if subscriber.bot_type != UserProfile.OUTGOING_WEBHOOK_BOT] old_subscriber_messages = [] for subscriber in subscribers: old_subscriber_messages.append(message_stream_count(subscriber)) non_subscribers = [user_profile for user_profile in UserProfile.objects.all() if user_profile not in subscribers] old_non_subscriber_messages = [] for non_subscriber in non_subscribers: old_non_subscriber_messages.append(message_stream_count(non_subscriber)) non_bot_subscribers = [user_profile for user_profile in subscribers if not user_profile.is_bot] a_subscriber_email = non_bot_subscribers[0].email self.login(a_subscriber_email) self.send_stream_message(a_subscriber_email, stream_name, content=content, topic_name=topic_name) # Did all of the subscribers get the message? new_subscriber_messages = [] for subscriber in subscribers: new_subscriber_messages.append(message_stream_count(subscriber)) # Did non-subscribers not get the message? new_non_subscriber_messages = [] for non_subscriber in non_subscribers: new_non_subscriber_messages.append(message_stream_count(non_subscriber)) self.assertEqual(old_non_subscriber_messages, new_non_subscriber_messages) self.assertEqual(new_subscriber_messages, [elt + 1 for elt in old_subscriber_messages]) def test_performance(self) -> None: ''' This test is part of the automated test suite, but it is more intended as an aid to measuring the performance of do_send_messages() with consistent data setup across different commits. You can modify the values below and run just this test, and then comment out the print statement toward the bottom. ''' num_messages = 2 num_extra_users = 10 sender = self.example_user('cordelia') realm = sender.realm message_content = 'whatever' stream = get_stream('Denmark', realm) topic_name = 'lunch' recipient = get_stream_recipient(stream.id) sending_client = make_client(name="test suite") for i in range(num_extra_users): # Make every other user be idle. long_term_idle = i % 2 > 0 email = 'foo%d@example.com' % (i,) user = UserProfile.objects.create( realm=realm, email=email, pointer=0, long_term_idle=long_term_idle, ) Subscription.objects.create( user_profile=user, recipient=recipient ) def send_test_message() -> None: message = Message( sender=sender, recipient=recipient, content=message_content, pub_date=timezone_now(), sending_client=sending_client, ) message.set_topic_name(topic_name) do_send_messages([dict(message=message)]) before_um_count = UserMessage.objects.count() t = time.time() for i in range(num_messages): send_test_message() delay = time.time() - t assert(delay) # quiet down lint # print(delay) after_um_count = UserMessage.objects.count() ums_created = after_um_count - before_um_count num_active_users = num_extra_users / 2 self.assertTrue(ums_created > (num_active_users * num_messages)) def test_not_too_many_queries(self) -> None: recipient_list = [self.example_user("hamlet"), self.example_user("iago"), self.example_user("cordelia"), self.example_user("othello")] for user_profile in recipient_list: self.subscribe(user_profile, "Denmark") sender = self.example_user('hamlet') sending_client = make_client(name="test suite") stream_name = 'Denmark' topic_name = 'foo' content = 'whatever' realm = sender.realm # To get accurate count of the queries, we should make sure that # caches don't come into play. If we count queries while caches are # filled, we will get a lower count. Caches are not supposed to be # persistent, so our test can also fail if cache is invalidated # during the course of the unit test. flush_per_request_caches() cache_delete(get_stream_cache_key(stream_name, realm.id)) with queries_captured() as queries: check_send_stream_message( sender=sender, client=sending_client, stream_name=stream_name, topic=topic_name, body=content, ) self.assert_length(queries, 14) def test_stream_message_dict(self) -> None: user_profile = self.example_user('iago') self.subscribe(user_profile, "Denmark") self.send_stream_message(self.example_email("hamlet"), "Denmark", content="whatever", topic_name="my topic") message = most_recent_message(user_profile) row = MessageDict.get_raw_db_rows([message.id])[0] dct = MessageDict.build_dict_from_raw_db_row(row) MessageDict.post_process_dicts([dct], apply_markdown=True, client_gravatar=False) self.assertEqual(dct['display_recipient'], 'Denmark') stream = get_stream('Denmark', user_profile.realm) self.assertEqual(dct['stream_id'], stream.id) def test_stream_message_unicode(self) -> None: user_profile = self.example_user('iago') self.subscribe(user_profile, "Denmark") self.send_stream_message(self.example_email("hamlet"), "Denmark", content="whatever", topic_name="my topic") message = most_recent_message(user_profile) self.assertEqual(str(message), u'<Message: Denmark / my topic / ' '<UserProfile: hamlet@zulip.com <Realm: zulip 1>>>') def test_message_mentions(self) -> None: user_profile = self.example_user('iago') self.subscribe(user_profile, "Denmark") self.send_stream_message(self.example_email("hamlet"), "Denmark", content="test @**Iago** rules") message = most_recent_message(user_profile) assert(UserMessage.objects.get(user_profile=user_profile, message=message).flags.mentioned.is_set) def test_is_private_flag(self) -> None: user_profile = self.example_user('iago') self.subscribe(user_profile, "Denmark") self.send_stream_message(self.example_email("hamlet"), "Denmark", content="test") message = most_recent_message(user_profile) self.assertFalse(UserMessage.objects.get(user_profile=user_profile, message=message).flags.is_private.is_set) self.send_personal_message(self.example_email("hamlet"), user_profile.email, content="test") message = most_recent_message(user_profile) self.assertTrue(UserMessage.objects.get(user_profile=user_profile, message=message).flags.is_private.is_set) def _send_stream_message(self, email: str, stream_name: str, content: str) -> Set[int]: with mock.patch('zerver.lib.actions.send_event') as m: self.send_stream_message( email, stream_name, content=content ) self.assertEqual(m.call_count, 1) users = m.call_args[0][2] user_ids = {u['id'] for u in users} return user_ids def test_unsub_mention(self) -> None: cordelia = self.example_user('cordelia') hamlet = self.example_user('hamlet') stream_name = 'Test Stream' self.subscribe(hamlet, stream_name) UserMessage.objects.filter( user_profile=cordelia ).delete() def mention_cordelia() -> Set[int]: content = 'test @**Cordelia Lear** rules' user_ids = self._send_stream_message( email=hamlet.email, stream_name=stream_name, content=content ) return user_ids def num_cordelia_messages() -> int: return UserMessage.objects.filter( user_profile=cordelia ).count() user_ids = mention_cordelia() self.assertEqual(0, num_cordelia_messages()) self.assertNotIn(cordelia.id, user_ids) # Make sure test isn't too brittle-subscribing # Cordelia and mentioning her should give her a # message. self.subscribe(cordelia, stream_name) user_ids = mention_cordelia() self.assertIn(cordelia.id, user_ids) self.assertEqual(1, num_cordelia_messages()) def test_message_bot_mentions(self) -> None: cordelia = self.example_user('cordelia') hamlet = self.example_user('hamlet') realm = hamlet.realm stream_name = 'Test Stream' self.subscribe(hamlet, stream_name) normal_bot = do_create_user( email='normal-bot@zulip.com', password='', realm=realm, full_name='Normal Bot', short_name='', bot_type=UserProfile.DEFAULT_BOT, bot_owner=cordelia, ) content = 'test @**Normal Bot** rules' user_ids = self._send_stream_message( email=hamlet.email, stream_name=stream_name, content=content ) self.assertIn(normal_bot.id, user_ids) user_message = most_recent_usermessage(normal_bot) self.assertEqual(user_message.message.content, content) self.assertTrue(user_message.flags.mentioned) def test_stream_message_mirroring(self) -> None: from zerver.lib.actions import do_change_is_admin user_profile = self.example_user('iago') email = user_profile.email do_change_is_admin(user_profile, True, 'api_super_user') result = self.api_post(email, "/api/v1/messages", {"type": "stream", "to": "Verona", "sender": self.example_email("cordelia"), "client": "test suite", "topic": "announcement", "content": "Everyone knows Iago rules", "forged": "true"}) self.assert_json_success(result) do_change_is_admin(user_profile, False, 'api_super_user') result = self.api_post(email, "/api/v1/messages", {"type": "stream", "to": "Verona", "sender": self.example_email("cordelia"), "client": "test suite", "topic": "announcement", "content": "Everyone knows Iago rules", "forged": "true"}) self.assert_json_error(result, "User not authorized for this query") def test_message_to_stream(self) -> None: """ If you send a message to a stream, everyone subscribed to the stream receives the messages. """ self.assert_stream_message("Scotland") def test_non_ascii_stream_message(self) -> None: """ Sending a stream message containing non-ASCII characters in the stream name, topic, or message body succeeds. """ self.login(self.example_email("hamlet")) # Subscribe everyone to a stream with non-ASCII characters. non_ascii_stream_name = u"hümbüǵ" realm = get_realm("zulip") stream = self.make_stream(non_ascii_stream_name) for user_profile in UserProfile.objects.filter(is_active=True, is_bot=False, realm=realm)[0:3]: self.subscribe(user_profile, stream.name) self.assert_stream_message(non_ascii_stream_name, topic_name=u"hümbüǵ", content=u"hümbüǵ") def test_get_raw_unread_data_for_huddle_messages(self) -> None: users = [ self.example_user('hamlet'), self.example_user('cordelia'), self.example_user('iago'), self.example_user('prospero'), self.example_user('othello'), ] message1_id = self.send_huddle_message(users[0].email, [user.email for user in users], "test content 1") message2_id = self.send_huddle_message(users[0].email, [user.email for user in users], "test content 2") msg_data = get_raw_unread_data(users[1]) # both the messages are present in msg_data self.assertIn(message1_id, msg_data["huddle_dict"].keys()) self.assertIn(message2_id, msg_data["huddle_dict"].keys()) # only these two messages are present in msg_data self.assertEqual(len(msg_data["huddle_dict"].keys()), 2) class MessageDictTest(ZulipTestCase): @slow('builds lots of messages') def test_bulk_message_fetching(self) -> None: sender = self.example_user('othello') receiver = self.example_user('hamlet') pm_recipient = Recipient.objects.get(type_id=receiver.id, type=Recipient.PERSONAL) stream_name = u'Çiğdem' stream = self.make_stream(stream_name) stream_recipient = Recipient.objects.get(type_id=stream.id, type=Recipient.STREAM) sending_client = make_client(name="test suite") ids = [] for i in range(300): for recipient in [pm_recipient, stream_recipient]: message = Message( sender=sender, recipient=recipient, content='whatever %d' % i, rendered_content='DOES NOT MATTER', rendered_content_version=bugdown.version, pub_date=timezone_now(), sending_client=sending_client, last_edit_time=timezone_now(), edit_history='[]' ) message.set_topic_name('whatever') message.save() ids.append(message.id) Reaction.objects.create(user_profile=sender, message=message, emoji_name='simple_smile') num_ids = len(ids) self.assertTrue(num_ids >= 600) flush_per_request_caches() t = time.time() with queries_captured() as queries: rows = list(MessageDict.get_raw_db_rows(ids)) objs = [ MessageDict.build_dict_from_raw_db_row(row) for row in rows ] MessageDict.post_process_dicts(objs, apply_markdown=False, client_gravatar=False) delay = time.time() - t # Make sure we don't take longer than 1.5ms per message to # extract messages. Note that we increased this from 1ms to # 1.5ms to handle tests running in parallel being a bit # slower. error_msg = "Number of ids: {}. Time delay: {}".format(num_ids, delay) self.assertTrue(delay < 0.0015 * num_ids, error_msg) self.assert_length(queries, 7) self.assertEqual(len(rows), num_ids) def test_applying_markdown(self) -> None: sender = self.example_user('othello') receiver = self.example_user('hamlet') recipient = Recipient.objects.get(type_id=receiver.id, type=Recipient.PERSONAL) sending_client = make_client(name="test suite") message = Message( sender=sender, recipient=recipient, content='hello **world**', pub_date=timezone_now(), sending_client=sending_client, last_edit_time=timezone_now(), edit_history='[]' ) message.set_topic_name('whatever') message.save() # An important part of this test is to get the message through this exact code path, # because there is an ugly hack we need to cover. So don't just say "row = message". row = MessageDict.get_raw_db_rows([message.id])[0] dct = MessageDict.build_dict_from_raw_db_row(row) expected_content = '<p>hello <strong>world</strong></p>' self.assertEqual(dct['rendered_content'], expected_content) message = Message.objects.get(id=message.id) self.assertEqual(message.rendered_content, expected_content) self.assertEqual(message.rendered_content_version, bugdown.version) @mock.patch("zerver.lib.message.bugdown.convert") def test_applying_markdown_invalid_format(self, convert_mock: Any) -> None: # pretend the converter returned an invalid message without raising an exception convert_mock.return_value = None sender = self.example_user('othello') receiver = self.example_user('hamlet') recipient = Recipient.objects.get(type_id=receiver.id, type=Recipient.PERSONAL) sending_client = make_client(name="test suite") message = Message( sender=sender, recipient=recipient, content='hello **world**', pub_date=timezone_now(), sending_client=sending_client, last_edit_time=timezone_now(), edit_history='[]' ) message.set_topic_name('whatever') message.save() # An important part of this test is to get the message through this exact code path, # because there is an ugly hack we need to cover. So don't just say "row = message". row = MessageDict.get_raw_db_rows([message.id])[0] dct = MessageDict.build_dict_from_raw_db_row(row) error_content = '<p>[Zulip note: Sorry, we could not understand the formatting of your message]</p>' self.assertEqual(dct['rendered_content'], error_content) def test_reaction(self) -> None: sender = self.example_user('othello') receiver = self.example_user('hamlet') recipient = Recipient.objects.get(type_id=receiver.id, type=Recipient.PERSONAL) sending_client = make_client(name="test suite") message = Message( sender=sender, recipient=recipient, content='hello **world**', pub_date=timezone_now(), sending_client=sending_client, last_edit_time=timezone_now(), edit_history='[]' ) message.set_topic_name('whatever') message.save() reaction = Reaction.objects.create( message=message, user_profile=sender, emoji_name='simple_smile') row = MessageDict.get_raw_db_rows([message.id])[0] msg_dict = MessageDict.build_dict_from_raw_db_row(row) self.assertEqual(msg_dict['reactions'][0]['emoji_name'], reaction.emoji_name) self.assertEqual(msg_dict['reactions'][0]['user']['id'], sender.id) self.assertEqual(msg_dict['reactions'][0]['user']['email'], sender.email) self.assertEqual(msg_dict['reactions'][0]['user']['full_name'], sender.full_name) def test_missing_anchor(self) -> None: self.login(self.example_email("hamlet")) result = self.client_get( '/json/messages?use_first_unread_anchor=false&num_before=1&num_after=1') self.assert_json_error( result, "Missing 'anchor' argument (or set 'use_first_unread_anchor'=True).") class SewMessageAndReactionTest(ZulipTestCase): def test_sew_messages_and_reaction(self) -> None: sender = self.example_user('othello') receiver = self.example_user('hamlet') pm_recipient = Recipient.objects.get(type_id=receiver.id, type=Recipient.PERSONAL) stream_name = u'Çiğdem' stream = self.make_stream(stream_name) stream_recipient = Recipient.objects.get(type_id=stream.id, type=Recipient.STREAM) sending_client = make_client(name="test suite") needed_ids = [] for i in range(5): for recipient in [pm_recipient, stream_recipient]: message = Message( sender=sender, recipient=recipient, content='whatever %d' % i, pub_date=timezone_now(), sending_client=sending_client, last_edit_time=timezone_now(), edit_history='[]' ) message.set_topic_name('whatever') message.save() needed_ids.append(message.id) reaction = Reaction(user_profile=sender, message=message, emoji_name='simple_smile') reaction.save() messages = Message.objects.filter(id__in=needed_ids).values( *['id', 'content']) reactions = Reaction.get_raw_db_rows(needed_ids) tied_data = sew_messages_and_reactions(messages, reactions) for data in tied_data: self.assertEqual(len(data['reactions']), 1) self.assertEqual(data['reactions'][0]['emoji_name'], 'simple_smile') self.assertTrue(data['id']) self.assertTrue(data['content']) class MessagePOSTTest(ZulipTestCase): def test_message_to_self(self) -> None: """ Sending a message to a stream to which you are subscribed is successful. """ self.login(self.example_email("hamlet")) result = self.client_post("/json/messages", {"type": "stream", "to": "Verona", "client": "test suite", "content": "Test message", "topic": "Test topic"}) self.assert_json_success(result) def test_api_message_to_self(self) -> None: """ Same as above, but for the API view """ email = self.example_email("hamlet") result = self.api_post(email, "/api/v1/messages", {"type": "stream", "to": "Verona", "client": "test suite", "content": "Test message", "topic": "Test topic"}) self.assert_json_success(result) def test_message_to_announce(self) -> None: """ Sending a message to an announcement_only stream by a realm admin successful. """ user_profile = self.example_user("iago") self.login(user_profile.email) stream_name = "Verona" stream = get_stream(stream_name, user_profile.realm) stream.is_announcement_only = True stream.save() result = self.client_post("/json/messages", {"type": "stream", "to": stream_name, "client": "test suite", "content": "Test message", "topic": "Test topic"}) self.assert_json_success(result) # Cross realm bots should be allowed. notification_bot = get_system_bot("notification-bot@zulip.com") result = self.api_post(notification_bot.email, "/json/messages", {"type": "stream", "to": stream_name, "client": "test suite", "content": "Test message", "topic": "Test topic"}) self.assert_json_success(result) def test_message_fail_to_announce(self) -> None: """ Sending a message to an announcement_only stream not by a realm admin fails. """ user_profile = self.example_user("hamlet") self.login(user_profile.email) stream_name = "Verona" stream = get_stream(stream_name, user_profile.realm) stream.is_announcement_only = True stream.save() result = self.client_post("/json/messages", {"type": "stream", "to": stream_name, "client": "test suite", "content": "Test message", "topic": "Test topic"}) self.assert_json_error(result, "Only organization administrators can send to this stream.") def test_api_message_with_default_to(self) -> None: """ Sending messages without a to field should be sent to the default stream for the user_profile. """ user_profile = self.example_user('hamlet') email = user_profile.email user_profile.default_sending_stream_id = get_stream('Verona', user_profile.realm).id user_profile.save() result = self.api_post(email, "/api/v1/messages", {"type": "stream", "client": "test suite", "content": "Test message no to", "topic": "Test topic"}) self.assert_json_success(result) sent_message = self.get_last_message() self.assertEqual(sent_message.content, "Test message no to") def test_message_to_nonexistent_stream(self) -> None: """ Sending a message to a nonexistent stream fails. """ self.login(self.example_email("hamlet")) self.assertFalse(Stream.objects.filter(name="nonexistent_stream")) result = self.client_post("/json/messages", {"type": "stream", "to": "nonexistent_stream", "client": "test suite", "content": "Test message", "topic": "Test topic"}) self.assert_json_error(result, "Stream 'nonexistent_stream' does not exist") def test_message_to_nonexistent_stream_with_bad_characters(self) -> None: """ Nonexistent stream name with bad characters should be escaped properly. """ self.login(self.example_email("hamlet")) self.assertFalse(Stream.objects.filter(name="""&<"'><non-existent>""")) result = self.client_post("/json/messages", {"type": "stream", "to": """&<"'><non-existent>""", "client": "test suite", "content": "Test message", "topic": "Test topic"}) self.assert_json_error(result, "Stream '&amp;&lt;&quot;&#39;&gt;&lt;non-existent&gt;' does not exist") def test_personal_message(self) -> None: """ Sending a personal message to a valid username is successful. """ self.login(self.example_email("hamlet")) result = self.client_post("/json/messages", {"type": "private", "content": "Test message", "client": "test suite", "to": self.example_email("othello")}) self.assert_json_success(result) def test_personal_message_copying_self(self) -> None: """ Sending a personal message to yourself plus another user is successful, and counts as a message just to that user. """ self.login(self.example_email("hamlet")) result = self.client_post("/json/messages", { "type": "private", "content": "Test message", "client": "test suite", "to": ujson.dumps([self.example_email("othello"), self.example_email("hamlet")])}) self.assert_json_success(result) msg = self.get_last_message() # Verify that we're not actually on the "recipient list" self.assertNotIn("Hamlet", str(msg.recipient)) def test_personal_message_to_nonexistent_user(self) -> None: """ Sending a personal message to an invalid email returns error JSON. """ self.login(self.example_email("hamlet")) result = self.client_post("/json/messages", {"type": "private", "content": "Test message", "client": "test suite", "to": "nonexistent"}) self.assert_json_error(result, "Invalid email 'nonexistent'") def test_personal_message_to_deactivated_user(self) -> None: """ Sending a personal message to a deactivated user returns error JSON. """ target_user_profile = self.example_user("othello") do_deactivate_user(target_user_profile) self.login(self.example_email("hamlet")) result = self.client_post("/json/messages", { "type": "private", "content": "Test message", "client": "test suite", "to": self.example_email("othello")}) self.assert_json_error(result, "'othello@zulip.com' is no longer using Zulip.") result = self.client_post("/json/messages", { "type": "private", "content": "Test message", "client": "test suite", "to": ujson.dumps([self.example_email("othello"), self.example_email("cordelia")])}) self.assert_json_error(result, "'othello@zulip.com' is no longer using Zulip.") def test_invalid_type(self) -> None: """ Sending a message of unknown type returns error JSON. """ self.login(self.example_email("hamlet")) result = self.client_post("/json/messages", {"type": "invalid type", "content": "Test message", "client": "test suite", "to": self.example_email("othello")}) self.assert_json_error(result, "Invalid message type") def test_empty_message(self) -> None: """ Sending a message that is empty or only whitespace should fail """ self.login(self.example_email("hamlet")) result = self.client_post("/json/messages", {"type": "private", "content": " ", "client": "test suite", "to": self.example_email("othello")}) self.assert_json_error(result, "Message must not be empty") def test_empty_string_topic(self) -> None: """ Sending a message that has empty string topic should fail """ self.login(self.example_email("hamlet")) result = self.client_post("/json/messages", {"type": "stream", "to": "Verona", "client": "test suite", "content": "Test message", "topic": ""}) self.assert_json_error(result, "Topic can't be empty") def test_missing_topic(self) -> None: """ Sending a message without topic should fail """ self.login(self.example_email("hamlet")) result = self.client_post("/json/messages", {"type": "stream", "to": "Verona", "client": "test suite", "content": "Test message"}) self.assert_json_error(result, "Missing topic") def test_invalid_message_type(self) -> None: """ Messages other than the type of "private" or "stream" are considered as invalid """ self.login(self.example_email("hamlet")) result = self.client_post("/json/messages", {"type": "invalid", "to": "Verona", "client": "test suite", "content": "Test message", "topic": "Test topic"}) self.assert_json_error(result, "Invalid message type") def test_private_message_without_recipients(self) -> None: """ Sending private message without recipients should fail """ self.login(self.example_email("hamlet")) result = self.client_post("/json/messages", {"type": "private", "content": "Test content", "client": "test suite", "to": ""}) self.assert_json_error(result, "Message must have recipients") def test_mirrored_huddle(self) -> None: """ Sending a mirrored huddle message works """ self.login(self.mit_email("starnine"), realm=get_realm("zephyr")) result = self.client_post("/json/messages", {"type": "private", "sender": self.mit_email("sipbtest"), "content": "Test message", "client": "zephyr_mirror", "to": ujson.dumps([self.mit_email("starnine"), self.mit_email("espuser")])}, subdomain="zephyr") self.assert_json_success(result) def test_mirrored_personal(self) -> None: """ Sending a mirrored personal message works """ self.login(self.mit_email("starnine"), realm=get_realm("zephyr")) result = self.client_post("/json/messages", {"type": "private", "sender": self.mit_email("sipbtest"), "content": "Test message", "client": "zephyr_mirror", "to": self.mit_email("starnine")}, subdomain="zephyr") self.assert_json_success(result) def test_mirrored_personal_to_someone_else(self) -> None: """ Sending a mirrored personal message to someone else is not allowed. """ self.login(self.mit_email("starnine"), realm=get_realm("zephyr")) result = self.client_post("/json/messages", {"type": "private", "sender": self.mit_email("sipbtest"), "content": "Test message", "client": "zephyr_mirror", "to": self.mit_email("espuser")}, subdomain="zephyr") self.assert_json_error(result, "User not authorized for this query") def test_duplicated_mirrored_huddle(self) -> None: """ Sending two mirrored huddles in the row return the same ID """ msg = {"type": "private", "sender": self.mit_email("sipbtest"), "content": "Test message", "client": "zephyr_mirror", "to": ujson.dumps([self.mit_email("espuser"), self.mit_email("starnine")])} with mock.patch('DNS.dnslookup', return_value=[['starnine:*:84233:101:Athena Consulting Exchange User,,,:/mit/starnine:/bin/bash']]): self.login(self.mit_email("starnine"), realm=get_realm("zephyr")) result1 = self.client_post("/json/messages", msg, subdomain="zephyr") with mock.patch('DNS.dnslookup', return_value=[['espuser:*:95494:101:Esp Classroom,,,:/mit/espuser:/bin/athena/bash']]): self.login(self.mit_email("espuser"), realm=get_realm("zephyr")) result2 = self.client_post("/json/messages", msg, subdomain="zephyr") self.assertEqual(ujson.loads(result1.content)['id'], ujson.loads(result2.content)['id']) def test_message_with_null_bytes(self) -> None: """ A message with null bytes in it is handled. """ self.login(self.example_email("hamlet")) post_data = {"type": "stream", "to": "Verona", "client": "test suite", "content": u" I like null bytes \x00 in my content", "topic": "Test topic"} result = self.client_post("/json/messages", post_data) self.assert_json_error(result, "Message must not contain null bytes") def test_strip_message(self) -> None: """ A message with mixed whitespace at the end is cleaned up. """ self.login(self.example_email("hamlet")) post_data = {"type": "stream", "to": "Verona", "client": "test suite", "content": " I like whitespace at the end! \n\n \n", "topic": "Test topic"} result = self.client_post("/json/messages", post_data) self.assert_json_success(result) sent_message = self.get_last_message() self.assertEqual(sent_message.content, " I like whitespace at the end!") def test_long_message(self) -> None: """ Sending a message longer than the maximum message length succeeds but is truncated. """ self.login(self.example_email("hamlet")) long_message = "A" * (MAX_MESSAGE_LENGTH + 1) post_data = {"type": "stream", "to": "Verona", "client": "test suite", "content": long_message, "topic": "Test topic"} result = self.client_post("/json/messages", post_data) self.assert_json_success(result) sent_message = self.get_last_message() self.assertEqual(sent_message.content, "A" * (MAX_MESSAGE_LENGTH - 3) + "...") def test_long_topic(self) -> None: """ Sending a message with a topic longer than the maximum topic length succeeds, but the topic is truncated. """ self.login(self.example_email("hamlet")) long_topic = "A" * (MAX_TOPIC_NAME_LENGTH + 1) post_data = {"type": "stream", "to": "Verona", "client": "test suite", "content": "test content", "topic": long_topic} result = self.client_post("/json/messages", post_data) self.assert_json_success(result) sent_message = self.get_last_message() self.assertEqual(sent_message.topic_name(), "A" * (MAX_TOPIC_NAME_LENGTH - 3) + "...") def test_send_forged_message_as_not_superuser(self) -> None: self.login(self.example_email("hamlet")) result = self.client_post("/json/messages", {"type": "stream", "to": "Verona", "client": "test suite", "content": "Test message", "topic": "Test topic", "forged": True}) self.assert_json_error(result, "User not authorized for this query") def test_send_message_as_not_superuser_to_different_domain(self) -> None: self.login(self.example_email("hamlet")) result = self.client_post("/json/messages", {"type": "stream", "to": "Verona", "client": "test suite", "content": "Test message", "topic": "Test topic", "realm_str": "mit"}) self.assert_json_error(result, "User not authorized for this query") def test_send_message_as_superuser_to_domain_that_dont_exist(self) -> None: user = get_system_bot(settings.EMAIL_GATEWAY_BOT) password = "test_password" user.set_password(password) user.is_api_super_user = True user.save() self.login(user.email, password) result = self.client_post("/json/messages", {"type": "stream", "to": "Verona", "client": "test suite", "content": "Test message", "topic": "Test topic", "realm_str": "non-existing"}) user.is_api_super_user = False user.save() self.assert_json_error(result, "Unknown organization 'non-existing'") def test_send_message_when_sender_is_not_set(self) -> None: self.login(self.mit_email("starnine"), realm=get_realm("zephyr")) result = self.client_post("/json/messages", {"type": "private", "content": "Test message", "client": "zephyr_mirror", "to": self.mit_email("starnine")}, subdomain="zephyr") self.assert_json_error(result, "Missing sender") def test_send_message_as_not_superuser_when_type_is_not_private(self) -> None: self.login(self.mit_email("starnine"), realm=get_realm("zephyr")) result = self.client_post("/json/messages", {"type": "not-private", "sender": self.mit_email("sipbtest"), "content": "Test message", "client": "zephyr_mirror", "to": self.mit_email("starnine")}, subdomain="zephyr") self.assert_json_error(result, "User not authorized for this query") @mock.patch("zerver.views.messages.create_mirrored_message_users") def test_send_message_create_mirrored_message_user_returns_invalid_input( self, create_mirrored_message_users_mock: Any) -> None: create_mirrored_message_users_mock.return_value = (False, True) self.login(self.mit_email("starnine"), realm=get_realm("zephyr")) result = self.client_post("/json/messages", {"type": "private", "sender": self.mit_email("sipbtest"), "content": "Test message", "client": "zephyr_mirror", "to": self.mit_email("starnine")}, subdomain="zephyr") self.assert_json_error(result, "Invalid mirrored message") @mock.patch("zerver.views.messages.create_mirrored_message_users") def test_send_message_when_client_is_zephyr_mirror_but_string_id_is_not_zephyr( self, create_mirrored_message_users_mock: Any) -> None: create_mirrored_message_users_mock.return_value = (True, True) user = self.mit_user("starnine") email = user.email user.realm.string_id = 'notzephyr' user.realm.save() self.login(email, realm=get_realm("notzephyr")) result = self.client_post("/json/messages", {"type": "private", "sender": self.mit_email("sipbtest"), "content": "Test message", "client": "zephyr_mirror", "to": email}, subdomain="notzephyr") self.assert_json_error(result, "Zephyr mirroring is not allowed in this organization") def test_send_message_irc_mirror(self) -> None: self.login(self.example_email('hamlet')) bot_info = { 'full_name': 'IRC bot', 'short_name': 'irc', } result = self.client_post("/json/bots", bot_info) self.assert_json_success(result) email = "irc-bot@zulip.testserver" user = get_user(email, get_realm('zulip')) user.is_api_super_user = True user.save() user = get_user(email, get_realm('zulip')) self.subscribe(user, "IRCland") # Simulate a mirrored message with a slightly old timestamp. fake_pub_date = timezone_now() - datetime.timedelta(minutes=37) fake_pub_time = datetime_to_timestamp(fake_pub_date) result = self.api_post(email, "/api/v1/messages", {"type": "stream", "forged": "true", "time": fake_pub_time, "sender": "irc-user@irc.zulip.com", "content": "Test message", "client": "irc_mirror", "topic": "from irc", "to": "IRCLand"}) self.assert_json_success(result) msg = self.get_last_message() self.assertEqual(int(datetime_to_timestamp(msg.pub_date)), int(fake_pub_time)) def test_unsubscribed_api_super_user(self) -> None: cordelia = self.example_user('cordelia') stream_name = 'private_stream' self.make_stream(stream_name, invite_only=True) self.unsubscribe(cordelia, stream_name) # As long as Cordelia is a super_user, she can send messages # to ANY stream, even one she is not unsubscribed to, and # she can do it for herself or on behalf of a mirrored user. def test_with(sender_email: str, client: str, forged: bool) ->None: payload = dict( type="stream", to=stream_name, sender=sender_email, client=client, topic='whatever', content='whatever', forged=ujson.dumps(forged), ) cordelia.is_api_super_user = False cordelia.save() result = self.api_post(cordelia.email, "/api/v1/messages", payload) self.assert_json_error_contains(result, 'authorized') cordelia.is_api_super_user = True cordelia.save() result = self.api_post(cordelia.email, "/api/v1/messages", payload) self.assert_json_success(result) test_with( sender_email=cordelia.email, client='test suite', forged=False, ) test_with( sender_email='irc_person@zulip.com', client='irc_mirror', forged=True, ) def test_bot_can_send_to_owner_stream(self) -> None: cordelia = self.example_user('cordelia') bot = self.create_test_bot( short_name='whatever', user_profile=cordelia, ) stream_name = 'private_stream' self.make_stream(stream_name, invite_only=True) payload = dict( type="stream", to=stream_name, sender=bot.email, client='test suite', topic='whatever', content='whatever', ) result = self.api_post(bot.email, "/api/v1/messages", payload) self.assert_json_error_contains(result, 'Not authorized to send') # We subscribe the bot owner! (aka cordelia) self.subscribe(bot.bot_owner, stream_name) result = self.api_post(bot.email, "/api/v1/messages", payload) self.assert_json_success(result) def test_notification_bot(self) -> None: sender = self.notification_bot() stream_name = 'private_stream' self.make_stream(stream_name, invite_only=True) payload = dict( type="stream", to=stream_name, sender=sender.email, client='test suite', topic='whatever', content='whatever', ) result = self.api_post(sender.email, "/api/v1/messages", payload) self.assert_json_success(result) def test_create_mirror_user_despite_race(self) -> None: realm = get_realm('zulip') email = 'fred@example.com' email_to_full_name = lambda email: 'fred' def create_user(**kwargs: Any) -> UserProfile: self.assertEqual(kwargs['full_name'], 'fred') self.assertEqual(kwargs['email'], email) self.assertEqual(kwargs['active'], False) self.assertEqual(kwargs['is_mirror_dummy'], True) # We create an actual user here to simulate a race. # We use the minimal, un-mocked function. kwargs['bot_type'] = None kwargs['bot_owner'] = None kwargs['tos_version'] = None kwargs['timezone'] = timezone_now() create_user_profile(**kwargs).save() raise IntegrityError() with mock.patch('zerver.lib.actions.create_user', side_effect=create_user) as m: mirror_fred_user = create_mirror_user_if_needed( realm, email, email_to_full_name, ) self.assertEqual(mirror_fred_user.email, email) m.assert_called() def test_guest_user(self) -> None: sender = self.example_user('polonius') stream_name = 'public stream' self.make_stream(stream_name, invite_only=False) payload = dict( type="stream", to=stream_name, sender=sender.email, client='test suite', topic='whatever', content='whatever', ) # Guest user can't send message to unsubscribed public streams result = self.api_post(sender.email, "/api/v1/messages", payload) self.assert_json_error(result, "Not authorized to send to stream 'public stream'") self.subscribe(sender, stream_name) # Guest user can send message to subscribed public streams result = self.api_post(sender.email, "/api/v1/messages", payload) self.assert_json_success(result) class ScheduledMessageTest(ZulipTestCase): def last_scheduled_message(self) -> ScheduledMessage: return ScheduledMessage.objects.all().order_by('-id')[0] def do_schedule_message(self, msg_type: str, to: str, msg: str, defer_until: str='', tz_guess: str='', delivery_type: str='send_later', realm_str: str='zulip') -> HttpResponse: self.login(self.example_email("hamlet")) topic_name = '' if msg_type == 'stream': topic_name = 'Test topic' payload = {"type": msg_type, "to": to, "client": "test suite", "content": msg, "topic": topic_name, "realm_str": realm_str, "delivery_type": delivery_type, "tz_guess": tz_guess} if defer_until: payload["deliver_at"] = defer_until result = self.client_post("/json/messages", payload) return result def test_schedule_message(self) -> None: content = "Test message" defer_until = timezone_now().replace(tzinfo=None) + datetime.timedelta(days=1) defer_until_str = str(defer_until) # Scheduling a message to a stream you are subscribed is successful. result = self.do_schedule_message('stream', 'Verona', content + ' 1', defer_until_str) message = self.last_scheduled_message() self.assert_json_success(result) self.assertEqual(message.content, 'Test message 1') self.assertEqual(message.topic_name(), 'Test topic') self.assertEqual(message.scheduled_timestamp, convert_to_UTC(defer_until)) self.assertEqual(message.delivery_type, ScheduledMessage.SEND_LATER) # Scheduling a message for reminders. result = self.do_schedule_message('stream', 'Verona', content + ' 2', defer_until_str, delivery_type='remind') message = self.last_scheduled_message() self.assert_json_success(result) self.assertEqual(message.delivery_type, ScheduledMessage.REMIND) # Scheduling a private message is successful. result = self.do_schedule_message('private', self.example_email("othello"), content + ' 3', defer_until_str) message = self.last_scheduled_message() self.assert_json_success(result) self.assertEqual(message.content, 'Test message 3') self.assertEqual(message.scheduled_timestamp, convert_to_UTC(defer_until)) self.assertEqual(message.delivery_type, ScheduledMessage.SEND_LATER) result = self.do_schedule_message('private', self.example_email("othello"), content + ' 4', defer_until_str, delivery_type='remind') message = self.last_scheduled_message() self.assert_json_success(result) self.assertEqual(message.delivery_type, ScheduledMessage.REMIND) # Scheduling a message while guessing timezone. tz_guess = 'Asia/Kolkata' result = self.do_schedule_message('stream', 'Verona', content + ' 5', defer_until_str, tz_guess=tz_guess) message = self.last_scheduled_message() self.assert_json_success(result) self.assertEqual(message.content, 'Test message 5') local_tz = get_timezone(tz_guess) # Since mypy is not able to recognize localize and normalize as attributes of tzinfo we use ignore. utz_defer_until = local_tz.normalize(local_tz.localize(defer_until)) # type: ignore # Reason in comment on previous line. self.assertEqual(message.scheduled_timestamp, convert_to_UTC(utz_defer_until)) self.assertEqual(message.delivery_type, ScheduledMessage.SEND_LATER) # Test with users timezone setting as set to some timezone rather than # empty. This will help interpret timestamp in users local timezone. user = self.example_user("hamlet") user.timezone = 'US/Pacific' user.save(update_fields=['timezone']) result = self.do_schedule_message('stream', 'Verona', content + ' 6', defer_until_str) message = self.last_scheduled_message() self.assert_json_success(result) self.assertEqual(message.content, 'Test message 6') local_tz = get_timezone(user.timezone) # Since mypy is not able to recognize localize and normalize as attributes of tzinfo we use ignore. utz_defer_until = local_tz.normalize(local_tz.localize(defer_until)) # type: ignore # Reason in comment on previous line. self.assertEqual(message.scheduled_timestamp, convert_to_UTC(utz_defer_until)) self.assertEqual(message.delivery_type, ScheduledMessage.SEND_LATER) def test_scheduling_in_past(self) -> None: # Scheduling a message in past should fail. content = "Test message" defer_until = timezone_now() defer_until_str = str(defer_until) result = self.do_schedule_message('stream', 'Verona', content + ' 1', defer_until_str) self.assert_json_error(result, 'Time must be in the future.') def test_invalid_timestamp(self) -> None: # Scheduling a message from which timestamp couldn't be parsed # successfully should fail. content = "Test message" defer_until = 'Missed the timestamp' result = self.do_schedule_message('stream', 'Verona', content + ' 1', defer_until) self.assert_json_error(result, 'Invalid time format') def test_missing_deliver_at(self) -> None: content = "Test message" result = self.do_schedule_message('stream', 'Verona', content + ' 1') self.assert_json_error(result, 'Missing deliver_at in a request for delayed message delivery') class EditMessageTest(ZulipTestCase): def check_message(self, msg_id: int, topic_name: Optional[str]=None, content: Optional[str]=None) -> Message: msg = Message.objects.get(id=msg_id) cached = MessageDict.wide_dict(msg) MessageDict.finalize_payload(cached, apply_markdown=False, client_gravatar=False) uncached = MessageDict.to_dict_uncached_helper(msg) MessageDict.post_process_dicts([uncached], apply_markdown=False, client_gravatar=False) self.assertEqual(cached, uncached) if topic_name: self.assertEqual(msg.topic_name(), topic_name) if content: self.assertEqual(msg.content, content) return msg def test_save_message(self) -> None: """This is also tested by a client test, but here we can verify the cache against the database""" self.login(self.example_email("hamlet")) msg_id = self.send_stream_message(self.example_email("hamlet"), "Scotland", topic_name="editing", content="before edit") result = self.client_patch("/json/messages/" + str(msg_id), { 'message_id': msg_id, 'content': 'after edit' }) self.assert_json_success(result) self.check_message(msg_id, content="after edit") result = self.client_patch("/json/messages/" + str(msg_id), { 'message_id': msg_id, 'topic': 'edited' }) self.assert_json_success(result) self.check_message(msg_id, topic_name="edited") def test_fetch_raw_message(self) -> None: self.login(self.example_email("hamlet")) msg_id = self.send_personal_message( from_email=self.example_email("hamlet"), to_email=self.example_email("cordelia"), content="**before** edit", ) result = self.client_get('/json/messages/' + str(msg_id)) self.assert_json_success(result) self.assertEqual(result.json()['raw_content'], '**before** edit') # Test error cases result = self.client_get('/json/messages/999999') self.assert_json_error(result, 'Invalid message(s)') self.login(self.example_email("cordelia")) result = self.client_get('/json/messages/' + str(msg_id)) self.assert_json_success(result) self.login(self.example_email("othello")) result = self.client_get('/json/messages/' + str(msg_id)) self.assert_json_error(result, 'Invalid message(s)') def test_fetch_raw_message_stream_wrong_realm(self) -> None: user_profile = self.example_user("hamlet") self.login(user_profile.email) stream = self.make_stream('public_stream') self.subscribe(user_profile, stream.name) msg_id = self.send_stream_message(user_profile.email, stream.name, topic_name="test", content="test") result = self.client_get('/json/messages/' + str(msg_id)) self.assert_json_success(result) self.login(self.mit_email("sipbtest"), realm=get_realm("zephyr")) result = self.client_get('/json/messages/' + str(msg_id), subdomain="zephyr") self.assert_json_error(result, 'Invalid message(s)') def test_fetch_raw_message_private_stream(self) -> None: user_profile = self.example_user("hamlet") self.login(user_profile.email) stream = self.make_stream('private_stream', invite_only=True) self.subscribe(user_profile, stream.name) msg_id = self.send_stream_message(user_profile.email, stream.name, topic_name="test", content="test") result = self.client_get('/json/messages/' + str(msg_id)) self.assert_json_success(result) self.login(self.example_email("othello")) result = self.client_get('/json/messages/' + str(msg_id)) self.assert_json_error(result, 'Invalid message(s)') def test_edit_message_no_permission(self) -> None: self.login(self.example_email("hamlet")) msg_id = self.send_stream_message(self.example_email("iago"), "Scotland", topic_name="editing", content="before edit") result = self.client_patch("/json/messages/" + str(msg_id), { 'message_id': msg_id, 'content': 'content after edit', }) self.assert_json_error(result, "You don't have permission to edit this message") def test_edit_message_no_changes(self) -> None: self.login(self.example_email("hamlet")) msg_id = self.send_stream_message(self.example_email("hamlet"), "Scotland", topic_name="editing", content="before edit") result = self.client_patch("/json/messages/" + str(msg_id), { 'message_id': msg_id, }) self.assert_json_error(result, "Nothing to change") def test_edit_message_no_topic(self) -> None: self.login(self.example_email("hamlet")) msg_id = self.send_stream_message(self.example_email("hamlet"), "Scotland", topic_name="editing", content="before edit") result = self.client_patch("/json/messages/" + str(msg_id), { 'message_id': msg_id, 'topic': ' ' }) self.assert_json_error(result, "Topic can't be empty") def test_edit_message_no_content(self) -> None: self.login(self.example_email("hamlet")) msg_id = self.send_stream_message(self.example_email("hamlet"), "Scotland", topic_name="editing", content="before edit") result = self.client_patch("/json/messages/" + str(msg_id), { 'message_id': msg_id, 'content': ' ' }) self.assert_json_success(result) content = Message.objects.filter(id=msg_id).values_list('content', flat = True)[0] self.assertEqual(content, "(deleted)") def test_edit_message_history_disabled(self) -> None: user_profile = self.example_user("hamlet") do_set_realm_property(user_profile.realm, "allow_edit_history", False) self.login(self.example_email("hamlet")) # Single-line edit msg_id_1 = self.send_stream_message(self.example_email("hamlet"), "Denmark", topic_name="editing", content="content before edit") new_content_1 = 'content after edit' result_1 = self.client_patch("/json/messages/" + str(msg_id_1), { 'message_id': msg_id_1, 'content': new_content_1 }) self.assert_json_success(result_1) result = self.client_get( "/json/messages/" + str(msg_id_1) + "/history") self.assert_json_error(result, "Message edit history is disabled in this organization") # Now verify that if we fetch the message directly, there's no # edit history data attached. messages_result = self.client_get("/json/messages", {"anchor": msg_id_1, "num_before": 0, "num_after": 10}) self.assert_json_success(messages_result) json_messages = ujson.loads( messages_result.content.decode('utf-8')) for msg in json_messages['messages']: self.assertNotIn("edit_history", msg) def test_edit_message_history(self) -> None: self.login(self.example_email("hamlet")) # Single-line edit msg_id_1 = self.send_stream_message( self.example_email("hamlet"), "Scotland", topic_name="editing", content="content before edit") new_content_1 = 'content after edit' result_1 = self.client_patch("/json/messages/" + str(msg_id_1), { 'message_id': msg_id_1, 'content': new_content_1 }) self.assert_json_success(result_1) message_edit_history_1 = self.client_get( "/json/messages/" + str(msg_id_1) + "/history") json_response_1 = ujson.loads( message_edit_history_1.content.decode('utf-8')) message_history_1 = json_response_1['message_history'] # Check content of message after edit. self.assertEqual(message_history_1[0]['rendered_content'], '<p>content before edit</p>') self.assertEqual(message_history_1[1]['rendered_content'], '<p>content after edit</p>') self.assertEqual(message_history_1[1]['content_html_diff'], ('<p>content ' '<span class="highlight_text_inserted">after</span> ' '<span class="highlight_text_deleted">before</span>' ' edit</p>')) # Check content of message before edit. self.assertEqual(message_history_1[1]['prev_rendered_content'], '<p>content before edit</p>') # Edits on new lines msg_id_2 = self.send_stream_message( self.example_email("hamlet"), "Scotland", topic_name="editing", content=('content before edit, line 1\n' '\n' 'content before edit, line 3')) new_content_2 = ('content before edit, line 1\n' 'content after edit, line 2\n' 'content before edit, line 3') result_2 = self.client_patch("/json/messages/" + str(msg_id_2), { 'message_id': msg_id_2, 'content': new_content_2 }) self.assert_json_success(result_2) message_edit_history_2 = self.client_get( "/json/messages/" + str(msg_id_2) + "/history") json_response_2 = ujson.loads( message_edit_history_2.content.decode('utf-8')) message_history_2 = json_response_2['message_history'] self.assertEqual(message_history_2[0]['rendered_content'], ('<p>content before edit, line 1</p>\n' '<p>content before edit, line 3</p>')) self.assertEqual(message_history_2[1]['rendered_content'], ('<p>content before edit, line 1<br>\n' 'content after edit, line 2<br>\n' 'content before edit, line 3</p>')) self.assertEqual(message_history_2[1]['content_html_diff'], ('<p>content before edit, line 1<br> ' 'content <span class="highlight_text_inserted">after edit, line 2<br> ' 'content</span> before edit, line 3</p>')) self.assertEqual(message_history_2[1]['prev_rendered_content'], ('<p>content before edit, line 1</p>\n' '<p>content before edit, line 3</p>')) def test_edit_link(self) -> None: # Link editing self.login(self.example_email("hamlet")) msg_id_1 = self.send_stream_message( self.example_email("hamlet"), "Scotland", topic_name="editing", content="Here is a link to [zulip](www.zulip.org).") new_content_1 = 'Here is a link to [zulip](www.zulipchat.com).' result_1 = self.client_patch("/json/messages/" + str(msg_id_1), { 'message_id': msg_id_1, 'content': new_content_1 }) self.assert_json_success(result_1) message_edit_history_1 = self.client_get( "/json/messages/" + str(msg_id_1) + "/history") json_response_1 = ujson.loads( message_edit_history_1.content.decode('utf-8')) message_history_1 = json_response_1['message_history'] # Check content of message after edit. self.assertEqual(message_history_1[0]['rendered_content'], '<p>Here is a link to ' '<a href="http://www.zulip.org" target="_blank" title="http://www.zulip.org">zulip</a>.</p>') self.assertEqual(message_history_1[1]['rendered_content'], '<p>Here is a link to ' '<a href="http://www.zulipchat.com" target="_blank" title="http://www.zulipchat.com">zulip</a>.</p>') self.assertEqual(message_history_1[1]['content_html_diff'], ('<p>Here is a link to <a href="http://www.zulipchat.com" ' 'target="_blank" title="http://www.zulipchat.com">zulip ' '<span class="highlight_text_inserted"> Link: http://www.zulipchat.com .' '</span> <span class="highlight_text_deleted"> Link: http://www.zulip.org .' '</span> </a></p>')) def test_edit_history_unedited(self) -> None: self.login(self.example_email('hamlet')) msg_id = self.send_stream_message( self.example_email('hamlet'), 'Scotland', topic_name='editing', content='This message has not been edited.') result = self.client_get('/json/messages/{}/history'.format(msg_id)) self.assert_json_success(result) message_history = result.json()['message_history'] self.assert_length(message_history, 1) def test_user_info_for_updates(self) -> None: hamlet = self.example_user('hamlet') cordelia = self.example_user('cordelia') self.login(hamlet.email) self.subscribe(hamlet, 'Scotland') self.subscribe(cordelia, 'Scotland') msg_id = self.send_stream_message(hamlet.email, 'Scotland', content='@**Cordelia Lear**') user_info = get_user_info_for_message_updates(msg_id) message_user_ids = user_info['message_user_ids'] self.assertIn(hamlet.id, message_user_ids) self.assertIn(cordelia.id, message_user_ids) mention_user_ids = user_info['mention_user_ids'] self.assertEqual(mention_user_ids, {cordelia.id}) def test_edit_cases(self) -> None: """This test verifies the accuracy of construction of Zulip's edit history data structures.""" self.login(self.example_email("hamlet")) hamlet = self.example_user('hamlet') msg_id = self.send_stream_message(self.example_email("hamlet"), "Scotland", topic_name="topic 1", content="content 1") result = self.client_patch("/json/messages/" + str(msg_id), { 'message_id': msg_id, 'content': 'content 2', }) self.assert_json_success(result) history = ujson.loads(Message.objects.get(id=msg_id).edit_history) self.assertEqual(history[0]['prev_content'], 'content 1') self.assertEqual(history[0]['user_id'], hamlet.id) self.assertEqual(set(history[0].keys()), {u'timestamp', u'prev_content', u'user_id', u'prev_rendered_content', u'prev_rendered_content_version'}) result = self.client_patch("/json/messages/" + str(msg_id), { 'message_id': msg_id, 'topic': 'topic 2', }) self.assert_json_success(result) history = ujson.loads(Message.objects.get(id=msg_id).edit_history) self.assertEqual(history[0][LEGACY_PREV_TOPIC], 'topic 1') self.assertEqual(history[0]['user_id'], hamlet.id) self.assertEqual(set(history[0].keys()), {'timestamp', LEGACY_PREV_TOPIC, 'user_id'}) result = self.client_patch("/json/messages/" + str(msg_id), { 'message_id': msg_id, 'content': 'content 3', 'topic': 'topic 3', }) self.assert_json_success(result) history = ujson.loads(Message.objects.get(id=msg_id).edit_history) self.assertEqual(history[0]['prev_content'], 'content 2') self.assertEqual(history[0][LEGACY_PREV_TOPIC], 'topic 2') self.assertEqual(history[0]['user_id'], hamlet.id) self.assertEqual(set(history[0].keys()), {'timestamp', LEGACY_PREV_TOPIC, 'prev_content', 'user_id', 'prev_rendered_content', 'prev_rendered_content_version'}) result = self.client_patch("/json/messages/" + str(msg_id), { 'message_id': msg_id, 'content': 'content 4', }) self.assert_json_success(result) history = ujson.loads(Message.objects.get(id=msg_id).edit_history) self.assertEqual(history[0]['prev_content'], 'content 3') self.assertEqual(history[0]['user_id'], hamlet.id) self.login(self.example_email("iago")) result = self.client_patch("/json/messages/" + str(msg_id), { 'message_id': msg_id, 'topic': 'topic 4', }) self.assert_json_success(result) history = ujson.loads(Message.objects.get(id=msg_id).edit_history) self.assertEqual(history[0][LEGACY_PREV_TOPIC], 'topic 3') self.assertEqual(history[0]['user_id'], self.example_user('iago').id) history = ujson.loads(Message.objects.get(id=msg_id).edit_history) self.assertEqual(history[0][LEGACY_PREV_TOPIC], 'topic 3') self.assertEqual(history[2][LEGACY_PREV_TOPIC], 'topic 2') self.assertEqual(history[3][LEGACY_PREV_TOPIC], 'topic 1') self.assertEqual(history[1]['prev_content'], 'content 3') self.assertEqual(history[2]['prev_content'], 'content 2') self.assertEqual(history[4]['prev_content'], 'content 1') # Now, we verify that the edit history data sent back has the # correct filled-out fields message_edit_history = self.client_get("/json/messages/" + str(msg_id) + "/history") json_response = ujson.loads(message_edit_history.content.decode('utf-8')) # We reverse the message history view output so that the IDs line up with the above. message_history = list(reversed(json_response['message_history'])) i = 0 for entry in message_history: expected_entries = {u'content', u'rendered_content', u'topic', u'timestamp', u'user_id'} if i in {0, 2, 3}: expected_entries.add('prev_topic') if i in {1, 2, 4}: expected_entries.add('prev_content') expected_entries.add('prev_rendered_content') expected_entries.add('content_html_diff') i += 1 self.assertEqual(expected_entries, set(entry.keys())) self.assertEqual(len(message_history), 6) self.assertEqual(message_history[0]['prev_topic'], 'topic 3') self.assertEqual(message_history[0]['topic'], 'topic 4') self.assertEqual(message_history[1]['topic'], 'topic 3') self.assertEqual(message_history[2]['topic'], 'topic 3') self.assertEqual(message_history[2]['prev_topic'], 'topic 2') self.assertEqual(message_history[3]['topic'], 'topic 2') self.assertEqual(message_history[3]['prev_topic'], 'topic 1') self.assertEqual(message_history[4]['topic'], 'topic 1') self.assertEqual(message_history[0]['content'], 'content 4') self.assertEqual(message_history[1]['content'], 'content 4') self.assertEqual(message_history[1]['prev_content'], 'content 3') self.assertEqual(message_history[2]['content'], 'content 3') self.assertEqual(message_history[2]['prev_content'], 'content 2') self.assertEqual(message_history[3]['content'], 'content 2') self.assertEqual(message_history[4]['content'], 'content 2') self.assertEqual(message_history[4]['prev_content'], 'content 1') self.assertEqual(message_history[5]['content'], 'content 1') self.assertEqual(message_history[5]['topic'], 'topic 1') def test_edit_message_content_limit(self) -> None: def set_message_editing_params(allow_message_editing: bool, message_content_edit_limit_seconds: int, allow_community_topic_editing: bool) -> None: result = self.client_patch("/json/realm", { 'allow_message_editing': ujson.dumps(allow_message_editing), 'message_content_edit_limit_seconds': message_content_edit_limit_seconds, 'allow_community_topic_editing': ujson.dumps(allow_community_topic_editing), }) self.assert_json_success(result) def do_edit_message_assert_success(id_: int, unique_str: str, topic_only: bool=False) -> None: new_topic = 'topic' + unique_str new_content = 'content' + unique_str params_dict = {'message_id': id_, 'topic': new_topic} if not topic_only: params_dict['content'] = new_content result = self.client_patch("/json/messages/" + str(id_), params_dict) self.assert_json_success(result) if topic_only: self.check_message(id_, topic_name=new_topic) else: self.check_message(id_, topic_name=new_topic, content=new_content) def do_edit_message_assert_error(id_: int, unique_str: str, error: str, topic_only: bool=False) -> None: message = Message.objects.get(id=id_) old_topic = message.topic_name() old_content = message.content new_topic = 'topic' + unique_str new_content = 'content' + unique_str params_dict = {'message_id': id_, 'topic': new_topic} if not topic_only: params_dict['content'] = new_content result = self.client_patch("/json/messages/" + str(id_), params_dict) message = Message.objects.get(id=id_) self.assert_json_error(result, error) self.check_message(id_, topic_name=old_topic, content=old_content) self.login(self.example_email("iago")) # send a message in the past id_ = self.send_stream_message(self.example_email("iago"), "Scotland", content="content", topic_name="topic") message = Message.objects.get(id=id_) message.pub_date = message.pub_date - datetime.timedelta(seconds=180) message.save() # test the various possible message editing settings # high enough time limit, all edits allowed set_message_editing_params(True, 240, False) do_edit_message_assert_success(id_, 'A') # out of time, only topic editing allowed set_message_editing_params(True, 120, False) do_edit_message_assert_success(id_, 'B', True) do_edit_message_assert_error(id_, 'C', "The time limit for editing this message has passed") # infinite time, all edits allowed set_message_editing_params(True, 0, False) do_edit_message_assert_success(id_, 'D') # without allow_message_editing, nothing is allowed set_message_editing_params(False, 240, False) do_edit_message_assert_error(id_, 'E', "Your organization has turned off message editing", True) set_message_editing_params(False, 120, False) do_edit_message_assert_error(id_, 'F', "Your organization has turned off message editing", True) set_message_editing_params(False, 0, False) do_edit_message_assert_error(id_, 'G', "Your organization has turned off message editing", True) def test_allow_community_topic_editing(self) -> None: def set_message_editing_params(allow_message_editing, message_content_edit_limit_seconds, allow_community_topic_editing): # type: (bool, int, bool) -> None result = self.client_patch("/json/realm", { 'allow_message_editing': ujson.dumps(allow_message_editing), 'message_content_edit_limit_seconds': message_content_edit_limit_seconds, 'allow_community_topic_editing': ujson.dumps(allow_community_topic_editing), }) self.assert_json_success(result) def do_edit_message_assert_success(id_, unique_str): # type: (int, str) -> None new_topic = 'topic' + unique_str params_dict = {'message_id': id_, 'topic': new_topic} result = self.client_patch("/json/messages/" + str(id_), params_dict) self.assert_json_success(result) self.check_message(id_, topic_name=new_topic) def do_edit_message_assert_error(id_, unique_str, error): # type: (int, str, str) -> None message = Message.objects.get(id=id_) old_topic = message.topic_name() old_content = message.content new_topic = 'topic' + unique_str params_dict = {'message_id': id_, 'topic': new_topic} result = self.client_patch("/json/messages/" + str(id_), params_dict) message = Message.objects.get(id=id_) self.assert_json_error(result, error) self.check_message(id_, topic_name=old_topic, content=old_content) self.login(self.example_email("iago")) # send a message in the past id_ = self.send_stream_message(self.example_email("hamlet"), "Scotland", content="content", topic_name="topic") message = Message.objects.get(id=id_) message.pub_date = message.pub_date - datetime.timedelta(seconds=180) message.save() # any user can edit the topic of a message set_message_editing_params(True, 0, True) # log in as a new user self.login(self.example_email("cordelia")) do_edit_message_assert_success(id_, 'A') # only admins can edit the topics of messages self.login(self.example_email("iago")) set_message_editing_params(True, 0, False) do_edit_message_assert_success(id_, 'B') self.login(self.example_email("cordelia")) do_edit_message_assert_error(id_, 'C', "You don't have permission to edit this message") # users cannot edit topics if allow_message_editing is False self.login(self.example_email("iago")) set_message_editing_params(False, 0, True) self.login(self.example_email("cordelia")) do_edit_message_assert_error(id_, 'D', "Your organization has turned off message editing") # non-admin users cannot edit topics sent > 24 hrs ago message.pub_date = message.pub_date - datetime.timedelta(seconds=90000) message.save() self.login(self.example_email("iago")) set_message_editing_params(True, 0, True) do_edit_message_assert_success(id_, 'E') self.login(self.example_email("cordelia")) do_edit_message_assert_error(id_, 'F', "The time limit for editing this message has passed") # anyone should be able to edit "no topic" indefinitely message.set_topic_name("(no topic)") message.save() self.login(self.example_email("cordelia")) do_edit_message_assert_success(id_, 'D') def test_propagate_topic_forward(self) -> None: self.login(self.example_email("hamlet")) id1 = self.send_stream_message(self.example_email("hamlet"), "Scotland", topic_name="topic1") id2 = self.send_stream_message(self.example_email("iago"), "Scotland", topic_name="topic1") id3 = self.send_stream_message(self.example_email("iago"), "Rome", topic_name="topic1") id4 = self.send_stream_message(self.example_email("hamlet"), "Scotland", topic_name="topic2") id5 = self.send_stream_message(self.example_email("iago"), "Scotland", topic_name="topic1") result = self.client_patch("/json/messages/" + str(id1), { 'message_id': id1, 'topic': 'edited', 'propagate_mode': 'change_later' }) self.assert_json_success(result) self.check_message(id1, topic_name="edited") self.check_message(id2, topic_name="edited") self.check_message(id3, topic_name="topic1") self.check_message(id4, topic_name="topic2") self.check_message(id5, topic_name="edited") def test_propagate_all_topics(self) -> None: self.login(self.example_email("hamlet")) id1 = self.send_stream_message(self.example_email("hamlet"), "Scotland", topic_name="topic1") id2 = self.send_stream_message(self.example_email("hamlet"), "Scotland", topic_name="topic1") id3 = self.send_stream_message(self.example_email("iago"), "Rome", topic_name="topic1") id4 = self.send_stream_message(self.example_email("hamlet"), "Scotland", topic_name="topic2") id5 = self.send_stream_message(self.example_email("iago"), "Scotland", topic_name="topic1") id6 = self.send_stream_message(self.example_email("iago"), "Scotland", topic_name="topic3") result = self.client_patch("/json/messages/" + str(id2), { 'message_id': id2, 'topic': 'edited', 'propagate_mode': 'change_all' }) self.assert_json_success(result) self.check_message(id1, topic_name="edited") self.check_message(id2, topic_name="edited") self.check_message(id3, topic_name="topic1") self.check_message(id4, topic_name="topic2") self.check_message(id5, topic_name="edited") self.check_message(id6, topic_name="topic3") class MirroredMessageUsersTest(ZulipTestCase): def test_invalid_sender(self) -> None: user = self.example_user('hamlet') recipients = [] # type: List[str] Request = namedtuple('Request', ['POST']) request = Request(POST=dict()) # no sender (valid_input, mirror_sender) = \ create_mirrored_message_users(request, user, recipients) self.assertEqual(valid_input, False) self.assertEqual(mirror_sender, None) def test_invalid_client(self) -> None: client = get_client(name='banned_mirror') # Invalid!!! user = self.example_user('hamlet') sender = user recipients = [] # type: List[str] Request = namedtuple('Request', ['POST', 'client']) request = Request(POST = dict(sender=sender.email, type='private'), client = client) (valid_input, mirror_sender) = \ create_mirrored_message_users(request, user, recipients) self.assertEqual(valid_input, False) self.assertEqual(mirror_sender, None) def test_invalid_email(self) -> None: invalid_email = 'alice AT example.com' recipients = [invalid_email] # We use an MIT user here to maximize code coverage user = self.mit_user('starnine') sender = user Request = namedtuple('Request', ['POST', 'client']) for client_name in ['zephyr_mirror', 'irc_mirror', 'jabber_mirror']: client = get_client(name=client_name) request = Request(POST = dict(sender=sender.email, type='private'), client = client) (valid_input, mirror_sender) = \ create_mirrored_message_users(request, user, recipients) self.assertEqual(valid_input, False) self.assertEqual(mirror_sender, None) @mock.patch('DNS.dnslookup', return_value=[['sipbtest:*:20922:101:Fred Sipb,,,:/mit/sipbtest:/bin/athena/tcsh']]) def test_zephyr_mirror_new_recipient(self, ignored: Any) -> None: """Test mirror dummy user creation for PM recipients""" client = get_client(name='zephyr_mirror') user = self.mit_user('starnine') sender = self.mit_user('sipbtest') new_user_email = 'bob_the_new_user@mit.edu' new_user_realm = get_realm("zephyr") recipients = [user.email, new_user_email] # Now make the request. Request = namedtuple('Request', ['POST', 'client']) request = Request(POST = dict(sender=sender.email, type='private'), client = client) (valid_input, mirror_sender) = \ create_mirrored_message_users(request, user, recipients) self.assertTrue(valid_input) self.assertEqual(mirror_sender, sender) realm_users = UserProfile.objects.filter(realm=sender.realm) realm_emails = {user.email for user in realm_users} self.assertIn(user.email, realm_emails) self.assertIn(new_user_email, realm_emails) bob = get_user(new_user_email, new_user_realm) self.assertTrue(bob.is_mirror_dummy) @mock.patch('DNS.dnslookup', return_value=[['sipbtest:*:20922:101:Fred Sipb,,,:/mit/sipbtest:/bin/athena/tcsh']]) def test_zephyr_mirror_new_sender(self, ignored: Any) -> None: """Test mirror dummy user creation for sender when sending to stream""" client = get_client(name='zephyr_mirror') user = self.mit_user('starnine') sender_email = 'new_sender@mit.edu' recipients = ['stream_name'] # Now make the request. Request = namedtuple('Request', ['POST', 'client']) request = Request(POST = dict(sender=sender_email, type='stream'), client = client) (valid_input, mirror_sender) = \ create_mirrored_message_users(request, user, recipients) assert(mirror_sender is not None) self.assertTrue(valid_input) self.assertEqual(mirror_sender.email, sender_email) self.assertTrue(mirror_sender.is_mirror_dummy) def test_irc_mirror(self) -> None: client = get_client(name='irc_mirror') sender = self.example_user('hamlet') user = sender recipients = [self.nonreg_email('alice'), 'bob@irc.zulip.com', self.nonreg_email('cordelia')] # Now make the request. Request = namedtuple('Request', ['POST', 'client']) request = Request(POST = dict(sender=sender.email, type='private'), client = client) (valid_input, mirror_sender) = \ create_mirrored_message_users(request, user, recipients) self.assertEqual(valid_input, True) self.assertEqual(mirror_sender, sender) realm_users = UserProfile.objects.filter(realm=sender.realm) realm_emails = {user.email for user in realm_users} self.assertIn(self.nonreg_email('alice'), realm_emails) self.assertIn('bob@irc.zulip.com', realm_emails) bob = get_user('bob@irc.zulip.com', sender.realm) self.assertTrue(bob.is_mirror_dummy) def test_jabber_mirror(self) -> None: client = get_client(name='jabber_mirror') sender = self.example_user('hamlet') user = sender recipients = [self.nonreg_email('alice'), self.nonreg_email('bob'), self.nonreg_email('cordelia')] # Now make the request. Request = namedtuple('Request', ['POST', 'client']) request = Request(POST = dict(sender=sender.email, type='private'), client = client) (valid_input, mirror_sender) = \ create_mirrored_message_users(request, user, recipients) self.assertEqual(valid_input, True) self.assertEqual(mirror_sender, sender) realm_users = UserProfile.objects.filter(realm=sender.realm) realm_emails = {user.email for user in realm_users} self.assertIn(self.nonreg_email('alice'), realm_emails) self.assertIn(self.nonreg_email('bob'), realm_emails) bob = get_user(self.nonreg_email('bob'), sender.realm) self.assertTrue(bob.is_mirror_dummy) class MessageAccessTests(ZulipTestCase): def test_update_invalid_flags(self) -> None: message = self.send_personal_message( self.example_email("cordelia"), self.example_email("hamlet"), "hello", ) self.login(self.example_email("hamlet")) result = self.client_post("/json/messages/flags", {"messages": ujson.dumps([message]), "op": "add", "flag": "invalid"}) self.assert_json_error(result, "Invalid flag: 'invalid'") result = self.client_post("/json/messages/flags", {"messages": ujson.dumps([message]), "op": "add", "flag": "is_private"}) self.assert_json_error(result, "Invalid flag: 'is_private'") result = self.client_post("/json/messages/flags", {"messages": ujson.dumps([message]), "op": "add", "flag": "active_mobile_push_notification"}) self.assert_json_error(result, "Invalid flag: 'active_mobile_push_notification'") def change_star(self, messages: List[int], add: bool=True, **kwargs: Any) -> HttpResponse: return self.client_post("/json/messages/flags", {"messages": ujson.dumps(messages), "op": "add" if add else "remove", "flag": "starred"}, **kwargs) def test_change_star(self) -> None: """ You can set a message as starred/un-starred through POST /json/messages/flags. """ self.login(self.example_email("hamlet")) message_ids = [self.send_personal_message(self.example_email("hamlet"), self.example_email("hamlet"), "test")] # Star a message. result = self.change_star(message_ids) self.assert_json_success(result) for msg in self.get_messages(): if msg['id'] in message_ids: self.assertEqual(msg['flags'], ['starred']) else: self.assertEqual(msg['flags'], ['read']) result = self.change_star(message_ids, False) self.assert_json_success(result) # Remove the stars. for msg in self.get_messages(): if msg['id'] in message_ids: self.assertEqual(msg['flags'], []) def test_change_star_public_stream_historical(self) -> None: """ You can set a message as starred/un-starred through POST /json/messages/flags. """ stream_name = "new_stream" self.subscribe(self.example_user("hamlet"), stream_name) self.login(self.example_email("hamlet")) message_ids = [ self.send_stream_message(self.example_email("hamlet"), stream_name, "test"), ] # Send a second message so we can verify it isn't modified other_message_ids = [ self.send_stream_message(self.example_email("hamlet"), stream_name, "test_unused"), ] received_message_ids = [ self.send_personal_message( self.example_email("hamlet"), self.example_email("cordelia"), "test_received" ), ] # Now login as another user who wasn't on that stream self.login(self.example_email("cordelia")) # Send a message to yourself to make sure we have at least one with the read flag sent_message_ids = [ self.send_personal_message( self.example_email("cordelia"), self.example_email("cordelia"), "test_read_message", ), ] result = self.client_post("/json/messages/flags", {"messages": ujson.dumps(sent_message_ids), "op": "add", "flag": "read"}) # We can't change flags other than "starred" on historical messages: result = self.client_post("/json/messages/flags", {"messages": ujson.dumps(message_ids), "op": "add", "flag": "read"}) self.assert_json_error(result, 'Invalid message(s)') # Trying to change a list of more than one historical message fails result = self.change_star(message_ids * 2) self.assert_json_error(result, 'Invalid message(s)') # Confirm that one can change the historical flag now result = self.change_star(message_ids) self.assert_json_success(result) for msg in self.get_messages(): if msg['id'] in message_ids: self.assertEqual(set(msg['flags']), {'starred', 'historical', 'read'}) elif msg['id'] in received_message_ids: self.assertEqual(msg['flags'], []) else: self.assertEqual(msg['flags'], ['read']) self.assertNotIn(msg['id'], other_message_ids) result = self.change_star(message_ids, False) self.assert_json_success(result) # But it still doesn't work if you're in another realm self.login(self.mit_email("sipbtest"), realm=get_realm("zephyr")) result = self.change_star(message_ids, subdomain="zephyr") self.assert_json_error(result, 'Invalid message(s)') def test_change_star_private_message_security(self) -> None: """ You can set a message as starred/un-starred through POST /json/messages/flags. """ self.login(self.example_email("hamlet")) message_ids = [ self.send_personal_message( self.example_email("hamlet"), self.example_email("hamlet"), "test", ), ] # Starring private messages you didn't receive fails. self.login(self.example_email("cordelia")) result = self.change_star(message_ids) self.assert_json_error(result, 'Invalid message(s)') def test_change_star_private_stream_security(self) -> None: stream_name = "private_stream" self.make_stream(stream_name, invite_only=True) self.subscribe(self.example_user("hamlet"), stream_name) self.login(self.example_email("hamlet")) message_ids = [ self.send_stream_message(self.example_email("hamlet"), stream_name, "test"), ] # Starring private stream messages you received works result = self.change_star(message_ids) self.assert_json_success(result) # Starring private stream messages you didn't receive fails. self.login(self.example_email("cordelia")) result = self.change_star(message_ids) self.assert_json_error(result, 'Invalid message(s)') stream_name = "private_stream_2" self.make_stream(stream_name, invite_only=True, history_public_to_subscribers=True) self.subscribe(self.example_user("hamlet"), stream_name) self.login(self.example_email("hamlet")) message_ids = [ self.send_stream_message(self.example_email("hamlet"), stream_name, "test"), ] # With stream.history_public_to_subscribers = True, you still # can't see it if you didn't receive the message and are # not subscribed. self.login(self.example_email("cordelia")) result = self.change_star(message_ids) self.assert_json_error(result, 'Invalid message(s)') # But if you subscribe, then you can star the message self.subscribe(self.example_user("cordelia"), stream_name) result = self.change_star(message_ids) self.assert_json_success(result) def test_new_message(self) -> None: """ New messages aren't starred. """ test_email = self.example_email('hamlet') self.login(test_email) content = "Test message for star" self.send_stream_message(test_email, "Verona", content=content) sent_message = UserMessage.objects.filter( user_profile=self.example_user('hamlet') ).order_by("id").reverse()[0] self.assertEqual(sent_message.message.content, content) self.assertFalse(sent_message.flags.starred) def test_change_star_public_stream_security_for_guest_user(self) -> None: # Guest user can't access(star) unsubscribed public stream messages normal_user = self.example_user("hamlet") stream_name = "public_stream" self.make_stream(stream_name) self.subscribe(normal_user, stream_name) self.login(normal_user.email) message_id = [ self.send_stream_message(normal_user.email, stream_name, "test 1") ] guest_user = self.example_user('polonius') self.login(guest_user.email) result = self.change_star(message_id) self.assert_json_error(result, 'Invalid message(s)') # Subscribed guest users can access public stream messages sent before they join self.subscribe(guest_user, stream_name) result = self.change_star(message_id) self.assert_json_success(result) # And messages sent after they join self.login(normal_user.email) message_id = [ self.send_stream_message(normal_user.email, stream_name, "test 2") ] self.login(guest_user.email) result = self.change_star(message_id) self.assert_json_success(result) def test_change_star_private_stream_security_for_guest_user(self) -> None: # Guest users can't access(star) unsubscribed private stream messages normal_user = self.example_user("hamlet") stream_name = "private_stream" stream = self.make_stream(stream_name, invite_only=True) self.subscribe(normal_user, stream_name) self.login(normal_user.email) message_id = [ self.send_stream_message(normal_user.email, stream_name, "test 1") ] guest_user = self.example_user('polonius') self.login(guest_user.email) result = self.change_star(message_id) self.assert_json_error(result, 'Invalid message(s)') # Guest user can't access messages of subscribed private streams if # history is not public to subscribers self.subscribe(guest_user, stream_name) result = self.change_star(message_id) self.assert_json_error(result, 'Invalid message(s)') # Guest user can access messages of subscribed private streams if # history is public to subscribers do_change_stream_invite_only(stream, True, history_public_to_subscribers=True) result = self.change_star(message_id) self.assert_json_success(result) # With history not public to subscribers, they can still see new messages do_change_stream_invite_only(stream, True, history_public_to_subscribers=False) self.login(normal_user.email) message_id = [ self.send_stream_message(normal_user.email, stream_name, "test 2") ] self.login(guest_user.email) result = self.change_star(message_id) self.assert_json_success(result) def test_bulk_access_messages_private_stream(self) -> None: user = self.example_user("hamlet") self.login(user.email) stream_name = "private_stream" stream = self.make_stream(stream_name, invite_only=True, history_public_to_subscribers=False) self.subscribe(user, stream_name) # Send a message before subscribing a new user to stream message_one_id = self.send_stream_message(user.email, stream_name, "Message one") later_subscribed_user = self.example_user("cordelia") # Subscribe a user to private-protected history stream self.subscribe(later_subscribed_user, stream_name) # Send a message after subscribing a new user to stream message_two_id = self.send_stream_message(user.email, stream_name, "Message two") message_ids = [message_one_id, message_two_id] messages = [Message.objects.select_related().get(id=message_id) for message_id in message_ids] filtered_messages = bulk_access_messages(later_subscribed_user, messages) # Message sent before subscribing wouldn't be accessible by later # subscribed user as stream has protected history self.assertEqual(len(filtered_messages), 1) self.assertEqual(filtered_messages[0].id, message_two_id) do_change_stream_invite_only(stream, True, history_public_to_subscribers=True) filtered_messages = bulk_access_messages(later_subscribed_user, messages) # Message sent before subscribing are accessible by 8user as stream # don't have protected history self.assertEqual(len(filtered_messages), 2) # Testing messages accessiblity for an unsubscribed user unsubscribed_user = self.example_user("ZOE") filtered_messages = bulk_access_messages(unsubscribed_user, messages) self.assertEqual(len(filtered_messages), 0) def test_bulk_access_messages_public_stream(self) -> None: user = self.example_user("hamlet") self.login(user.email) # Testing messages accessiblity including a public stream message stream_name = "public_stream" self.subscribe(user, stream_name) message_one_id = self.send_stream_message(user.email, stream_name, "Message one") later_subscribed_user = self.example_user("cordelia") self.subscribe(later_subscribed_user, stream_name) # Send a message after subscribing a new user to stream message_two_id = self.send_stream_message(user.email, stream_name, "Message two") message_ids = [message_one_id, message_two_id] messages = [Message.objects.select_related().get(id=message_id) for message_id in message_ids] # All public stream messages are always accessible filtered_messages = bulk_access_messages(later_subscribed_user, messages) self.assertEqual(len(filtered_messages), 2) unsubscribed_user = self.example_user("ZOE") filtered_messages = bulk_access_messages(unsubscribed_user, messages) self.assertEqual(len(filtered_messages), 2) class AttachmentTest(ZulipTestCase): def test_basics(self) -> None: self.assertFalse(Message.content_has_attachment('whatever')) self.assertFalse(Message.content_has_attachment('yo http://foo.com')) self.assertTrue(Message.content_has_attachment('yo\n https://staging.zulip.com/user_uploads/')) self.assertTrue(Message.content_has_attachment('yo\n /user_uploads/1/wEAnI-PEmVmCjo15xxNaQbnj/photo-10.jpg foo')) self.assertFalse(Message.content_has_image('whatever')) self.assertFalse(Message.content_has_image('yo http://foo.com')) self.assertFalse(Message.content_has_image('yo\n /user_uploads/1/wEAnI-PEmVmCjo15xxNaQbnj/photo-10.pdf foo')) for ext in [".bmp", ".gif", ".jpg", "jpeg", ".png", ".webp", ".JPG"]: content = 'yo\n /user_uploads/1/wEAnI-PEmVmCjo15xxNaQbnj/photo-10.%s foo' % (ext,) self.assertTrue(Message.content_has_image(content)) self.assertFalse(Message.content_has_link('whatever')) self.assertTrue(Message.content_has_link('yo\n http://foo.com')) self.assertTrue(Message.content_has_link('yo\n https://example.com?spam=1&eggs=2')) self.assertTrue(Message.content_has_link('yo /user_uploads/1/wEAnI-PEmVmCjo15xxNaQbnj/photo-10.pdf foo')) def test_claim_attachment(self) -> None: # Create dummy DB entry user_profile = self.example_user('hamlet') sample_size = 10 dummy_files = [ ('zulip.txt', '1/31/4CBjtTLYZhk66pZrF8hnYGwc/zulip.txt', sample_size), ('temp_file.py', '1/31/4CBjtTLYZhk66pZrF8hnYGwc/temp_file.py', sample_size), ('abc.py', '1/31/4CBjtTLYZhk66pZrF8hnYGwc/abc.py', sample_size) ] for file_name, path_id, size in dummy_files: create_attachment(file_name, path_id, user_profile, size) # Send message referring the attachment self.subscribe(user_profile, "Denmark") body = "Some files here ...[zulip.txt](http://localhost:9991/user_uploads/1/31/4CBjtTLYZhk66pZrF8hnYGwc/zulip.txt)" + \ "http://localhost:9991/user_uploads/1/31/4CBjtTLYZhk66pZrF8hnYGwc/temp_file.py.... Some more...." + \ "http://localhost:9991/user_uploads/1/31/4CBjtTLYZhk66pZrF8hnYGwc/abc.py" self.send_stream_message(user_profile.email, "Denmark", body, "test") for file_name, path_id, size in dummy_files: attachment = Attachment.objects.get(path_id=path_id) self.assertTrue(attachment.is_claimed()) class MissedMessageTest(ZulipTestCase): def test_presence_idle_user_ids(self) -> None: UserPresence.objects.all().delete() sender = self.example_user('cordelia') realm = sender.realm hamlet = self.example_user('hamlet') othello = self.example_user('othello') recipient_ids = {hamlet.id, othello.id} message_type = 'stream' user_flags = {} # type: Dict[int, List[str]] def assert_missing(user_ids: List[int]) -> None: presence_idle_user_ids = get_active_presence_idle_user_ids( realm=realm, sender_id=sender.id, message_type=message_type, active_user_ids=recipient_ids, user_flags=user_flags, ) self.assertEqual(sorted(user_ids), sorted(presence_idle_user_ids)) def set_presence(user_id: int, client_name: str, ago: int) -> None: when = timezone_now() - datetime.timedelta(seconds=ago) UserPresence.objects.create( user_profile_id=user_id, client=get_client(client_name), timestamp=when, ) message_type = 'private' assert_missing([hamlet.id, othello.id]) message_type = 'stream' user_flags[hamlet.id] = ['mentioned'] assert_missing([hamlet.id]) set_presence(hamlet.id, 'iPhone', ago=5000) assert_missing([hamlet.id]) set_presence(hamlet.id, 'webapp', ago=15) assert_missing([]) message_type = 'private' assert_missing([othello.id]) class LogDictTest(ZulipTestCase): def test_to_log_dict(self) -> None: email = self.example_email('hamlet') stream_name = 'Denmark' topic_name = 'Copenhagen' content = 'find me some good coffee shops' # self.login(self.example_email("hamlet")) message_id = self.send_stream_message(email, stream_name, topic_name=topic_name, content=content) message = Message.objects.get(id=message_id) dct = message.to_log_dict() self.assertTrue('timestamp' in dct) self.assertEqual(dct['content'], 'find me some good coffee shops') self.assertEqual(dct['id'], message.id) self.assertEqual(dct['recipient'], 'Denmark') self.assertEqual(dct['sender_realm_str'], 'zulip') self.assertEqual(dct['sender_email'], self.example_email("hamlet")) self.assertEqual(dct['sender_full_name'], 'King Hamlet') self.assertEqual(dct['sender_id'], self.example_user('hamlet').id) self.assertEqual(dct['sender_short_name'], 'hamlet') self.assertEqual(dct['sending_client'], 'test suite') self.assertEqual(dct[DB_TOPIC_NAME], 'Copenhagen') self.assertEqual(dct['type'], 'stream') class CheckMessageTest(ZulipTestCase): def test_basic_check_message_call(self) -> None: sender = self.example_user('othello') client = make_client(name="test suite") stream_name = u'España y Francia' self.make_stream(stream_name) topic_name = 'issue' message_content = 'whatever' addressee = Addressee.for_stream(stream_name, topic_name) ret = check_message(sender, client, addressee, message_content) self.assertEqual(ret['message'].sender.email, self.example_email("othello")) def test_bot_pm_feature(self) -> None: """We send a PM to a bot's owner if their bot sends a message to an unsubscribed stream""" parent = self.example_user('othello') bot = do_create_user( email='othello-bot@zulip.com', password='', realm=parent.realm, full_name='', short_name='', bot_type=UserProfile.DEFAULT_BOT, bot_owner=parent ) bot.last_reminder = None sender = bot client = make_client(name="test suite") stream_name = u'Россия' topic_name = 'issue' addressee = Addressee.for_stream(stream_name, topic_name) message_content = 'whatever' old_count = message_stream_count(parent) # Try sending to stream that doesn't exist sends a reminder to # the sender with self.assertRaises(JsonableError): check_message(sender, client, addressee, message_content) new_count = message_stream_count(parent) self.assertEqual(new_count, old_count + 1) self.assertIn("that stream does not yet exist.", most_recent_message(parent).content) # Try sending to stream that exists with no subscribers soon # after; due to rate-limiting, this should send nothing. self.make_stream(stream_name) ret = check_message(sender, client, addressee, message_content) new_count = message_stream_count(parent) self.assertEqual(new_count, old_count + 1) # Try sending to stream that exists with no subscribers longer # after; this should send an error to the bot owner that the # stream doesn't exist assert(sender.last_reminder is not None) sender.last_reminder = sender.last_reminder - datetime.timedelta(hours=1) sender.save(update_fields=["last_reminder"]) ret = check_message(sender, client, addressee, message_content) new_count = message_stream_count(parent) self.assertEqual(new_count, old_count + 2) self.assertEqual(ret['message'].sender.email, 'othello-bot@zulip.com') self.assertIn("there are no subscribers to that stream", most_recent_message(parent).content) def test_bot_pm_error_handling(self) -> None: # This just test some defensive code. cordelia = self.example_user('cordelia') test_bot = self.create_test_bot( short_name='test', user_profile=cordelia, ) content = 'whatever' good_realm = test_bot.realm wrong_realm = get_realm('mit') wrong_sender = cordelia send_rate_limited_pm_notification_to_bot_owner(test_bot, wrong_realm, content) self.assertEqual(test_bot.last_reminder, None) send_rate_limited_pm_notification_to_bot_owner(wrong_sender, good_realm, content) self.assertEqual(test_bot.last_reminder, None) test_bot.realm.deactivated = True send_rate_limited_pm_notification_to_bot_owner(test_bot, good_realm, content) self.assertEqual(test_bot.last_reminder, None) class DeleteMessageTest(ZulipTestCase): def test_delete_message_by_user(self) -> None: def set_message_deleting_params(allow_message_deleting: bool, message_content_delete_limit_seconds: int) -> None: self.login("iago@zulip.com") result = self.client_patch("/json/realm", { 'allow_message_deleting': ujson.dumps(allow_message_deleting), 'message_content_delete_limit_seconds': message_content_delete_limit_seconds }) self.assert_json_success(result) def test_delete_message_by_admin(msg_id: int) -> HttpResponse: self.login("iago@zulip.com") result = self.client_delete('/json/messages/{msg_id}'.format(msg_id=msg_id)) return result def test_delete_message_by_owner(msg_id: int) -> HttpResponse: self.login("hamlet@zulip.com") result = self.client_delete('/json/messages/{msg_id}'.format(msg_id=msg_id)) return result def test_delete_message_by_other_user(msg_id: int) -> HttpResponse: self.login("cordelia@zulip.com") result = self.client_delete('/json/messages/{msg_id}'.format(msg_id=msg_id)) return result # Test if message deleting is not allowed(default). set_message_deleting_params(False, 0) self.login("hamlet@zulip.com") msg_id = self.send_stream_message("hamlet@zulip.com", "Scotland") result = test_delete_message_by_owner(msg_id=msg_id) self.assert_json_error(result, "You don't have permission to delete this message") result = test_delete_message_by_other_user(msg_id=msg_id) self.assert_json_error(result, "You don't have permission to delete this message") result = test_delete_message_by_admin(msg_id=msg_id) self.assert_json_success(result) # Test if message deleting is allowed. # Test if time limit is zero(no limit). set_message_deleting_params(True, 0) msg_id = self.send_stream_message("hamlet@zulip.com", "Scotland") message = Message.objects.get(id=msg_id) message.pub_date = message.pub_date - datetime.timedelta(seconds=600) message.save() result = test_delete_message_by_other_user(msg_id=msg_id) self.assert_json_error(result, "You don't have permission to delete this message") result = test_delete_message_by_owner(msg_id=msg_id) self.assert_json_success(result) # Test if time limit is non-zero. set_message_deleting_params(True, 240) msg_id_1 = self.send_stream_message("hamlet@zulip.com", "Scotland") message = Message.objects.get(id=msg_id_1) message.pub_date = message.pub_date - datetime.timedelta(seconds=120) message.save() msg_id_2 = self.send_stream_message("hamlet@zulip.com", "Scotland") message = Message.objects.get(id=msg_id_2) message.pub_date = message.pub_date - datetime.timedelta(seconds=360) message.save() result = test_delete_message_by_other_user(msg_id=msg_id_1) self.assert_json_error(result, "You don't have permission to delete this message") result = test_delete_message_by_owner(msg_id=msg_id_1) self.assert_json_success(result) result = test_delete_message_by_owner(msg_id=msg_id_2) self.assert_json_error(result, "The time limit for deleting this message has passed") # No limit for admin. result = test_delete_message_by_admin(msg_id=msg_id_2) self.assert_json_success(result) class SoftDeactivationMessageTest(ZulipTestCase): def test_maybe_catch_up_soft_deactivated_user(self) -> None: recipient_list = [self.example_user("hamlet"), self.example_user("iago")] for user_profile in recipient_list: self.subscribe(user_profile, "Denmark") sender = self.example_email('iago') stream_name = 'Denmark' topic_name = 'foo' def last_realm_audit_log_entry(event_type: str) -> RealmAuditLog: return RealmAuditLog.objects.filter( event_type=event_type ).order_by('-event_time')[0] long_term_idle_user = self.example_user('hamlet') # We are sending this message to ensure that long_term_idle_user has # at least one UserMessage row. self.send_stream_message(long_term_idle_user.email, stream_name) do_soft_deactivate_users([long_term_idle_user]) message = 'Test Message 1' self.send_stream_message(sender, stream_name, message, topic_name) idle_user_msg_list = get_user_messages(long_term_idle_user) idle_user_msg_count = len(idle_user_msg_list) self.assertNotEqual(idle_user_msg_list[-1].content, message) with queries_captured() as queries: maybe_catch_up_soft_deactivated_user(long_term_idle_user) self.assert_length(queries, 7) self.assertFalse(long_term_idle_user.long_term_idle) self.assertEqual(last_realm_audit_log_entry( RealmAuditLog.USER_SOFT_ACTIVATED).modified_user, long_term_idle_user) idle_user_msg_list = get_user_messages(long_term_idle_user) self.assertEqual(len(idle_user_msg_list), idle_user_msg_count + 1) self.assertEqual(idle_user_msg_list[-1].content, message) def test_add_missing_messages(self) -> None: recipient_list = [self.example_user("hamlet"), self.example_user("iago")] for user_profile in recipient_list: self.subscribe(user_profile, "Denmark") sender = self.example_user('iago') realm = sender.realm sending_client = make_client(name="test suite") stream_name = 'Denmark' stream = get_stream(stream_name, realm) topic_name = 'foo' def send_fake_message(message_content: str, stream: Stream) -> Message: recipient = get_stream_recipient(stream.id) message = Message(sender = sender, recipient = recipient, content = message_content, pub_date = timezone_now(), sending_client = sending_client) message.set_topic_name(topic_name) message.save() return message long_term_idle_user = self.example_user('hamlet') self.send_stream_message(long_term_idle_user.email, stream_name) do_soft_deactivate_users([long_term_idle_user]) # Test that add_missing_messages() in simplest case of adding a # message for which UserMessage row doesn't exist for this user. sent_message = send_fake_message('Test Message 1', stream) idle_user_msg_list = get_user_messages(long_term_idle_user) idle_user_msg_count = len(idle_user_msg_list) self.assertNotEqual(idle_user_msg_list[-1], sent_message) with queries_captured() as queries: add_missing_messages(long_term_idle_user) self.assert_length(queries, 5) idle_user_msg_list = get_user_messages(long_term_idle_user) self.assertEqual(len(idle_user_msg_list), idle_user_msg_count + 1) self.assertEqual(idle_user_msg_list[-1], sent_message) # Test that add_missing_messages() only adds messages that aren't # already present in the UserMessage table. This test works on the # fact that previous test just above this added a message but didn't # updated the last_active_message_id field for the user. sent_message = send_fake_message('Test Message 2', stream) idle_user_msg_list = get_user_messages(long_term_idle_user) idle_user_msg_count = len(idle_user_msg_list) self.assertNotEqual(idle_user_msg_list[-1], sent_message) with queries_captured() as queries: add_missing_messages(long_term_idle_user) self.assert_length(queries, 5) idle_user_msg_list = get_user_messages(long_term_idle_user) self.assertEqual(len(idle_user_msg_list), idle_user_msg_count + 1) self.assertEqual(idle_user_msg_list[-1], sent_message) # Test UserMessage rows are created correctly in case of stream # Subscription was altered by admin while user was away. # Test for a public stream. sent_message_list = [] sent_message_list.append(send_fake_message('Test Message 3', stream)) # Alter subscription to stream. self.unsubscribe(long_term_idle_user, stream_name) send_fake_message('Test Message 4', stream) self.subscribe(long_term_idle_user, stream_name) sent_message_list.append(send_fake_message('Test Message 5', stream)) sent_message_list.reverse() idle_user_msg_list = get_user_messages(long_term_idle_user) idle_user_msg_count = len(idle_user_msg_list) for sent_message in sent_message_list: self.assertNotEqual(idle_user_msg_list.pop(), sent_message) with queries_captured() as queries: add_missing_messages(long_term_idle_user) self.assert_length(queries, 5) idle_user_msg_list = get_user_messages(long_term_idle_user) self.assertEqual(len(idle_user_msg_list), idle_user_msg_count + 2) for sent_message in sent_message_list: self.assertEqual(idle_user_msg_list.pop(), sent_message) # Test consecutive subscribe/unsubscribe in a public stream sent_message_list = [] sent_message_list.append(send_fake_message('Test Message 6', stream)) # Unsubscribe from stream and then immediately subscribe back again. self.unsubscribe(long_term_idle_user, stream_name) self.subscribe(long_term_idle_user, stream_name) sent_message_list.append(send_fake_message('Test Message 7', stream)) # Again unsubscribe from stream and send a message. # This will make sure that if initially in a unsubscribed state # a consecutive subscribe/unsubscribe doesn't misbehave. self.unsubscribe(long_term_idle_user, stream_name) send_fake_message('Test Message 8', stream) # Do a subscribe and unsubscribe immediately. self.subscribe(long_term_idle_user, stream_name) self.unsubscribe(long_term_idle_user, stream_name) sent_message_list.reverse() idle_user_msg_list = get_user_messages(long_term_idle_user) idle_user_msg_count = len(idle_user_msg_list) for sent_message in sent_message_list: self.assertNotEqual(idle_user_msg_list.pop(), sent_message) with queries_captured() as queries: add_missing_messages(long_term_idle_user) self.assert_length(queries, 5) idle_user_msg_list = get_user_messages(long_term_idle_user) self.assertEqual(len(idle_user_msg_list), idle_user_msg_count + 2) for sent_message in sent_message_list: self.assertEqual(idle_user_msg_list.pop(), sent_message) # Test for when user unsubscribes before soft deactivation # (must reactivate them in order to do this). do_soft_activate_users([long_term_idle_user]) self.subscribe(long_term_idle_user, stream_name) # Send a real message to update last_active_message_id sent_message_id = self.send_stream_message( sender.email, stream_name, 'Test Message 9') self.unsubscribe(long_term_idle_user, stream_name) # Soft deactivate and send another message to the unsubscribed stream. do_soft_deactivate_users([long_term_idle_user]) send_fake_message('Test Message 10', stream) idle_user_msg_list = get_user_messages(long_term_idle_user) idle_user_msg_count = len(idle_user_msg_list) self.assertEqual(idle_user_msg_list[-1].id, sent_message_id) with queries_captured() as queries: add_missing_messages(long_term_idle_user) # There are no streams to fetch missing messages from, so # the Message.objects query will be avoided. self.assert_length(queries, 4) idle_user_msg_list = get_user_messages(long_term_idle_user) # No new UserMessage rows should have been created. self.assertEqual(len(idle_user_msg_list), idle_user_msg_count) # Note: At this point in this test we have long_term_idle_user # unsubscribed from the 'Denmark' stream. # Test for a Private Stream. stream_name = "Core" private_stream = self.make_stream('Core', invite_only=True) self.subscribe(self.example_user("iago"), stream_name) sent_message_list = [] send_fake_message('Test Message 11', private_stream) self.subscribe(self.example_user("hamlet"), stream_name) sent_message_list.append(send_fake_message('Test Message 12', private_stream)) self.unsubscribe(long_term_idle_user, stream_name) send_fake_message('Test Message 13', private_stream) self.subscribe(long_term_idle_user, stream_name) sent_message_list.append(send_fake_message('Test Message 14', private_stream)) sent_message_list.reverse() idle_user_msg_list = get_user_messages(long_term_idle_user) idle_user_msg_count = len(idle_user_msg_list) for sent_message in sent_message_list: self.assertNotEqual(idle_user_msg_list.pop(), sent_message) with queries_captured() as queries: add_missing_messages(long_term_idle_user) self.assert_length(queries, 5) idle_user_msg_list = get_user_messages(long_term_idle_user) self.assertEqual(len(idle_user_msg_list), idle_user_msg_count + 2) for sent_message in sent_message_list: self.assertEqual(idle_user_msg_list.pop(), sent_message) def test_user_message_filter(self) -> None: # In this test we are basically testing out the logic used out in # do_send_messages() in action.py for filtering the messages for which # UserMessage rows should be created for a soft-deactivated user. recipient_list = [ self.example_user("hamlet"), self.example_user("iago"), self.example_user('cordelia') ] for user_profile in recipient_list: self.subscribe(user_profile, "Denmark") cordelia = self.example_user('cordelia') sender = self.example_email('iago') stream_name = 'Denmark' topic_name = 'foo' def send_stream_message(content: str) -> None: self.send_stream_message(sender, stream_name, content, topic_name) def send_personal_message(content: str) -> None: self.send_personal_message(sender, self.example_email("hamlet"), content) long_term_idle_user = self.example_user('hamlet') self.send_stream_message(long_term_idle_user.email, stream_name) do_soft_deactivate_users([long_term_idle_user]) def assert_um_count(user: UserProfile, count: int) -> None: user_messages = get_user_messages(user) self.assertEqual(len(user_messages), count) def assert_last_um_content(user: UserProfile, content: str, negate: bool=False) -> None: user_messages = get_user_messages(user) if negate: self.assertNotEqual(user_messages[-1].content, content) else: self.assertEqual(user_messages[-1].content, content) # Test that sending a message to a stream with soft deactivated user # doesn't end up creating UserMessage row for deactivated user. general_user_msg_count = len(get_user_messages(cordelia)) soft_deactivated_user_msg_count = len(get_user_messages(long_term_idle_user)) message = 'Test Message 1' send_stream_message(message) assert_last_um_content(long_term_idle_user, message, negate=True) assert_um_count(long_term_idle_user, soft_deactivated_user_msg_count) assert_um_count(cordelia, general_user_msg_count + 1) assert_last_um_content(cordelia, message) # Test that sending a message to a stream with soft deactivated user # and push/email notifications on creates a UserMessage row for the # deactivated user. sub = get_subscription(stream_name, long_term_idle_user) sub.push_notifications = True sub.save() general_user_msg_count = len(get_user_messages(cordelia)) soft_deactivated_user_msg_count = len(get_user_messages(long_term_idle_user)) message = 'Test private stream message' send_stream_message(message) assert_um_count(long_term_idle_user, soft_deactivated_user_msg_count + 1) assert_last_um_content(long_term_idle_user, message) sub.push_notifications = False sub.save() # Test sending a private message to soft deactivated user creates # UserMessage row. soft_deactivated_user_msg_count = len(get_user_messages(long_term_idle_user)) message = 'Test PM' send_personal_message(message) assert_um_count(long_term_idle_user, soft_deactivated_user_msg_count + 1) assert_last_um_content(long_term_idle_user, message) # Test UserMessage row is created while user is deactivated if # user itself is mentioned. general_user_msg_count = len(get_user_messages(cordelia)) soft_deactivated_user_msg_count = len(get_user_messages(long_term_idle_user)) message = 'Test @**King Hamlet** mention' send_stream_message(message) assert_last_um_content(long_term_idle_user, message) assert_um_count(long_term_idle_user, soft_deactivated_user_msg_count + 1) assert_um_count(cordelia, general_user_msg_count + 1) assert_last_um_content(cordelia, message) # Test UserMessage row is not created while user is deactivated if # anyone is mentioned but the user. general_user_msg_count = len(get_user_messages(cordelia)) soft_deactivated_user_msg_count = len(get_user_messages(long_term_idle_user)) message = 'Test @**Cordelia Lear** mention' send_stream_message(message) assert_last_um_content(long_term_idle_user, message, negate=True) assert_um_count(long_term_idle_user, soft_deactivated_user_msg_count) assert_um_count(cordelia, general_user_msg_count + 1) assert_last_um_content(cordelia, message) # Test UserMessage row is created while user is deactivated if # there is a wildcard mention such as @all or @everyone general_user_msg_count = len(get_user_messages(cordelia)) soft_deactivated_user_msg_count = len(get_user_messages(long_term_idle_user)) message = 'Test @**all** mention' send_stream_message(message) assert_last_um_content(long_term_idle_user, message) assert_um_count(long_term_idle_user, soft_deactivated_user_msg_count + 1) assert_um_count(cordelia, general_user_msg_count + 1) assert_last_um_content(cordelia, message) general_user_msg_count = len(get_user_messages(cordelia)) soft_deactivated_user_msg_count = len(get_user_messages(long_term_idle_user)) message = 'Test @**everyone** mention' send_stream_message(message) assert_last_um_content(long_term_idle_user, message) assert_um_count(long_term_idle_user, soft_deactivated_user_msg_count + 1) assert_um_count(cordelia, general_user_msg_count + 1) assert_last_um_content(cordelia, message) general_user_msg_count = len(get_user_messages(cordelia)) soft_deactivated_user_msg_count = len(get_user_messages(long_term_idle_user)) message = 'Test @**stream** mention' send_stream_message(message) assert_last_um_content(long_term_idle_user, message) assert_um_count(long_term_idle_user, soft_deactivated_user_msg_count + 1) assert_um_count(cordelia, general_user_msg_count + 1) assert_last_um_content(cordelia, message) # Test UserMessage row is not created while user is deactivated if there # is a alert word in message. do_add_alert_words(long_term_idle_user, ['test_alert_word']) general_user_msg_count = len(get_user_messages(cordelia)) soft_deactivated_user_msg_count = len(get_user_messages(long_term_idle_user)) message = 'Testing test_alert_word' send_stream_message(message) assert_last_um_content(long_term_idle_user, message) assert_um_count(long_term_idle_user, soft_deactivated_user_msg_count + 1) assert_um_count(cordelia, general_user_msg_count + 1) assert_last_um_content(cordelia, message) # Test UserMessage row is created while user is deactivated if # message is a me message. general_user_msg_count = len(get_user_messages(cordelia)) soft_deactivated_user_msg_count = len(get_user_messages(long_term_idle_user)) message = '/me says test' send_stream_message(message) assert_last_um_content(long_term_idle_user, message, negate=True) assert_um_count(long_term_idle_user, soft_deactivated_user_msg_count) assert_um_count(cordelia, general_user_msg_count + 1) assert_last_um_content(cordelia, message) class MessageHydrationTest(ZulipTestCase): def test_hydrate_stream_recipient_info(self) -> None: realm = get_realm('zulip') cordelia = self.example_user('cordelia') stream_id = get_stream('Verona', realm).id obj = dict( raw_display_recipient='Verona', recipient_type=Recipient.STREAM, recipient_type_id=stream_id, sender_is_mirror_dummy=False, sender_email=cordelia.email, sender_full_name=cordelia.full_name, sender_short_name=cordelia.short_name, sender_id=cordelia.id, ) MessageDict.hydrate_recipient_info(obj) self.assertEqual(obj['display_recipient'], 'Verona') self.assertEqual(obj['type'], 'stream') def test_hydrate_pm_recipient_info(self) -> None: cordelia = self.example_user('cordelia') obj = dict( raw_display_recipient=[ dict( email='aaron@example.com', full_name='Aaron Smith', ), ], recipient_type=Recipient.PERSONAL, recipient_type_id=None, sender_is_mirror_dummy=False, sender_email=cordelia.email, sender_full_name=cordelia.full_name, sender_short_name=cordelia.short_name, sender_id=cordelia.id, ) MessageDict.hydrate_recipient_info(obj) self.assertEqual( obj['display_recipient'], [ dict( email='aaron@example.com', full_name='Aaron Smith', ), dict( email=cordelia.email, full_name=cordelia.full_name, id=cordelia.id, short_name=cordelia.short_name, is_mirror_dummy=False, ), ], ) self.assertEqual(obj['type'], 'private') def test_messages_for_ids(self) -> None: hamlet = self.example_user('hamlet') cordelia = self.example_user('cordelia') stream_name = 'test stream' self.subscribe(cordelia, stream_name) old_message_id = self.send_stream_message(cordelia.email, stream_name, content='foo') self.subscribe(hamlet, stream_name) content = 'hello @**King Hamlet**' new_message_id = self.send_stream_message(cordelia.email, stream_name, content=content) user_message_flags = { old_message_id: ['read', 'historical'], new_message_id: ['mentioned'], } messages = messages_for_ids( message_ids=[old_message_id, new_message_id], user_message_flags=user_message_flags, search_fields={}, apply_markdown=True, client_gravatar=True, allow_edit_history=False, ) self.assertEqual(len(messages), 2) for message in messages: if message['id'] == old_message_id: old_message = message elif message['id'] == new_message_id: new_message = message self.assertEqual(old_message['content'], '<p>foo</p>') self.assertEqual(old_message['flags'], ['read', 'historical']) self.assertIn('class="user-mention"', new_message['content']) self.assertEqual(new_message['flags'], ['mentioned']) class MessageVisibilityTest(ZulipTestCase): def test_update_first_visible_message_id(self) -> None: Message.objects.all().delete() message_ids = [self.send_stream_message(self.example_email("othello"), "Scotland") for i in range(15)] realm = get_realm("zulip") realm.message_visibility_limit = 10 realm.save() expected_message_id = message_ids[5] update_first_visible_message_id(realm) self.assertEqual(get_first_visible_message_id(realm), expected_message_id) # If the message_visibility_limit is greater than number of messages # get_first_visible_message_id should return 0 message_visibility_limit = 50 realm.message_visibility_limit = message_visibility_limit realm.save() update_first_visible_message_id(realm) self.assertEqual(get_first_visible_message_id(realm), 0) def test_maybe_update_first_visible_message_id(self) -> None: realm = get_realm("zulip") lookback_hours = 30 realm.message_visibility_limit = None realm.save() end_time = timezone_now() - datetime.timedelta(hours=lookback_hours - 5) stat = COUNT_STATS['messages_sent:is_bot:hour'] RealmCount.objects.create(realm=realm, property=stat.property, end_time=end_time, value=5) with mock.patch("zerver.lib.message.update_first_visible_message_id") as m: maybe_update_first_visible_message_id(realm, lookback_hours) m.assert_not_called() realm.message_visibility_limit = 10 realm.save() RealmCount.objects.all().delete() with mock.patch("zerver.lib.message.update_first_visible_message_id") as m: maybe_update_first_visible_message_id(realm, lookback_hours) # Cache got cleared when the value of message_visibility_limit was updated m.assert_called_once_with(realm) with mock.patch('zerver.lib.message.cache_get', return_value=True), \ mock.patch("zerver.lib.message.update_first_visible_message_id") as m: maybe_update_first_visible_message_id(realm, lookback_hours) m.assert_not_called() RealmCount.objects.create(realm=realm, property=stat.property, end_time=end_time, value=5) with mock.patch('zerver.lib.message.cache_get', return_value=True), \ mock.patch("zerver.lib.message.update_first_visible_message_id") as m: maybe_update_first_visible_message_id(realm, lookback_hours) m.assert_called_once_with(realm)
[ "str", "str", "str", "UserProfile", "UserProfile", "str", "str", "str", "str", "str", "str", "Any", "Any", "Any", "str", "str", "bool", "Any", "str", "str", "str", "int", "bool", "int", "bool", "int", "str", "int", "str", "str", "Any", "Any", "List[int]", "Any", "List[int]", "int", "str", "int", "bool", "int", "int", "int", "int", "str", "str", "Stream", "str", "str", "UserProfile", "int", "UserProfile", "str" ]
[ 4713, 9212, 9423, 10074, 10098, 23048, 23069, 25425, 33345, 33363, 33377, 43393, 70106, 71008, 73893, 73906, 73919, 76544, 78591, 78600, 78610, 84688, 104662, 104743, 104818, 105258, 105275, 105921, 105938, 105950, 116727, 118000, 122155, 122192, 138832, 139247, 139265, 139275, 145104, 145188, 145581, 145809, 146044, 149042, 150905, 150918, 159567, 159741, 160064, 160084, 160248, 160270 ]
[ 4716, 9215, 9426, 10085, 10109, 23051, 23072, 25428, 33348, 33366, 33380, 43396, 70109, 71011, 73896, 73909, 73923, 76547, 78594, 78603, 78613, 84691, 104666, 104746, 104822, 105261, 105278, 105924, 105941, 105953, 116730, 118003, 122164, 122195, 138841, 139250, 139268, 139278, 145108, 145191, 145584, 145812, 146047, 149045, 150908, 150924, 159570, 159744, 160075, 160087, 160259, 160273 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_middleware.py
import time from django.test import override_settings from unittest.mock import Mock, patch from zerver.lib.test_classes import ZulipTestCase from zerver.middleware import is_slow_query from zerver.middleware import write_log_line class SlowQueryTest(ZulipTestCase): SLOW_QUERY_TIME = 10 log_data = {'extra': '[transport=websocket]', 'time_started': 0, 'bugdown_requests_start': 0, 'bugdown_time_start': 0, 'remote_cache_time_start': 0, 'remote_cache_requests_start': 0} def test_is_slow_query(self) -> None: self.assertFalse(is_slow_query(1.1, '/some/random/url')) self.assertTrue(is_slow_query(2, '/some/random/url')) self.assertTrue(is_slow_query(5.1, '/activity')) self.assertFalse(is_slow_query(2, '/activity')) self.assertFalse(is_slow_query(2, '/json/report/error')) self.assertFalse(is_slow_query(2, '/api/v1/deployments/report_error')) self.assertFalse(is_slow_query(2, '/realm_activity/whatever')) self.assertFalse(is_slow_query(2, '/user_activity/whatever')) self.assertFalse(is_slow_query(9, '/accounts/webathena_kerberos_login/')) self.assertTrue(is_slow_query(11, '/accounts/webathena_kerberos_login/')) @override_settings(SLOW_QUERY_LOGS_STREAM="logs") @patch('logging.info') def test_slow_query_log(self, mock_logging_info: Mock) -> None: self.log_data['time_started'] = time.time() - self.SLOW_QUERY_TIME write_log_line(self.log_data, path='/socket/open', method='SOCKET', remote_ip='123.456.789.012', email='unknown', client_name='?') last_message = self.get_last_message() self.assertEqual(last_message.sender.email, "error-bot@zulip.com") self.assertIn("logs", str(last_message.recipient)) self.assertEqual(last_message.topic_name(), "testserver: slow queries") self.assertRegexpMatches(last_message.content, r"123\.456\.789\.012 SOCKET 200 10\.\ds .*") @override_settings(ERROR_BOT=None) @patch('logging.info') @patch('zerver.lib.actions.internal_send_message') def test_slow_query_log_without_error_bot(self, mock_internal_send_message: Mock, mock_logging_info: Mock) -> None: self.log_data['time_started'] = time.time() - self.SLOW_QUERY_TIME write_log_line(self.log_data, path='/socket/open', method='SOCKET', remote_ip='123.456.789.012', email='unknown', client_name='?') mock_internal_send_message.assert_not_called()
[ "Mock", "Mock", "Mock" ]
[ 1428, 2277, 2348 ]
[ 1432, 2281, 2352 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_migrations.py
# These are tests for Zulip's database migrations. System documented at: # https://zulip.readthedocs.io/en/latest/subsystems/schema-migrations.html # # You can also read # https://www.caktusgroup.com/blog/2016/02/02/writing-unit-tests-django-migrations/ # to get a tutorial on the framework that inspired this feature. from zerver.lib.test_classes import MigrationsTestCase from zerver.lib.test_helpers import use_db_models, make_client from django.utils.timezone import now as timezone_now from django.db.migrations.state import StateApps from django.db.models.base import ModelBase from zerver.models import get_stream class EmojiName2IdTestCase(MigrationsTestCase): migrate_from = '0144_remove_realm_create_generic_bot_by_admins_only' migrate_to = '0145_reactions_realm_emoji_name_to_id' @use_db_models def setUpBeforeMigration(self, apps: StateApps) -> None: Reaction = apps.get_model('zerver', 'Reaction') RealmEmoji = apps.get_model('zerver', 'RealmEmoji') Message = apps.get_model('zerver', 'Message') Recipient = apps.get_model('zerver', 'Recipient') sender = self.example_user('iago') realm = sender.realm sending_client = make_client(name="test suite") stream_name = 'Denmark' stream = get_stream(stream_name, realm) subject = 'foo' def send_fake_message(message_content: str, stream: ModelBase) -> ModelBase: recipient = Recipient.objects.get(type_id=stream.id, type=2) return Message.objects.create(sender = sender, recipient = recipient, subject = subject, content = message_content, pub_date = timezone_now(), sending_client = sending_client) message = send_fake_message('Test 1', stream) # Create reactions for all the realm emoji's on the message we faked. for realm_emoji in RealmEmoji.objects.all(): reaction = Reaction(user_profile=sender, message=message, emoji_name=realm_emoji.name, emoji_code=realm_emoji.name, reaction_type='realm_emoji') reaction.save() realm_emoji_reactions_count = Reaction.objects.filter(reaction_type='realm_emoji').count() self.assertEqual(realm_emoji_reactions_count, 1) def test_tags_migrated(self) -> None: """Test runs after the migration, and verifies the data was migrated correctly""" Reaction = self.apps.get_model('zerver', 'Reaction') RealmEmoji = self.apps.get_model('zerver', 'RealmEmoji') realm_emoji_reactions = Reaction.objects.filter(reaction_type='realm_emoji') realm_emoji_reactions_count = realm_emoji_reactions.count() self.assertEqual(realm_emoji_reactions_count, 1) for reaction in realm_emoji_reactions: realm_emoji = RealmEmoji.objects.get( realm_id=reaction.user_profile.realm_id, name=reaction.emoji_name) self.assertEqual(reaction.emoji_code, str(realm_emoji.id))
[ "StateApps", "str", "ModelBase" ]
[ 869, 1398, 1411 ]
[ 878, 1401, 1420 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_muting.py
import ujson from django.http import HttpResponse from mock import patch from typing import Any, Dict from zerver.lib.test_classes import ZulipTestCase from zerver.lib.stream_topic import StreamTopicTarget from zerver.models import ( get_realm, get_stream, get_stream_recipient, get_user, Recipient, UserProfile, ) from zerver.lib.topic_mutes import ( add_topic_mute, get_topic_mutes, topic_is_muted, ) class MutedTopicsTests(ZulipTestCase): def test_user_ids_muting_topic(self) -> None: hamlet = self.example_user('hamlet') cordelia = self.example_user('cordelia') realm = hamlet.realm stream = get_stream(u'Verona', realm) recipient = get_stream_recipient(stream.id) topic_name = 'teST topic' stream_topic_target = StreamTopicTarget( stream_id=stream.id, topic_name=topic_name, ) user_ids = stream_topic_target.user_ids_muting_topic() self.assertEqual(user_ids, set()) def mute_user(user: UserProfile) -> None: add_topic_mute( user_profile=user, stream_id=stream.id, recipient_id=recipient.id, topic_name='test TOPIC', ) mute_user(hamlet) user_ids = stream_topic_target.user_ids_muting_topic() self.assertEqual(user_ids, {hamlet.id}) mute_user(cordelia) user_ids = stream_topic_target.user_ids_muting_topic() self.assertEqual(user_ids, {hamlet.id, cordelia.id}) def test_add_muted_topic(self) -> None: email = self.example_email('hamlet') self.login(email) url = '/api/v1/users/me/subscriptions/muted_topics' data = {'stream': 'Verona', 'topic': 'Verona3', 'op': 'add'} result = self.api_patch(email, url, data) self.assert_json_success(result) user = self.example_user('hamlet') self.assertIn([u'Verona', u'Verona3'], get_topic_mutes(user)) stream = get_stream(u'Verona', user.realm) self.assertTrue(topic_is_muted(user, stream.id, 'Verona3')) self.assertTrue(topic_is_muted(user, stream.id, 'verona3')) def test_remove_muted_topic(self) -> None: self.user_profile = self.example_user('hamlet') email = self.user_profile.email self.login(email) realm = self.user_profile.realm stream = get_stream(u'Verona', realm) recipient = get_stream_recipient(stream.id) add_topic_mute( user_profile=self.user_profile, stream_id=stream.id, recipient_id=recipient.id, topic_name=u'Verona3', ) url = '/api/v1/users/me/subscriptions/muted_topics' data = {'stream': 'Verona', 'topic': 'vERONA3', 'op': 'remove'} result = self.api_patch(email, url, data) self.assert_json_success(result) user = self.example_user('hamlet') self.assertNotIn([[u'Verona', u'Verona3']], get_topic_mutes(user)) def test_muted_topic_add_invalid(self) -> None: self.user_profile = self.example_user('hamlet') email = self.user_profile.email self.login(email) realm = self.user_profile.realm stream = get_stream(u'Verona', realm) recipient = get_stream_recipient(stream.id) add_topic_mute( user_profile=self.user_profile, stream_id=stream.id, recipient_id=recipient.id, topic_name=u'Verona3', ) url = '/api/v1/users/me/subscriptions/muted_topics' data = {'stream': 'Verona', 'topic': 'Verona3', 'op': 'add'} result = self.api_patch(email, url, data) self.assert_json_error(result, "Topic already muted") def test_muted_topic_remove_invalid(self) -> None: self.user_profile = self.example_user('hamlet') email = self.user_profile.email self.login(email) url = '/api/v1/users/me/subscriptions/muted_topics' data = {'stream': 'BOGUS', 'topic': 'Verona3', 'op': 'remove'} result = self.api_patch(email, url, data) self.assert_json_error(result, "Topic is not muted") data = {'stream': 'Verona', 'topic': 'BOGUS', 'op': 'remove'} result = self.api_patch(email, url, data) self.assert_json_error(result, "Topic is not muted")
[ "UserProfile" ]
[ 1053 ]
[ 1064 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_narrow.py
# -*- coding: utf-8 -*- from django.db import connection from django.test import override_settings from sqlalchemy.sql import ( and_, select, column, table, literal, join, literal_column, ) from sqlalchemy.sql import compiler from zerver.models import ( Realm, Stream, Subscription, UserProfile, Attachment, get_display_recipient, get_personal_recipient, get_realm, get_stream, get_user, Reaction, UserMessage, get_stream_recipient, Message ) from zerver.lib.message import ( MessageDict, get_first_visible_message_id, ) from zerver.lib.narrow import ( build_narrow_filter, is_web_public_compatible, ) from zerver.lib.request import JsonableError from zerver.lib.sqlalchemy_utils import get_sqlalchemy_connection from zerver.lib.test_helpers import ( POSTRequestMock, TestCase, get_user_messages, queries_captured, ) from zerver.lib.test_classes import ( ZulipTestCase, ) from zerver.lib.topic import ( MATCH_TOPIC, TOPIC_NAME, ) from zerver.lib.topic_mutes import ( set_topic_mutes, ) from zerver.views.messages import ( exclude_muting_conditions, get_messages_backend, ok_to_include_history, NarrowBuilder, BadNarrowOperator, Query, post_process_limited_query, find_first_unread_anchor, LARGER_THAN_MAX_MESSAGE_ID, ) from typing import Dict, List, Mapping, Sequence, Tuple, Generic, Union, Any, Optional import mock import os import re import ujson def get_sqlalchemy_query_params(query: str) -> Dict[str, str]: dialect = get_sqlalchemy_connection().dialect comp = compiler.SQLCompiler(dialect, query) return comp.params def fix_ws(s: str) -> str: return re.sub(r'\s+', ' ', str(s)).strip() def get_recipient_id_for_stream_name(realm: Realm, stream_name: str) -> str: stream = get_stream(stream_name, realm) return get_stream_recipient(stream.id).id def mute_stream(realm: Realm, user_profile: str, stream_name: str) -> None: stream = get_stream(stream_name, realm) recipient = get_stream_recipient(stream.id) subscription = Subscription.objects.get(recipient=recipient, user_profile=user_profile) subscription.in_home_view = False subscription.save() def first_visible_id_as(message_id: int) -> Any: return mock.patch( 'zerver.views.messages.get_first_visible_message_id', return_value=message_id, ) class NarrowBuilderTest(ZulipTestCase): def setUp(self) -> None: self.realm = get_realm('zulip') self.user_profile = self.example_user('hamlet') self.builder = NarrowBuilder(self.user_profile, column('id')) self.raw_query = select([column("id")], None, table("zerver_message")) def test_add_term_using_not_defined_operator(self) -> None: term = dict(operator='not-defined', operand='any') self.assertRaises(BadNarrowOperator, self._build_query, term) def test_add_term_using_stream_operator(self) -> None: term = dict(operator='stream', operand='Scotland') self._do_add_term_test(term, 'WHERE recipient_id = :recipient_id_1') def test_add_term_using_stream_operator_and_negated(self) -> None: # NEGATED term = dict(operator='stream', operand='Scotland', negated=True) self._do_add_term_test(term, 'WHERE recipient_id != :recipient_id_1') def test_add_term_using_stream_operator_and_non_existing_operand_should_raise_error( self) -> None: # NEGATED term = dict(operator='stream', operand='NonExistingStream') self.assertRaises(BadNarrowOperator, self._build_query, term) def test_add_term_using_is_operator_and_private_operand(self) -> None: term = dict(operator='is', operand='private') self._do_add_term_test(term, 'WHERE (flags & :flags_1) != :param_1') def test_add_term_using_is_operator_private_operand_and_negated( self) -> None: # NEGATED term = dict(operator='is', operand='private', negated=True) self._do_add_term_test(term, 'WHERE (flags & :flags_1) = :param_1') def test_add_term_using_is_operator_and_non_private_operand(self) -> None: for operand in ['starred', 'mentioned', 'alerted']: term = dict(operator='is', operand=operand) self._do_add_term_test(term, 'WHERE (flags & :flags_1) != :param_1') def test_add_term_using_is_operator_and_unread_operand(self) -> None: term = dict(operator='is', operand='unread') self._do_add_term_test(term, 'WHERE (flags & :flags_1) = :param_1') def test_add_term_using_is_operator_and_unread_operand_and_negated( self) -> None: # NEGATED term = dict(operator='is', operand='unread', negated=True) self._do_add_term_test(term, 'WHERE (flags & :flags_1) != :param_1') def test_add_term_using_is_operator_non_private_operand_and_negated( self) -> None: # NEGATED term = dict(operator='is', operand='starred', negated=True) where_clause = 'WHERE (flags & :flags_1) = :param_1' params = dict( flags_1=UserMessage.flags.starred.mask, param_1=0 ) self._do_add_term_test(term, where_clause, params) term = dict(operator='is', operand='alerted', negated=True) where_clause = 'WHERE (flags & :flags_1) = :param_1' params = dict( flags_1=UserMessage.flags.has_alert_word.mask, param_1=0 ) self._do_add_term_test(term, where_clause, params) term = dict(operator='is', operand='mentioned', negated=True) where_clause = 'WHERE NOT ((flags & :flags_1) != :param_1 OR (flags & :flags_2) != :param_2)' params = dict( flags_1=UserMessage.flags.mentioned.mask, param_1=0, flags_2=UserMessage.flags.wildcard_mentioned.mask, param_2=0 ) self._do_add_term_test(term, where_clause, params) def test_add_term_using_non_supported_operator_should_raise_error(self) -> None: term = dict(operator='is', operand='non_supported') self.assertRaises(BadNarrowOperator, self._build_query, term) def test_add_term_using_topic_operator_and_lunch_operand(self) -> None: term = dict(operator='topic', operand='lunch') self._do_add_term_test(term, 'WHERE upper(subject) = upper(:param_1)') def test_add_term_using_topic_operator_lunch_operand_and_negated( self) -> None: # NEGATED term = dict(operator='topic', operand='lunch', negated=True) self._do_add_term_test(term, 'WHERE upper(subject) != upper(:param_1)') def test_add_term_using_topic_operator_and_personal_operand(self) -> None: term = dict(operator='topic', operand='personal') self._do_add_term_test(term, 'WHERE upper(subject) = upper(:param_1)') def test_add_term_using_topic_operator_personal_operand_and_negated( self) -> None: # NEGATED term = dict(operator='topic', operand='personal', negated=True) self._do_add_term_test(term, 'WHERE upper(subject) != upper(:param_1)') def test_add_term_using_sender_operator(self) -> None: term = dict(operator='sender', operand=self.example_email("othello")) self._do_add_term_test(term, 'WHERE sender_id = :param_1') def test_add_term_using_sender_operator_and_negated(self) -> None: # NEGATED term = dict(operator='sender', operand=self.example_email("othello"), negated=True) self._do_add_term_test(term, 'WHERE sender_id != :param_1') def test_add_term_using_sender_operator_with_non_existing_user_as_operand( self) -> None: # NEGATED term = dict(operator='sender', operand='non-existing@zulip.com') self.assertRaises(BadNarrowOperator, self._build_query, term) def test_add_term_using_pm_with_operator_and_not_the_same_user_as_operand(self) -> None: term = dict(operator='pm-with', operand=self.example_email("othello")) self._do_add_term_test(term, 'WHERE sender_id = :sender_id_1 AND recipient_id = :recipient_id_1 OR sender_id = :sender_id_2 AND recipient_id = :recipient_id_2') def test_add_term_using_pm_with_operator_not_the_same_user_as_operand_and_negated( self) -> None: # NEGATED term = dict(operator='pm-with', operand=self.example_email("othello"), negated=True) self._do_add_term_test(term, 'WHERE NOT (sender_id = :sender_id_1 AND recipient_id = :recipient_id_1 OR sender_id = :sender_id_2 AND recipient_id = :recipient_id_2)') def test_add_term_using_pm_with_operator_the_same_user_as_operand(self) -> None: term = dict(operator='pm-with', operand=self.example_email("hamlet")) self._do_add_term_test(term, 'WHERE sender_id = :sender_id_1 AND recipient_id = :recipient_id_1') def test_add_term_using_pm_with_operator_the_same_user_as_operand_and_negated( self) -> None: # NEGATED term = dict(operator='pm-with', operand=self.example_email("hamlet"), negated=True) self._do_add_term_test(term, 'WHERE NOT (sender_id = :sender_id_1 AND recipient_id = :recipient_id_1)') def test_add_term_using_pm_with_operator_and_self_and_user_as_operand(self) -> None: term = dict(operator='pm-with', operand='hamlet@zulip.com, othello@zulip.com') self._do_add_term_test(term, 'WHERE sender_id = :sender_id_1 AND recipient_id = :recipient_id_1 OR sender_id = :sender_id_2 AND recipient_id = :recipient_id_2') def test_add_term_using_pm_with_operator_more_than_one_user_as_operand(self) -> None: term = dict(operator='pm-with', operand='cordelia@zulip.com, othello@zulip.com') self._do_add_term_test(term, 'WHERE recipient_id = :recipient_id_1') def test_add_term_using_pm_with_operator_self_and_user_as_operand_and_negated( self) -> None: # NEGATED term = dict(operator='pm-with', operand='hamlet@zulip.com, othello@zulip.com', negated=True) self._do_add_term_test(term, 'WHERE NOT (sender_id = :sender_id_1 AND recipient_id = :recipient_id_1 OR sender_id = :sender_id_2 AND recipient_id = :recipient_id_2)') def test_add_term_using_pm_with_operator_more_than_one_user_as_operand_and_negated(self) -> None: term = dict(operator='pm-with', operand='cordelia@zulip.com, othello@zulip.com', negated=True) self._do_add_term_test(term, 'WHERE recipient_id != :recipient_id_1') def test_add_term_using_pm_with_operator_with_comma_noise(self) -> None: term = dict(operator='pm-with', operand=' ,,, ,,, ,') self.assertRaises(BadNarrowOperator, self._build_query, term) def test_add_term_using_pm_with_operator_with_existing_and_non_existing_user_as_operand(self) -> None: term = dict(operator='pm-with', operand='othello@zulip.com,non-existing@zulip.com') self.assertRaises(BadNarrowOperator, self._build_query, term) def test_add_term_using_id_operator(self) -> None: term = dict(operator='id', operand=555) self._do_add_term_test(term, 'WHERE id = :param_1') def test_add_term_using_id_operator_invalid(self) -> None: term = dict(operator='id', operand='') self.assertRaises(BadNarrowOperator, self._build_query, term) term = dict(operator='id', operand='notanint') self.assertRaises(BadNarrowOperator, self._build_query, term) def test_add_term_using_id_operator_and_negated(self) -> None: # NEGATED term = dict(operator='id', operand=555, negated=True) self._do_add_term_test(term, 'WHERE id != :param_1') def test_add_term_using_group_pm_operator_and_not_the_same_user_as_operand(self) -> None: # Test wtihout any such group PM threads existing term = dict(operator='group-pm-with', operand=self.example_email("othello")) self._do_add_term_test(term, 'WHERE 1 != 1') # Test with at least one such group PM thread existing self.send_huddle_message(self.user_profile.email, [self.example_email("othello"), self.example_email("cordelia")]) term = dict(operator='group-pm-with', operand=self.example_email("othello")) self._do_add_term_test(term, 'WHERE recipient_id IN (:recipient_id_1)') def test_add_term_using_group_pm_operator_not_the_same_user_as_operand_and_negated( self) -> None: # NEGATED term = dict(operator='group-pm-with', operand=self.example_email("othello"), negated=True) self._do_add_term_test(term, 'WHERE 1 = 1') def test_add_term_using_group_pm_operator_with_non_existing_user_as_operand(self) -> None: term = dict(operator='group-pm-with', operand='non-existing@zulip.com') self.assertRaises(BadNarrowOperator, self._build_query, term) @override_settings(USING_PGROONGA=False) def test_add_term_using_search_operator(self) -> None: term = dict(operator='search', operand='"french fries"') self._do_add_term_test(term, 'WHERE (lower(content) LIKE lower(:content_1) OR lower(subject) LIKE lower(:subject_1)) AND (search_tsvector @@ plainto_tsquery(:param_2, :param_3))') @override_settings(USING_PGROONGA=False) def test_add_term_using_search_operator_and_negated( self) -> None: # NEGATED term = dict(operator='search', operand='"french fries"', negated=True) self._do_add_term_test(term, 'WHERE NOT (lower(content) LIKE lower(:content_1) OR lower(subject) LIKE lower(:subject_1)) AND NOT (search_tsvector @@ plainto_tsquery(:param_2, :param_3))') @override_settings(USING_PGROONGA=True) def test_add_term_using_search_operator_pgroonga(self) -> None: term = dict(operator='search', operand='"french fries"') self._do_add_term_test(term, 'WHERE search_pgroonga &@~ escape_html(:escape_html_1)') @override_settings(USING_PGROONGA=True) def test_add_term_using_search_operator_and_negated_pgroonga( self) -> None: # NEGATED term = dict(operator='search', operand='"french fries"', negated=True) self._do_add_term_test(term, 'WHERE NOT (search_pgroonga &@~ escape_html(:escape_html_1))') def test_add_term_using_has_operator_and_attachment_operand(self) -> None: term = dict(operator='has', operand='attachment') self._do_add_term_test(term, 'WHERE has_attachment') def test_add_term_using_has_operator_attachment_operand_and_negated( self) -> None: # NEGATED term = dict(operator='has', operand='attachment', negated=True) self._do_add_term_test(term, 'WHERE NOT has_attachment') def test_add_term_using_has_operator_and_image_operand(self) -> None: term = dict(operator='has', operand='image') self._do_add_term_test(term, 'WHERE has_image') def test_add_term_using_has_operator_image_operand_and_negated( self) -> None: # NEGATED term = dict(operator='has', operand='image', negated=True) self._do_add_term_test(term, 'WHERE NOT has_image') def test_add_term_using_has_operator_and_link_operand(self) -> None: term = dict(operator='has', operand='link') self._do_add_term_test(term, 'WHERE has_link') def test_add_term_using_has_operator_link_operand_and_negated( self) -> None: # NEGATED term = dict(operator='has', operand='link', negated=True) self._do_add_term_test(term, 'WHERE NOT has_link') def test_add_term_using_has_operator_non_supported_operand_should_raise_error(self) -> None: term = dict(operator='has', operand='non_supported') self.assertRaises(BadNarrowOperator, self._build_query, term) def test_add_term_using_in_operator(self) -> None: mute_stream(self.realm, self.user_profile, 'Verona') term = dict(operator='in', operand='home') self._do_add_term_test(term, 'WHERE recipient_id NOT IN (:recipient_id_1)') def test_add_term_using_in_operator_and_negated(self) -> None: # negated = True should not change anything mute_stream(self.realm, self.user_profile, 'Verona') term = dict(operator='in', operand='home', negated=True) self._do_add_term_test(term, 'WHERE recipient_id NOT IN (:recipient_id_1)') def test_add_term_using_in_operator_and_all_operand(self) -> None: mute_stream(self.realm, self.user_profile, 'Verona') term = dict(operator='in', operand='all') query = self._build_query(term) self.assertEqual(str(query), 'SELECT id \nFROM zerver_message') def test_add_term_using_in_operator_all_operand_and_negated(self) -> None: # negated = True should not change anything mute_stream(self.realm, self.user_profile, 'Verona') term = dict(operator='in', operand='all', negated=True) query = self._build_query(term) self.assertEqual(str(query), 'SELECT id \nFROM zerver_message') def test_add_term_using_in_operator_and_not_defined_operand(self) -> None: term = dict(operator='in', operand='not_defined') self.assertRaises(BadNarrowOperator, self._build_query, term) def test_add_term_using_near_operator(self) -> None: term = dict(operator='near', operand='operand') query = self._build_query(term) self.assertEqual(str(query), 'SELECT id \nFROM zerver_message') def _do_add_term_test(self, term: Dict[str, Any], where_clause: str, params: Optional[Dict[str, Any]]=None) -> None: query = self._build_query(term) if params is not None: actual_params = query.compile().params self.assertEqual(actual_params, params) self.assertIn(where_clause, str(query)) def _build_query(self, term: Dict[str, Any]) -> Query: return self.builder.add_term(self.raw_query, term) class NarrowLibraryTest(TestCase): def test_build_narrow_filter(self) -> None: fixtures_path = os.path.join(os.path.dirname(__file__), 'fixtures/narrow.json') scenarios = ujson.loads(open(fixtures_path, 'r').read()) self.assertTrue(len(scenarios) == 9) for scenario in scenarios: narrow = scenario['narrow'] accept_events = scenario['accept_events'] reject_events = scenario['reject_events'] narrow_filter = build_narrow_filter(narrow) for e in accept_events: self.assertTrue(narrow_filter(e)) for e in reject_events: self.assertFalse(narrow_filter(e)) def test_build_narrow_filter_invalid(self) -> None: with self.assertRaises(JsonableError): build_narrow_filter(["invalid_operator", "operand"]) def test_is_web_public_compatible(self) -> None: self.assertTrue(is_web_public_compatible([])) self.assertTrue(is_web_public_compatible([{"operator": "has", "operand": "attachment"}])) self.assertTrue(is_web_public_compatible([{"operator": "has", "operand": "image"}])) self.assertTrue(is_web_public_compatible([{"operator": "search", "operand": "magic"}])) self.assertTrue(is_web_public_compatible([{"operator": "near", "operand": "15"}])) self.assertTrue(is_web_public_compatible([{"operator": "id", "operand": "15"}, {"operator": "has", "operand": "attachment"}])) self.assertTrue(is_web_public_compatible([{"operator": "sender", "operand": "hamlet@zulip.com"}])) self.assertFalse(is_web_public_compatible([{"operator": "pm-with", "operand": "hamlet@zulip.com"}])) self.assertFalse(is_web_public_compatible([{"operator": "group-pm-with", "operand": "hamlet@zulip.com"}])) self.assertTrue(is_web_public_compatible([{"operator": "stream", "operand": "Denmark"}])) self.assertTrue(is_web_public_compatible([{"operator": "stream", "operand": "Denmark"}, {"operator": "topic", "operand": "logic"}])) self.assertFalse(is_web_public_compatible([{"operator": "is", "operand": "starred"}])) self.assertFalse(is_web_public_compatible([{"operator": "is", "operand": "private"}])) # Malformed input not allowed self.assertFalse(is_web_public_compatible([{"operator": "has"}])) class IncludeHistoryTest(ZulipTestCase): def test_ok_to_include_history(self) -> None: user_profile = self.example_user("hamlet") self.make_stream('public_stream', realm=user_profile.realm) # Negated stream searches should not include history. narrow = [ dict(operator='stream', operand='public_stream', negated=True), ] self.assertFalse(ok_to_include_history(narrow, user_profile)) # Definitely forbid seeing history on private streams. self.make_stream('private_stream', realm=user_profile.realm, invite_only=True) subscribed_user_profile = self.example_user("cordelia") self.subscribe(subscribed_user_profile, 'private_stream') narrow = [ dict(operator='stream', operand='private_stream'), ] self.assertFalse(ok_to_include_history(narrow, user_profile)) # Verify that with stream.history_public_to_subscribers, subscribed # users can access history. self.make_stream('private_stream_2', realm=user_profile.realm, invite_only=True, history_public_to_subscribers=True) subscribed_user_profile = self.example_user("cordelia") self.subscribe(subscribed_user_profile, 'private_stream_2') narrow = [ dict(operator='stream', operand='private_stream_2'), ] self.assertFalse(ok_to_include_history(narrow, user_profile)) self.assertTrue(ok_to_include_history(narrow, subscribed_user_profile)) # History doesn't apply to PMs. narrow = [ dict(operator='is', operand='private'), ] self.assertFalse(ok_to_include_history(narrow, user_profile)) # History doesn't apply to unread messages. narrow = [ dict(operator='is', operand='unread'), ] self.assertFalse(ok_to_include_history(narrow, user_profile)) # If we are looking for something like starred messages, there is # no point in searching historical messages. narrow = [ dict(operator='stream', operand='public_stream'), dict(operator='is', operand='starred'), ] self.assertFalse(ok_to_include_history(narrow, user_profile)) # simple True case narrow = [ dict(operator='stream', operand='public_stream'), ] self.assertTrue(ok_to_include_history(narrow, user_profile)) narrow = [ dict(operator='stream', operand='public_stream'), dict(operator='topic', operand='whatever'), dict(operator='search', operand='needle in haystack'), ] self.assertTrue(ok_to_include_history(narrow, user_profile)) # Tests for guest user guest_user_profile = self.example_user("polonius") # Using 'Cordelia' to compare between a guest and a normal user subscribed_user_profile = self.example_user("cordelia") # Guest user can't access public stream self.subscribe(subscribed_user_profile, 'public_stream_2') narrow = [ dict(operator='stream', operand='public_stream_2'), ] self.assertFalse(ok_to_include_history(narrow, guest_user_profile)) self.assertTrue(ok_to_include_history(narrow, subscribed_user_profile)) # Definitely, a guest user can't access the unsubscribed private stream self.subscribe(subscribed_user_profile, 'private_stream_3') narrow = [ dict(operator='stream', operand='private_stream_3'), ] self.assertFalse(ok_to_include_history(narrow, guest_user_profile)) self.assertTrue(ok_to_include_history(narrow, subscribed_user_profile)) # Guest user can access (history of) subscribed private streams self.subscribe(guest_user_profile, 'private_stream_4') self.subscribe(subscribed_user_profile, 'private_stream_4') narrow = [ dict(operator='stream', operand='private_stream_4'), ] self.assertTrue(ok_to_include_history(narrow, guest_user_profile)) self.assertTrue(ok_to_include_history(narrow, subscribed_user_profile)) class PostProcessTest(ZulipTestCase): def test_basics(self) -> None: def verify(in_ids: List[int], num_before: int, num_after: int, first_visible_message_id: int, anchor: int, anchored_to_left: bool, anchored_to_right: bool, out_ids: List[int], found_anchor: bool, found_oldest: bool, found_newest: bool, history_limited: bool) -> None: in_rows = [[row_id] for row_id in in_ids] out_rows = [[row_id] for row_id in out_ids] info = post_process_limited_query( rows=in_rows, num_before=num_before, num_after=num_after, anchor=anchor, anchored_to_left=anchored_to_left, anchored_to_right=anchored_to_right, first_visible_message_id=first_visible_message_id, ) self.assertEqual(info['rows'], out_rows) self.assertEqual(info['found_anchor'], found_anchor) self.assertEqual(info['found_newest'], found_newest) self.assertEqual(info['found_oldest'], found_oldest) self.assertEqual(info['history_limited'], history_limited) # typical 2-sided query, with a bunch of tests for different # values of first_visible_message_id. anchor = 10 verify( in_ids=[8, 9, anchor, 11, 12], num_before=2, num_after=2, first_visible_message_id=0, anchor=anchor, anchored_to_left=False, anchored_to_right=False, out_ids=[8, 9, 10, 11, 12], found_anchor=True, found_oldest=False, found_newest=False, history_limited=False, ) verify( in_ids=[8, 9, anchor, 11, 12], num_before=2, num_after=2, first_visible_message_id=8, anchor=anchor, anchored_to_left=False, anchored_to_right=False, out_ids=[8, 9, 10, 11, 12], found_anchor=True, found_oldest=False, found_newest=False, history_limited=False, ) verify( in_ids=[8, 9, anchor, 11, 12], num_before=2, num_after=2, first_visible_message_id=9, anchor=anchor, anchored_to_left=False, anchored_to_right=False, out_ids=[9, 10, 11, 12], found_anchor=True, found_oldest=True, found_newest=False, history_limited=True, ) verify( in_ids=[8, 9, anchor, 11, 12], num_before=2, num_after=2, first_visible_message_id=10, anchor=anchor, anchored_to_left=False, anchored_to_right=False, out_ids=[10, 11, 12], found_anchor=True, found_oldest=True, found_newest=False, history_limited=True, ) verify( in_ids=[8, 9, anchor, 11, 12], num_before=2, num_after=2, first_visible_message_id=11, anchor=anchor, anchored_to_left=False, anchored_to_right=False, out_ids=[11, 12], found_anchor=False, found_oldest=True, found_newest=False, history_limited=True, ) verify( in_ids=[8, 9, anchor, 11, 12], num_before=2, num_after=2, first_visible_message_id=12, anchor=anchor, anchored_to_left=False, anchored_to_right=False, out_ids=[12], found_anchor=False, found_oldest=True, found_newest=True, history_limited=True, ) verify( in_ids=[8, 9, anchor, 11, 12], num_before=2, num_after=2, first_visible_message_id=13, anchor=anchor, anchored_to_left=False, anchored_to_right=False, out_ids=[], found_anchor=False, found_oldest=True, found_newest=True, history_limited=True, ) # typical 2-sided query missing anchor and grabbing an extra row anchor = 10 verify( in_ids=[7, 9, 11, 13, 15], num_before=2, num_after=2, anchor=anchor, anchored_to_left=False, anchored_to_right=False, first_visible_message_id=0, out_ids=[7, 9, 11, 13], found_anchor=False, found_oldest=False, found_newest=False, history_limited=False, ) verify( in_ids=[7, 9, 11, 13, 15], num_before=2, num_after=2, first_visible_message_id=10, anchor=anchor, anchored_to_left=False, anchored_to_right=False, out_ids=[11, 13], found_anchor=False, found_oldest=True, found_newest=False, history_limited=True, ) verify( in_ids=[7, 9, 11, 13, 15], num_before=2, num_after=2, first_visible_message_id=9, anchor=anchor, anchored_to_left=False, anchored_to_right=False, out_ids=[9, 11, 13], found_anchor=False, found_oldest=True, found_newest=False, history_limited=True, ) # 2-sided query with old anchor anchor = 100 verify( in_ids=[50, anchor, 150, 200], num_before=2, num_after=2, first_visible_message_id=0, anchor=anchor, anchored_to_left=False, anchored_to_right=False, out_ids=[50, 100, 150, 200], found_anchor=True, found_oldest=True, found_newest=False, history_limited=False, ) verify( in_ids=[50, anchor, 150, 200], num_before=2, num_after=2, first_visible_message_id=anchor, anchor=anchor, anchored_to_left=False, anchored_to_right=False, out_ids=[100, 150, 200], found_anchor=True, found_oldest=True, found_newest=False, history_limited=True, ) # 2-sided query with new anchor anchor = 900 verify( in_ids=[700, 800, anchor, 1000], num_before=2, num_after=2, first_visible_message_id=0, anchor=anchor, anchored_to_left=False, anchored_to_right=False, out_ids=[700, 800, 900, 1000], found_anchor=True, found_oldest=False, found_newest=True, history_limited=False, ) verify( in_ids=[700, 800, anchor, 1000], num_before=2, num_after=2, first_visible_message_id=anchor, anchor=anchor, anchored_to_left=False, anchored_to_right=False, out_ids=[900, 1000], found_anchor=True, found_oldest=True, found_newest=True, history_limited=True, ) # left-sided query with old anchor anchor = 100 verify( in_ids=[50, anchor], num_before=2, num_after=0, first_visible_message_id=0, anchor=anchor, anchored_to_left=False, anchored_to_right=False, out_ids=[50, 100], found_anchor=True, found_oldest=True, found_newest=False, history_limited=False, ) verify( in_ids=[50, anchor], num_before=2, num_after=0, first_visible_message_id=anchor, anchor=anchor, anchored_to_left=False, anchored_to_right=False, out_ids=[100], found_anchor=True, found_oldest=True, found_newest=False, history_limited=True, ) # left-sided query with new anchor anchor = 900 verify( in_ids=[700, 800, anchor], num_before=2, num_after=0, first_visible_message_id=0, anchor=anchor, anchored_to_left=False, anchored_to_right=False, out_ids=[700, 800, 900], found_anchor=True, found_oldest=False, found_newest=False, history_limited=False, ) verify( in_ids=[700, 800, anchor], num_before=2, num_after=0, first_visible_message_id=anchor, anchor=anchor, anchored_to_left=False, anchored_to_right=False, out_ids=[900], found_anchor=True, found_oldest=True, found_newest=False, history_limited=True, ) # left-sided query with new anchor and extra row anchor = 900 verify( in_ids=[600, 700, 800, anchor], num_before=2, num_after=0, first_visible_message_id=0, anchor=anchor, anchored_to_left=False, anchored_to_right=False, out_ids=[700, 800, 900], found_anchor=True, found_oldest=False, found_newest=False, history_limited=False, ) verify( in_ids=[600, 700, 800, anchor], num_before=2, num_after=0, first_visible_message_id=anchor, anchor=anchor, anchored_to_left=False, anchored_to_right=False, out_ids=[900], found_anchor=True, found_oldest=True, found_newest=False, history_limited=True, ) # left-sided query anchored to the right anchor = None verify( in_ids=[900, 1000], num_before=2, num_after=0, first_visible_message_id=0, anchor=anchor, anchored_to_left=False, anchored_to_right=True, out_ids=[900, 1000], found_anchor=False, found_oldest=False, found_newest=True, history_limited=False, ) verify( in_ids=[900, 1000], num_before=2, num_after=0, first_visible_message_id=1000, anchor=anchor, anchored_to_left=False, anchored_to_right=True, out_ids=[1000], found_anchor=False, found_oldest=True, found_newest=True, history_limited=True, ) verify( in_ids=[900, 1000], num_before=2, num_after=0, first_visible_message_id=1100, anchor=anchor, anchored_to_left=False, anchored_to_right=True, out_ids=[], found_anchor=False, found_oldest=True, found_newest=True, history_limited=True, ) # right-sided query with old anchor anchor = 100 verify( in_ids=[anchor, 200, 300, 400], num_before=0, num_after=2, first_visible_message_id=0, anchor=anchor, anchored_to_left=False, anchored_to_right=False, out_ids=[100, 200, 300], found_anchor=True, found_oldest=False, found_newest=False, history_limited=False, ) verify( in_ids=[anchor, 200, 300, 400], num_before=0, num_after=2, first_visible_message_id=anchor, anchor=anchor, anchored_to_left=False, anchored_to_right=False, out_ids=[100, 200, 300], found_anchor=True, found_oldest=False, found_newest=False, history_limited=False, ) verify( in_ids=[anchor, 200, 300, 400], num_before=0, num_after=2, first_visible_message_id=300, anchor=anchor, anchored_to_left=False, anchored_to_right=False, out_ids=[300, 400], found_anchor=False, found_oldest=False, # BUG: history_limited should be False here. found_newest=False, history_limited=False, ) # right-sided query with new anchor anchor = 900 verify( in_ids=[anchor, 1000], num_before=0, num_after=2, first_visible_message_id=0, anchor=anchor, anchored_to_left=False, anchored_to_right=False, out_ids=[900, 1000], found_anchor=True, found_oldest=False, found_newest=True, history_limited=False, ) verify( in_ids=[anchor, 1000], num_before=0, num_after=2, first_visible_message_id=anchor, anchor=anchor, anchored_to_left=False, anchored_to_right=False, out_ids=[900, 1000], found_anchor=True, found_oldest=False, found_newest=True, history_limited=False, ) # right-sided query with non-matching anchor anchor = 903 verify( in_ids=[1000, 1100, 1200], num_before=0, num_after=2, first_visible_message_id=0, anchor=anchor, anchored_to_left=False, anchored_to_right=False, out_ids=[1000, 1100], found_anchor=False, found_oldest=False, found_newest=False, history_limited=False, ) verify( in_ids=[1000, 1100, 1200], num_before=0, num_after=2, first_visible_message_id=anchor, anchor=anchor, anchored_to_left=False, anchored_to_right=False, out_ids=[1000, 1100], found_anchor=False, found_oldest=False, found_newest=False, history_limited=False, ) verify( in_ids=[1000, 1100, 1200], num_before=0, num_after=2, first_visible_message_id=1000, anchor=anchor, anchored_to_left=False, anchored_to_right=False, out_ids=[1000, 1100], found_anchor=False, found_oldest=False, found_newest=False, history_limited=False, ) verify( in_ids=[1000, 1100, 1200], num_before=0, num_after=2, first_visible_message_id=1100, anchor=anchor, anchored_to_left=False, anchored_to_right=False, out_ids=[1100, 1200], found_anchor=False, found_oldest=False, # BUG: history_limited should be False here. found_newest=False, history_limited=False, ) # targeted query that finds row anchor = 1000 verify( in_ids=[1000], num_before=0, num_after=0, first_visible_message_id=0, anchor=anchor, anchored_to_left=False, anchored_to_right=False, out_ids=[1000], found_anchor=True, found_oldest=False, found_newest=False, history_limited=False ) verify( in_ids=[1000], num_before=0, num_after=0, first_visible_message_id=anchor, anchor=anchor, anchored_to_left=False, anchored_to_right=False, out_ids=[1000], found_anchor=True, found_oldest=False, found_newest=False, history_limited=False ) verify( in_ids=[1000], num_before=0, num_after=0, first_visible_message_id=1100, anchor=anchor, anchored_to_left=False, anchored_to_right=False, out_ids=[], found_anchor=False, found_oldest=False, found_newest=False, history_limited=False, ) # targeted query that finds nothing anchor = 903 verify( in_ids=[], num_before=0, num_after=0, first_visible_message_id=0, anchor=anchor, anchored_to_left=False, anchored_to_right=False, out_ids=[], found_anchor=False, found_oldest=False, found_newest=False, history_limited=False ) class GetOldMessagesTest(ZulipTestCase): def get_and_check_messages(self, modified_params: Dict[str, Union[str, int]], **kwargs: Any) -> Dict[str, Any]: post_params = {"anchor": 1, "num_before": 1, "num_after": 1} # type: Dict[str, Union[str, int]] post_params.update(modified_params) payload = self.client_get("/json/messages", dict(post_params), **kwargs) self.assert_json_success(payload) result = ujson.loads(payload.content) self.assertIn("messages", result) self.assertIsInstance(result["messages"], list) for message in result["messages"]: for field in ("content", "content_type", "display_recipient", "avatar_url", "recipient_id", "sender_full_name", "sender_short_name", "timestamp", "reactions"): self.assertIn(field, message) return result def message_visibility_test(self, narrow: List[Dict[str, str]], message_ids: List[int], pivot_index: int) -> None: num_before = len(message_ids) post_params = dict(narrow=ujson.dumps(narrow), num_before=num_before, num_after=0, anchor=LARGER_THAN_MAX_MESSAGE_ID) payload = self.client_get("/json/messages", dict(post_params)) self.assert_json_success(payload) result = ujson.loads(payload.content) self.assertEqual(len(result["messages"]), len(message_ids)) for message in result["messages"]: assert(message["id"] in message_ids) post_params.update({"num_before": len(message_ids[pivot_index:])}) with first_visible_id_as(message_ids[pivot_index]): payload = self.client_get("/json/messages", dict(post_params)) self.assert_json_success(payload) result = ujson.loads(payload.content) self.assertEqual(len(result["messages"]), len(message_ids[pivot_index:])) for message in result["messages"]: assert(message["id"] in message_ids) def get_query_ids(self) -> Dict[str, int]: hamlet_user = self.example_user('hamlet') othello_user = self.example_user('othello') query_ids = {} # type: Dict[str, int] scotland_stream = get_stream('Scotland', hamlet_user.realm) query_ids['scotland_recipient'] = get_stream_recipient(scotland_stream.id).id query_ids['hamlet_id'] = hamlet_user.id query_ids['othello_id'] = othello_user.id query_ids['hamlet_recipient'] = get_personal_recipient(hamlet_user.id).id query_ids['othello_recipient'] = get_personal_recipient(othello_user.id).id return query_ids def test_content_types(self) -> None: """ Test old `/json/messages` returns reactions. """ self.login(self.example_email("hamlet")) def get_content_type(apply_markdown: bool) -> str: req = dict( apply_markdown=ujson.dumps(apply_markdown), ) # type: Dict[str, Any] result = self.get_and_check_messages(req) message = result['messages'][0] return message['content_type'] self.assertEqual( get_content_type(apply_markdown=False), 'text/x-markdown', ) self.assertEqual( get_content_type(apply_markdown=True), 'text/html', ) def test_successful_get_messages_reaction(self) -> None: """ Test old `/json/messages` returns reactions. """ self.login(self.example_email("hamlet")) messages = self.get_and_check_messages(dict()) message_id = messages['messages'][0]['id'] self.login(self.example_email("othello")) reaction_name = 'thumbs_up' url = '/json/messages/{}/emoji_reactions/{}'.format(message_id, reaction_name) payload = self.client_put(url) self.assert_json_success(payload) self.login(self.example_email("hamlet")) messages = self.get_and_check_messages({}) message_to_assert = None for message in messages['messages']: if message['id'] == message_id: message_to_assert = message break assert(message_to_assert is not None) self.assertEqual(len(message_to_assert['reactions']), 1) self.assertEqual(message_to_assert['reactions'][0]['emoji_name'], reaction_name) def test_successful_get_messages(self) -> None: """ A call to GET /json/messages with valid parameters returns a list of messages. """ self.login(self.example_email("hamlet")) self.get_and_check_messages(dict()) # We have to support the legacy tuple style while there are old # clients around, which might include third party home-grown bots. self.get_and_check_messages(dict(narrow=ujson.dumps([['pm-with', self.example_email("othello")]]))) self.get_and_check_messages(dict(narrow=ujson.dumps([dict(operator='pm-with', operand=self.example_email("othello"))]))) def test_client_avatar(self) -> None: """ The client_gravatar flag determines whether we send avatar_url. """ hamlet = self.example_user('hamlet') self.login(hamlet.email) self.send_personal_message(hamlet.email, self.example_email("iago")) result = self.get_and_check_messages({}) message = result['messages'][0] self.assertIn('gravatar.com', message['avatar_url']) result = self.get_and_check_messages(dict(client_gravatar=ujson.dumps(True))) message = result['messages'][0] self.assertEqual(message['avatar_url'], None) def test_get_messages_with_narrow_pm_with(self) -> None: """ A request for old messages with a narrow by pm-with only returns conversations with that user. """ me = self.example_email('hamlet') def dr_emails(dr: Union[str, List[Dict[str, Any]]]) -> str: assert isinstance(dr, list) return ','.join(sorted(set([r['email'] for r in dr] + [me]))) self.send_personal_message(me, self.example_email("iago")) self.send_huddle_message( me, [self.example_email("iago"), self.example_email("cordelia")], ) personals = [m for m in get_user_messages(self.example_user('hamlet')) if not m.is_stream_message()] for personal in personals: emails = dr_emails(get_display_recipient(personal.recipient)) self.login(me) narrow = [dict(operator='pm-with', operand=emails)] result = self.get_and_check_messages(dict(narrow=ujson.dumps(narrow))) for message in result["messages"]: self.assertEqual(dr_emails(message['display_recipient']), emails) def test_get_visible_messages_with_narrow_pm_with(self) -> None: me = self.example_email('hamlet') self.login(me) self.subscribe(self.example_user("hamlet"), 'Scotland') message_ids = [] for i in range(5): message_ids.append(self.send_personal_message(me, self.example_email("iago"))) narrow = [dict(operator='pm-with', operand=self.example_email("iago"))] self.message_visibility_test(narrow, message_ids, 2) def test_get_messages_with_narrow_group_pm_with(self) -> None: """ A request for old messages with a narrow by group-pm-with only returns group-private conversations with that user. """ me = self.example_email("hamlet") matching_message_ids = [] matching_message_ids.append( self.send_huddle_message( me, [ self.example_email("iago"), self.example_email("cordelia"), self.example_email("othello"), ], ), ) matching_message_ids.append( self.send_huddle_message( me, [ self.example_email("cordelia"), self.example_email("othello"), ], ), ) non_matching_message_ids = [] non_matching_message_ids.append( self.send_personal_message(me, self.example_email("cordelia")), ) non_matching_message_ids.append( self.send_huddle_message( me, [ self.example_email("iago"), self.example_email("othello"), ], ), ) non_matching_message_ids.append( self.send_huddle_message( self.example_email("cordelia"), [ self.example_email("iago"), self.example_email("othello"), ], ), ) self.login(me) narrow = [dict(operator='group-pm-with', operand=self.example_email("cordelia"))] result = self.get_and_check_messages(dict(narrow=ujson.dumps(narrow))) for message in result["messages"]: self.assertIn(message["id"], matching_message_ids) self.assertNotIn(message["id"], non_matching_message_ids) def test_get_visible_messages_with_narrow_group_pm_with(self) -> None: me = self.example_email('hamlet') self.login(me) message_ids = [] message_ids.append( self.send_huddle_message( me, [ self.example_email("iago"), self.example_email("cordelia"), self.example_email("othello"), ], ), ) message_ids.append( self.send_huddle_message( me, [ self.example_email("cordelia"), self.example_email("othello"), ], ), ) message_ids.append( self.send_huddle_message( me, [ self.example_email("cordelia"), self.example_email("iago"), ], ), ) narrow = [dict(operator='group-pm-with', operand=self.example_email("cordelia"))] self.message_visibility_test(narrow, message_ids, 1) def test_include_history(self) -> None: hamlet = self.example_user('hamlet') cordelia = self.example_user('cordelia') stream_name = 'test stream' self.subscribe(cordelia, stream_name) old_message_id = self.send_stream_message(cordelia.email, stream_name, content='foo') self.subscribe(hamlet, stream_name) content = 'hello @**King Hamlet**' new_message_id = self.send_stream_message(cordelia.email, stream_name, content=content) self.login(hamlet.email) narrow = [ dict(operator='stream', operand=stream_name) ] req = dict( narrow=ujson.dumps(narrow), anchor=LARGER_THAN_MAX_MESSAGE_ID, num_before=100, num_after=100, ) payload = self.client_get('/json/messages', req) self.assert_json_success(payload) result = ujson.loads(payload.content) messages = result['messages'] self.assertEqual(len(messages), 2) for message in messages: if message['id'] == old_message_id: old_message = message elif message['id'] == new_message_id: new_message = message self.assertEqual(old_message['flags'], ['read', 'historical']) self.assertEqual(new_message['flags'], ['mentioned']) def test_get_messages_with_narrow_stream(self) -> None: """ A request for old messages with a narrow by stream only returns messages for that stream. """ self.login(self.example_email('hamlet')) # We need to subscribe to a stream and then send a message to # it to ensure that we actually have a stream message in this # narrow view. self.subscribe(self.example_user("hamlet"), 'Scotland') self.send_stream_message(self.example_email("hamlet"), "Scotland") messages = get_user_messages(self.example_user('hamlet')) stream_messages = [msg for msg in messages if msg.is_stream_message()] stream_name = get_display_recipient(stream_messages[0].recipient) stream_id = stream_messages[0].recipient.id narrow = [dict(operator='stream', operand=stream_name)] result = self.get_and_check_messages(dict(narrow=ujson.dumps(narrow))) for message in result["messages"]: self.assertEqual(message["type"], "stream") self.assertEqual(message["recipient_id"], stream_id) def test_get_visible_messages_with_narrow_stream(self) -> None: self.login(self.example_email('hamlet')) self.subscribe(self.example_user("hamlet"), 'Scotland') message_ids = [] for i in range(5): message_ids.append(self.send_stream_message(self.example_email("iago"), "Scotland")) narrow = [dict(operator='stream', operand="Scotland")] self.message_visibility_test(narrow, message_ids, 2) def test_get_messages_with_narrow_stream_mit_unicode_regex(self) -> None: """ A request for old messages for a user in the mit.edu relam with unicode stream name should be correctly escaped in the database query. """ self.login(self.mit_email("starnine"), realm=get_realm("zephyr")) # We need to susbcribe to a stream and then send a message to # it to ensure that we actually have a stream message in this # narrow view. lambda_stream_name = u"\u03bb-stream" stream = self.subscribe(self.mit_user("starnine"), lambda_stream_name) self.assertTrue(stream.is_in_zephyr_realm) lambda_stream_d_name = u"\u03bb-stream.d" self.subscribe(self.mit_user("starnine"), lambda_stream_d_name) self.send_stream_message(self.mit_email("starnine"), u"\u03bb-stream", sender_realm="zephyr") self.send_stream_message(self.mit_email("starnine"), u"\u03bb-stream.d", sender_realm="zephyr") narrow = [dict(operator='stream', operand=u'\u03bb-stream')] result = self.get_and_check_messages(dict(num_after=2, narrow=ujson.dumps(narrow)), subdomain="zephyr") messages = get_user_messages(self.mit_user("starnine")) stream_messages = [msg for msg in messages if msg.is_stream_message()] self.assertEqual(len(result["messages"]), 2) for i, message in enumerate(result["messages"]): self.assertEqual(message["type"], "stream") stream_id = stream_messages[i].recipient.id self.assertEqual(message["recipient_id"], stream_id) def test_get_messages_with_narrow_topic_mit_unicode_regex(self) -> None: """ A request for old messages for a user in the mit.edu realm with unicode topic name should be correctly escaped in the database query. """ mit_user_profile = self.mit_user("starnine") email = mit_user_profile.email self.login(email, realm=get_realm("zephyr")) # We need to susbcribe to a stream and then send a message to # it to ensure that we actually have a stream message in this # narrow view. self.subscribe(mit_user_profile, "Scotland") self.send_stream_message(email, "Scotland", topic_name=u"\u03bb-topic", sender_realm="zephyr") self.send_stream_message(email, "Scotland", topic_name=u"\u03bb-topic.d", sender_realm="zephyr") self.send_stream_message(email, "Scotland", topic_name=u"\u03bb-topic.d.d", sender_realm="zephyr") self.send_stream_message(email, "Scotland", topic_name=u"\u03bb-topic.d.d.d", sender_realm="zephyr") self.send_stream_message(email, "Scotland", topic_name=u"\u03bb-topic.d.d.d.d", sender_realm="zephyr") narrow = [dict(operator='topic', operand=u'\u03bb-topic')] result = self.get_and_check_messages( dict(num_after=100, narrow=ujson.dumps(narrow)), subdomain="zephyr") messages = get_user_messages(mit_user_profile) stream_messages = [msg for msg in messages if msg.is_stream_message()] self.assertEqual(len(result["messages"]), 5) for i, message in enumerate(result["messages"]): self.assertEqual(message["type"], "stream") stream_id = stream_messages[i].recipient.id self.assertEqual(message["recipient_id"], stream_id) def test_get_messages_with_narrow_topic_mit_personal(self) -> None: """ We handle .d grouping for MIT realm personal messages correctly. """ mit_user_profile = self.mit_user("starnine") email = mit_user_profile.email # We need to susbcribe to a stream and then send a message to # it to ensure that we actually have a stream message in this # narrow view. self.login(email, realm=mit_user_profile.realm) self.subscribe(mit_user_profile, "Scotland") self.send_stream_message(email, "Scotland", topic_name=u".d.d", sender_realm="zephyr") self.send_stream_message(email, "Scotland", topic_name=u"PERSONAL", sender_realm="zephyr") self.send_stream_message(email, "Scotland", topic_name=u'(instance "").d', sender_realm="zephyr") self.send_stream_message(email, "Scotland", topic_name=u".d.d.d", sender_realm="zephyr") self.send_stream_message(email, "Scotland", topic_name=u"personal.d", sender_realm="zephyr") self.send_stream_message(email, "Scotland", topic_name=u'(instance "")', sender_realm="zephyr") self.send_stream_message(email, "Scotland", topic_name=u".d.d.d.d", sender_realm="zephyr") narrow = [dict(operator='topic', operand=u'personal.d.d')] result = self.get_and_check_messages( dict(num_before=50, num_after=50, narrow=ujson.dumps(narrow)), subdomain="zephyr") messages = get_user_messages(mit_user_profile) stream_messages = [msg for msg in messages if msg.is_stream_message()] self.assertEqual(len(result["messages"]), 7) for i, message in enumerate(result["messages"]): self.assertEqual(message["type"], "stream") stream_id = stream_messages[i].recipient.id self.assertEqual(message["recipient_id"], stream_id) def test_get_messages_with_narrow_sender(self) -> None: """ A request for old messages with a narrow by sender only returns messages sent by that person. """ self.login(self.example_email("hamlet")) # We need to send a message here to ensure that we actually # have a stream message in this narrow view. self.send_stream_message(self.example_email("hamlet"), "Scotland") self.send_stream_message(self.example_email("othello"), "Scotland") self.send_personal_message(self.example_email("othello"), self.example_email("hamlet")) self.send_stream_message(self.example_email("iago"), "Scotland") narrow = [dict(operator='sender', operand=self.example_email("othello"))] result = self.get_and_check_messages(dict(narrow=ujson.dumps(narrow))) for message in result["messages"]: self.assertEqual(message["sender_email"], self.example_email("othello")) def _update_tsvector_index(self) -> None: # We use brute force here and update our text search index # for the entire zerver_message table (which is small in test # mode). In production there is an async process which keeps # the search index up to date. with connection.cursor() as cursor: cursor.execute(""" UPDATE zerver_message SET search_tsvector = to_tsvector('zulip.english_us_search', subject || rendered_content) """) @override_settings(USING_PGROONGA=False) def test_messages_in_narrow(self) -> None: email = self.example_email("cordelia") self.login(email) def send(content: str) -> int: msg_id = self.send_stream_message( sender_email=email, stream_name="Verona", content=content, ) return msg_id good_id = send('KEYWORDMATCH and should work') bad_id = send('no match') msg_ids = [good_id, bad_id] send('KEYWORDMATCH but not in msg_ids') self._update_tsvector_index() narrow = [ dict(operator='search', operand='KEYWORDMATCH'), ] raw_params = dict(msg_ids=msg_ids, narrow=narrow) params = {k: ujson.dumps(v) for k, v in raw_params.items()} result = self.client_get('/json/messages/matches_narrow', params) self.assert_json_success(result) messages = result.json()['messages'] self.assertEqual(len(list(messages.keys())), 1) message = messages[str(good_id)] self.assertEqual(message['match_content'], u'<p><span class="highlight">KEYWORDMATCH</span> and should work</p>') @override_settings(USING_PGROONGA=False) def test_get_messages_with_search(self) -> None: self.login(self.example_email("cordelia")) messages_to_search = [ ('breakfast', 'there are muffins in the conference room'), ('lunch plans', 'I am hungry!'), ('meetings', 'discuss lunch after lunch'), ('meetings', 'please bring your laptops to take notes'), ('dinner', 'Anybody staying late tonight?'), ('urltest', 'https://google.com'), (u'日本', u'こんに ちは 。 今日は いい 天気ですね。'), (u'日本', u'今朝はごはんを食べました。'), (u'日本', u'昨日、日本 のお菓子を送りました。'), ('english', u'I want to go to 日本!'), ] next_message_id = self.get_last_message().id + 1 for topic, content in messages_to_search: self.send_stream_message( sender_email=self.example_email("cordelia"), stream_name="Verona", content=content, topic_name=topic, ) self._update_tsvector_index() narrow = [ dict(operator='sender', operand=self.example_email("cordelia")), dict(operator='search', operand='lunch'), ] result = self.get_and_check_messages(dict( narrow=ujson.dumps(narrow), anchor=next_message_id, num_before=0, num_after=10, )) # type: Dict[str, Any] self.assertEqual(len(result['messages']), 2) messages = result['messages'] narrow = [dict(operator='search', operand='https://google.com')] link_search_result = self.get_and_check_messages(dict( narrow=ujson.dumps(narrow), anchor=next_message_id, num_before=0, num_after=10, )) # type: Dict[str, Any] self.assertEqual(len(link_search_result['messages']), 1) self.assertEqual(link_search_result['messages'][0]['match_content'], '<p><a href="https://google.com" target="_blank" title="https://google.com">https://<span class="highlight">google.com</span></a></p>') meeting_message = [m for m in messages if m[TOPIC_NAME] == 'meetings'][0] self.assertEqual( meeting_message[MATCH_TOPIC], 'meetings') self.assertEqual( meeting_message['match_content'], '<p>discuss <span class="highlight">lunch</span> after ' + '<span class="highlight">lunch</span></p>') meeting_message = [m for m in messages if m[TOPIC_NAME] == 'lunch plans'][0] self.assertEqual( meeting_message[MATCH_TOPIC], '<span class="highlight">lunch</span> plans') self.assertEqual( meeting_message['match_content'], '<p>I am hungry!</p>') # Should not crash when multiple search operands are present multi_search_narrow = [ dict(operator='search', operand='discuss'), dict(operator='search', operand='after'), ] multi_search_result = self.get_and_check_messages(dict( narrow=ujson.dumps(multi_search_narrow), anchor=next_message_id, num_after=10, num_before=0, )) # type: Dict[str, Any] self.assertEqual(len(multi_search_result['messages']), 1) self.assertEqual(multi_search_result['messages'][0]['match_content'], '<p><span class="highlight">discuss</span> lunch <span class="highlight">after</span> lunch</p>') # Test searching in messages with unicode characters narrow = [ dict(operator='search', operand=u'日本'), ] result = self.get_and_check_messages(dict( narrow=ujson.dumps(narrow), anchor=next_message_id, num_after=10, num_before=0, )) self.assertEqual(len(result['messages']), 4) messages = result['messages'] japanese_message = [m for m in messages if m[TOPIC_NAME] == u'日本'][-1] self.assertEqual( japanese_message[MATCH_TOPIC], u'<span class="highlight">日本</span>') self.assertEqual( japanese_message['match_content'], u'<p>昨日、<span class="highlight">日本</span>' + u' のお菓子を送りました。</p>') english_message = [m for m in messages if m[TOPIC_NAME] == 'english'][0] self.assertEqual( english_message[MATCH_TOPIC], 'english') self.assertIn( english_message['match_content'], u'<p>I want to go to <span class="highlight">日本</span>!</p>') # Multiple search operands with unicode multi_search_narrow = [ dict(operator='search', operand='ちは'), dict(operator='search', operand='今日は'), ] multi_search_result = self.get_and_check_messages(dict( narrow=ujson.dumps(multi_search_narrow), anchor=next_message_id, num_after=10, num_before=0, )) self.assertEqual(len(multi_search_result['messages']), 1) self.assertEqual(multi_search_result['messages'][0]['match_content'], '<p>こんに <span class="highlight">ちは</span> 。 <span class="highlight">今日は</span> いい 天気ですね。</p>') @override_settings(USING_PGROONGA=False) def test_get_visible_messages_with_search(self) -> None: self.login(self.example_email('hamlet')) self.subscribe(self.example_user("hamlet"), 'Scotland') messages_to_search = [ ("Gryffindor", "Hogwart's house which values courage, bravery, nerve, and chivalry"), ("Hufflepuff", "Hogwart's house which values hard work, patience, justice, and loyalty."), ("Ravenclaw", "Hogwart's house which values intelligence, creativity, learning, and wit"), ("Slytherin", "Hogwart's house which values ambition, cunning, leadership, and resourcefulness"), ] message_ids = [] for topic, content in messages_to_search: message_ids.append(self.send_stream_message(self.example_email("iago"), "Scotland", topic_name=topic, content=content)) self._update_tsvector_index() narrow = [dict(operator='search', operand="Hogwart's")] self.message_visibility_test(narrow, message_ids, 2) @override_settings(USING_PGROONGA=False) def test_get_messages_with_search_not_subscribed(self) -> None: """Verify support for searching a stream you're not subscribed to""" self.subscribe(self.example_user("hamlet"), "newstream") self.send_stream_message( sender_email=self.example_email("hamlet"), stream_name="newstream", content="Public special content!", topic_name="new", ) self._update_tsvector_index() self.login(self.example_email("cordelia")) stream_search_narrow = [ dict(operator='search', operand='special'), dict(operator='stream', operand='newstream'), ] stream_search_result = self.get_and_check_messages(dict( narrow=ujson.dumps(stream_search_narrow), anchor=0, num_after=10, num_before=10, )) # type: Dict[str, Any] self.assertEqual(len(stream_search_result['messages']), 1) self.assertEqual(stream_search_result['messages'][0]['match_content'], '<p>Public <span class="highlight">special</span> content!</p>') @override_settings(USING_PGROONGA=True) def test_get_messages_with_search_pgroonga(self) -> None: self.login(self.example_email("cordelia")) next_message_id = self.get_last_message().id + 1 messages_to_search = [ (u'日本語', u'こんにちは。今日はいい天気ですね。'), (u'日本語', u'今朝はごはんを食べました。'), (u'日本語', u'昨日、日本のお菓子を送りました。'), ('english', u'I want to go to 日本!'), ('english', 'Can you speak https://en.wikipedia.org/wiki/Japanese?'), ('english', 'https://google.com'), ('bread & butter', 'chalk & cheese'), ] for topic, content in messages_to_search: self.send_stream_message( sender_email=self.example_email("cordelia"), stream_name="Verona", content=content, topic_name=topic, ) # We use brute force here and update our text search index # for the entire zerver_message table (which is small in test # mode). In production there is an async process which keeps # the search index up to date. with connection.cursor() as cursor: cursor.execute(""" UPDATE zerver_message SET search_pgroonga = escape_html(subject) || ' ' || rendered_content """) narrow = [ dict(operator='search', operand=u'日本'), ] result = self.get_and_check_messages(dict( narrow=ujson.dumps(narrow), anchor=next_message_id, num_after=10, num_before=0, )) # type: Dict[str, Any] self.assertEqual(len(result['messages']), 4) messages = result['messages'] japanese_message = [m for m in messages if m[TOPIC_NAME] == u'日本語'][-1] self.assertEqual( japanese_message[MATCH_TOPIC], u'<span class="highlight">日本</span>語') self.assertEqual( japanese_message['match_content'], u'<p>昨日、<span class="highlight">日本</span>の' + u'お菓子を送りました。</p>') english_message = [m for m in messages if m[TOPIC_NAME] == 'english'][0] self.assertEqual( english_message[MATCH_TOPIC], 'english') self.assertIn( english_message['match_content'], # NOTE: The whitespace here is off due to a pgroonga bug. # This bug is a pgroonga regression and according to one of # the author, this should be fixed in its next release. [u'<p>I want to go to <span class="highlight">日本</span>!</p>', # This is correct. u'<p>I want to go to<span class="highlight"> 日本</span>!</p>', ]) # Should not crash when multiple search operands are present multi_search_narrow = [ dict(operator='search', operand='can'), dict(operator='search', operand='speak'), dict(operator='search', operand='wiki'), ] multi_search_result = self.get_and_check_messages(dict( narrow=ujson.dumps(multi_search_narrow), anchor=next_message_id, num_after=10, num_before=0, )) # type: Dict[str, Any] self.assertEqual(len(multi_search_result['messages']), 1) self.assertEqual(multi_search_result['messages'][0]['match_content'], '<p><span class="highlight">Can</span> you <span class="highlight">speak</span> <a href="https://en.wikipedia.org/wiki/Japanese" target="_blank" title="https://en.wikipedia.org/wiki/Japanese">https://en.<span class="highlight">wiki</span>pedia.org/<span class="highlight">wiki</span>/Japanese</a>?</p>') # Multiple search operands with unicode multi_search_narrow = [ dict(operator='search', operand='朝は'), dict(operator='search', operand='べました'), ] multi_search_result = self.get_and_check_messages(dict( narrow=ujson.dumps(multi_search_narrow), anchor=next_message_id, num_after=10, num_before=0, )) self.assertEqual(len(multi_search_result['messages']), 1) self.assertEqual(multi_search_result['messages'][0]['match_content'], '<p>今<span class="highlight">朝は</span>ごはんを食<span class="highlight">べました</span>。</p>') narrow = [dict(operator='search', operand='https://google.com')] link_search_result = self.get_and_check_messages(dict( narrow=ujson.dumps(narrow), anchor=next_message_id, num_after=10, num_before=0, )) # type: Dict[str, Any] self.assertEqual(len(link_search_result['messages']), 1) self.assertEqual(link_search_result['messages'][0]['match_content'], '<p><a href="https://google.com" target="_blank" title="https://google.com"><span class="highlight">https://google.com</span></a></p>') # Search operands with HTML Special Characters special_search_narrow = [ dict(operator='search', operand='butter'), ] special_search_result = self.get_and_check_messages(dict( narrow=ujson.dumps(special_search_narrow), anchor=next_message_id, num_after=10, num_before=0, )) # type: Dict[str, Any] self.assertEqual(len(special_search_result['messages']), 1) self.assertEqual(special_search_result['messages'][0][MATCH_TOPIC], 'bread &amp; <span class="highlight">butter</span>') special_search_narrow = [ dict(operator='search', operand='&'), ] special_search_result = self.get_and_check_messages(dict( narrow=ujson.dumps(special_search_narrow), anchor=next_message_id, num_after=10, num_before=0, )) self.assertEqual(len(special_search_result['messages']), 1) self.assertEqual(special_search_result['messages'][0][MATCH_TOPIC], 'bread <span class="highlight">&amp;</span> butter') self.assertEqual(special_search_result['messages'][0]['match_content'], '<p>chalk <span class="highlight">&amp;</span> cheese</p>') def test_messages_in_narrow_for_non_search(self) -> None: email = self.example_email("cordelia") self.login(email) def send(content: str) -> int: msg_id = self.send_stream_message( sender_email=email, stream_name="Verona", topic_name='test_topic', content=content, ) return msg_id good_id = send('http://foo.com') bad_id = send('no link here') msg_ids = [good_id, bad_id] send('http://bar.com but not in msg_ids') narrow = [ dict(operator='has', operand='link'), ] raw_params = dict(msg_ids=msg_ids, narrow=narrow) params = {k: ujson.dumps(v) for k, v in raw_params.items()} result = self.client_get('/json/messages/matches_narrow', params) self.assert_json_success(result) messages = result.json()['messages'] self.assertEqual(len(list(messages.keys())), 1) message = messages[str(good_id)] self.assertIn('a href=', message['match_content']) self.assertIn('http://foo.com', message['match_content']) self.assertEqual(message[MATCH_TOPIC], 'test_topic') def test_get_messages_with_only_searching_anchor(self) -> None: """ Test that specifying an anchor but 0 for num_before and num_after returns at most 1 message. """ self.login(self.example_email("cordelia")) anchor = self.send_stream_message(self.example_email("cordelia"), "Verona") narrow = [dict(operator='sender', operand=self.example_email("cordelia"))] result = self.get_and_check_messages(dict(narrow=ujson.dumps(narrow), anchor=anchor, num_before=0, num_after=0)) # type: Dict[str, Any] self.assertEqual(len(result['messages']), 1) narrow = [dict(operator='is', operand='mentioned')] result = self.get_and_check_messages(dict(narrow=ujson.dumps(narrow), anchor=anchor, num_before=0, num_after=0)) self.assertEqual(len(result['messages']), 0) def test_get_visible_messages_with_anchor(self) -> None: def messages_matches_ids(messages: List[Dict[str, Any]], message_ids: List[int]) -> None: self.assertEqual(len(messages), len(message_ids)) for message in messages: assert(message["id"] in message_ids) self.login(self.example_email("hamlet")) Message.objects.all().delete() message_ids = [] for i in range(10): message_ids.append(self.send_stream_message(self.example_email("cordelia"), "Verona")) data = self.get_messages_response(anchor=message_ids[9], num_before=9, num_after=0) messages = data['messages'] self.assertEqual(data['found_anchor'], True) self.assertEqual(data['found_oldest'], False) self.assertEqual(data['found_newest'], False) self.assertEqual(data['history_limited'], False) messages_matches_ids(messages, message_ids) with first_visible_id_as(message_ids[5]): data = self.get_messages_response(anchor=message_ids[9], num_before=9, num_after=0) messages = data['messages'] self.assertEqual(data['found_anchor'], True) self.assertEqual(data['found_oldest'], True) self.assertEqual(data['found_newest'], False) self.assertEqual(data['history_limited'], True) messages_matches_ids(messages, message_ids[5:]) with first_visible_id_as(message_ids[2]): data = self.get_messages_response(anchor=message_ids[6], num_before=9, num_after=0) messages = data['messages'] self.assertEqual(data['found_anchor'], True) self.assertEqual(data['found_oldest'], True) self.assertEqual(data['found_newest'], False) self.assertEqual(data['history_limited'], True) messages_matches_ids(messages, message_ids[2:7]) with first_visible_id_as(message_ids[9] + 1): data = self.get_messages_response(anchor=message_ids[9], num_before=9, num_after=0) messages = data['messages'] self.assert_length(messages, 0) self.assertEqual(data['found_anchor'], False) self.assertEqual(data['found_oldest'], True) self.assertEqual(data['found_newest'], False) self.assertEqual(data['history_limited'], True) data = self.get_messages_response(anchor=message_ids[5], num_before=0, num_after=5) messages = data['messages'] self.assertEqual(data['found_anchor'], True) self.assertEqual(data['found_oldest'], False) self.assertEqual(data['found_newest'], True) self.assertEqual(data['history_limited'], False) messages_matches_ids(messages, message_ids[5:]) with first_visible_id_as(message_ids[7]): data = self.get_messages_response(anchor=message_ids[5], num_before=0, num_after=5) messages = data['messages'] self.assertEqual(data['found_anchor'], False) self.assertEqual(data['found_oldest'], False) self.assertEqual(data['found_newest'], True) self.assertEqual(data['history_limited'], False) messages_matches_ids(messages, message_ids[7:]) with first_visible_id_as(message_ids[2]): data = self.get_messages_response(anchor=message_ids[0], num_before=0, num_after=5) messages = data['messages'] self.assertEqual(data['found_anchor'], False) self.assertEqual(data['found_oldest'], False) self.assertEqual(data['found_newest'], False) self.assertEqual(data['history_limited'], False) messages_matches_ids(messages, message_ids[2:7]) with first_visible_id_as(message_ids[9] + 1): data = self.get_messages_response(anchor=message_ids[0], num_before=0, num_after=5) messages = data['messages'] self.assertEqual(data['found_anchor'], False) self.assertEqual(data['found_oldest'], False) self.assertEqual(data['found_newest'], True) self.assertEqual(data['history_limited'], False) self.assert_length(messages, 0) data = self.get_messages_response(anchor=message_ids[5], num_before=5, num_after=4) messages = data['messages'] self.assertEqual(data['found_anchor'], True) self.assertEqual(data['found_oldest'], False) self.assertEqual(data['found_newest'], False) self.assertEqual(data['history_limited'], False) messages_matches_ids(messages, message_ids) data = self.get_messages_response(anchor=message_ids[5], num_before=10, num_after=10) messages = data['messages'] self.assertEqual(data['found_anchor'], True) self.assertEqual(data['found_oldest'], True) self.assertEqual(data['found_newest'], True) self.assertEqual(data['history_limited'], False) messages_matches_ids(messages, message_ids) with first_visible_id_as(message_ids[5]): data = self.get_messages_response(anchor=message_ids[5], num_before=5, num_after=4) messages = data['messages'] self.assertEqual(data['found_anchor'], True) self.assertEqual(data['found_oldest'], True) self.assertEqual(data['found_newest'], False) self.assertEqual(data['history_limited'], True) messages_matches_ids(messages, message_ids[5:]) with first_visible_id_as(message_ids[5]): data = self.get_messages_response(anchor=message_ids[2], num_before=5, num_after=3) messages = data['messages'] self.assertEqual(data['found_anchor'], False) self.assertEqual(data['found_oldest'], True) self.assertEqual(data['found_newest'], False) self.assertEqual(data['history_limited'], True) messages_matches_ids(messages, message_ids[5:8]) with first_visible_id_as(message_ids[5]): data = self.get_messages_response(anchor=message_ids[2], num_before=10, num_after=10) messages = data['messages'] self.assertEqual(data['found_anchor'], False) self.assertEqual(data['found_oldest'], True) self.assertEqual(data['found_newest'], True) messages_matches_ids(messages, message_ids[5:]) with first_visible_id_as(message_ids[9] + 1): data = self.get_messages_response(anchor=message_ids[5], num_before=5, num_after=4) messages = data['messages'] self.assertEqual(data['found_anchor'], False) self.assertEqual(data['found_oldest'], True) self.assertEqual(data['found_newest'], True) self.assertEqual(data['history_limited'], True) self.assert_length(messages, 0) with first_visible_id_as(message_ids[5]): data = self.get_messages_response(anchor=message_ids[5], num_before=0, num_after=0) messages = data['messages'] self.assertEqual(data['found_anchor'], True) self.assertEqual(data['found_oldest'], False) self.assertEqual(data['found_newest'], False) self.assertEqual(data['history_limited'], False) messages_matches_ids(messages, message_ids[5:6]) with first_visible_id_as(message_ids[5]): data = self.get_messages_response(anchor=message_ids[2], num_before=0, num_after=0) messages = data['messages'] self.assertEqual(data['found_anchor'], False) self.assertEqual(data['found_oldest'], False) self.assertEqual(data['found_newest'], False) self.assertEqual(data['history_limited'], False) self.assert_length(messages, 0) def test_missing_params(self) -> None: """ anchor, num_before, and num_after are all required POST parameters for get_messages. """ self.login(self.example_email("hamlet")) required_args = (("num_before", 1), ("num_after", 1)) # type: Tuple[Tuple[str, int], ...] for i in range(len(required_args)): post_params = dict(required_args[:i] + required_args[i + 1:]) result = self.client_get("/json/messages", post_params) self.assert_json_error(result, "Missing '%s' argument" % (required_args[i][0],)) def test_get_messages_limits(self) -> None: """ A call to GET /json/messages requesting more than MAX_MESSAGES_PER_FETCH messages returns an error message. """ self.login(self.example_email("hamlet")) result = self.client_get("/json/messages", dict(anchor=1, num_before=3000, num_after=3000)) self.assert_json_error(result, "Too many messages requested (maximum 5000).") result = self.client_get("/json/messages", dict(anchor=1, num_before=6000, num_after=0)) self.assert_json_error(result, "Too many messages requested (maximum 5000).") result = self.client_get("/json/messages", dict(anchor=1, num_before=0, num_after=6000)) self.assert_json_error(result, "Too many messages requested (maximum 5000).") def test_bad_int_params(self) -> None: """ num_before, num_after, and narrow must all be non-negative integers or strings that can be converted to non-negative integers. """ self.login(self.example_email("hamlet")) other_params = [("narrow", {}), ("anchor", 0)] int_params = ["num_before", "num_after"] bad_types = (False, "", "-1", -1) for idx, param in enumerate(int_params): for type in bad_types: # Rotate through every bad type for every integer # parameter, one at a time. post_params = dict(other_params + [(param, type)] + [(other_param, 0) for other_param in int_params[:idx] + int_params[idx + 1:]] ) result = self.client_get("/json/messages", post_params) self.assert_json_error(result, "Bad value for '%s': %s" % (param, type)) def test_bad_narrow_type(self) -> None: """ narrow must be a list of string pairs. """ self.login(self.example_email("hamlet")) other_params = [("anchor", 0), ("num_before", 0), ("num_after", 0)] # type: List[Tuple[str, Union[int, str, bool]]] bad_types = (False, 0, '', '{malformed json,', '{foo: 3}', '[1,2]', '[["x","y","z"]]') # type: Tuple[Union[int, str, bool], ...] for type in bad_types: post_params = dict(other_params + [("narrow", type)]) result = self.client_get("/json/messages", post_params) self.assert_json_error(result, "Bad value for 'narrow': %s" % (type,)) def test_bad_narrow_operator(self) -> None: """ Unrecognized narrow operators are rejected. """ self.login(self.example_email("hamlet")) for operator in ['', 'foo', 'stream:verona', '__init__']: narrow = [dict(operator=operator, operand='')] params = dict(anchor=0, num_before=0, num_after=0, narrow=ujson.dumps(narrow)) result = self.client_get("/json/messages", params) self.assert_json_error_contains(result, "Invalid narrow operator: unknown operator") def test_non_string_narrow_operand_in_dict(self) -> None: """ We expect search operands to be strings, not integers. """ self.login(self.example_email("hamlet")) not_a_string = 42 narrow = [dict(operator='stream', operand=not_a_string)] params = dict(anchor=0, num_before=0, num_after=0, narrow=ujson.dumps(narrow)) result = self.client_get("/json/messages", params) self.assert_json_error_contains(result, 'elem["operand"] is not a string') def exercise_bad_narrow_operand(self, operator: str, operands: Sequence[Any], error_msg: str) -> None: other_params = [("anchor", 0), ("num_before", 0), ("num_after", 0)] # type: List[Tuple[str, Any]] for operand in operands: post_params = dict(other_params + [ ("narrow", ujson.dumps([[operator, operand]]))]) result = self.client_get("/json/messages", post_params) self.assert_json_error_contains(result, error_msg) def test_bad_narrow_stream_content(self) -> None: """ If an invalid stream name is requested in get_messages, an error is returned. """ self.login(self.example_email("hamlet")) bad_stream_content = (0, [], ["x", "y"]) # type: Tuple[int, List[None], List[str]] self.exercise_bad_narrow_operand("stream", bad_stream_content, "Bad value for 'narrow'") def test_bad_narrow_one_on_one_email_content(self) -> None: """ If an invalid 'pm-with' is requested in get_messages, an error is returned. """ self.login(self.example_email("hamlet")) bad_stream_content = (0, [], ["x", "y"]) # type: Tuple[int, List[None], List[str]] self.exercise_bad_narrow_operand("pm-with", bad_stream_content, "Bad value for 'narrow'") def test_bad_narrow_nonexistent_stream(self) -> None: self.login(self.example_email("hamlet")) self.exercise_bad_narrow_operand("stream", ['non-existent stream'], "Invalid narrow operator: unknown stream") def test_bad_narrow_nonexistent_email(self) -> None: self.login(self.example_email("hamlet")) self.exercise_bad_narrow_operand("pm-with", ['non-existent-user@zulip.com'], "Invalid narrow operator: unknown user") def test_message_without_rendered_content(self) -> None: """Older messages may not have rendered_content in the database""" m = self.get_last_message() m.rendered_content = m.rendered_content_version = None m.content = 'test content' d = MessageDict.wide_dict(m) MessageDict.finalize_payload(d, apply_markdown=True, client_gravatar=False) self.assertEqual(d['content'], '<p>test content</p>') def common_check_get_messages_query(self, query_params: Dict[str, object], expected: str) -> None: user_profile = self.example_user('hamlet') request = POSTRequestMock(query_params, user_profile) with queries_captured() as queries: get_messages_backend(request, user_profile) for query in queries: if "/* get_messages */" in query['sql']: sql = str(query['sql']).replace(" /* get_messages */", '') self.assertEqual(sql, expected) return raise AssertionError("get_messages query not found") def test_find_first_unread_anchor(self) -> None: hamlet = self.example_user('hamlet') cordelia = self.example_user('cordelia') othello = self.example_user('othello') self.make_stream('England') # Send a few messages that Hamlet won't have UserMessage rows for. unsub_message_id = self.send_stream_message(cordelia.email, 'England') self.send_personal_message(cordelia.email, othello.email) self.subscribe(hamlet, 'England') muted_topics = [ ['England', 'muted'], ] set_topic_mutes(hamlet, muted_topics) # send a muted message muted_message_id = self.send_stream_message(cordelia.email, 'England', topic_name='muted') # finally send Hamlet a "normal" message first_message_id = self.send_stream_message(cordelia.email, 'England') # send a few more messages extra_message_id = self.send_stream_message(cordelia.email, 'England') self.send_personal_message(cordelia.email, hamlet.email) sa_conn = get_sqlalchemy_connection() user_profile = hamlet anchor = find_first_unread_anchor( sa_conn=sa_conn, user_profile=user_profile, narrow=[], ) self.assertEqual(anchor, first_message_id) # With the same data setup, we now want to test that a reasonable # search still gets the first message sent to Hamlet (before he # subscribed) and other recent messages to the stream. query_params = dict( use_first_unread_anchor='true', anchor=0, num_before=10, num_after=10, narrow='[["stream", "England"]]' ) request = POSTRequestMock(query_params, user_profile) payload = get_messages_backend(request, user_profile) result = ujson.loads(payload.content) self.assertEqual(result['anchor'], first_message_id) self.assertEqual(result['found_newest'], True) self.assertEqual(result['found_oldest'], True) messages = result['messages'] self.assertEqual( {msg['id'] for msg in messages}, {unsub_message_id, muted_message_id, first_message_id, extra_message_id} ) def test_use_first_unread_anchor_with_some_unread_messages(self) -> None: user_profile = self.example_user('hamlet') # Have Othello send messages to Hamlet that he hasn't read. # Here, Hamlet isn't subscribed to the stream Scotland self.send_stream_message(self.example_email("othello"), "Scotland") first_unread_message_id = self.send_personal_message( self.example_email("othello"), self.example_email("hamlet"), ) # Add a few messages that help us test that our query doesn't # look at messages that are irrelevant to Hamlet. self.send_personal_message(self.example_email("othello"), self.example_email("cordelia")) self.send_personal_message(self.example_email("othello"), self.example_email("iago")) query_params = dict( use_first_unread_anchor='true', anchor=0, num_before=10, num_after=10, narrow='[]' ) request = POSTRequestMock(query_params, user_profile) with queries_captured() as all_queries: get_messages_backend(request, user_profile) # Verify the query for old messages looks correct. queries = [q for q in all_queries if '/* get_messages */' in q['sql']] self.assertEqual(len(queries), 1) sql = queries[0]['sql'] self.assertNotIn('AND message_id = %s' % (LARGER_THAN_MAX_MESSAGE_ID,), sql) self.assertIn('ORDER BY message_id ASC', sql) cond = 'WHERE user_profile_id = %d AND message_id >= %d' % ( user_profile.id, first_unread_message_id, ) self.assertIn(cond, sql) cond = 'WHERE user_profile_id = %d AND message_id <= %d' % ( user_profile.id, first_unread_message_id - 1, ) self.assertIn(cond, sql) self.assertIn('UNION', sql) def test_visible_messages_use_first_unread_anchor_with_some_unread_messages(self) -> None: user_profile = self.example_user('hamlet') # Have Othello send messages to Hamlet that he hasn't read. self.subscribe(self.example_user("hamlet"), 'Scotland') first_unread_message_id = self.send_stream_message(self.example_email("othello"), "Scotland") self.send_stream_message(self.example_email("othello"), "Scotland") self.send_stream_message(self.example_email("othello"), "Scotland") self.send_personal_message( self.example_email("othello"), self.example_email("hamlet"), ) # Add a few messages that help us test that our query doesn't # look at messages that are irrelevant to Hamlet. self.send_personal_message(self.example_email("othello"), self.example_email("cordelia")) self.send_personal_message(self.example_email("othello"), self.example_email("iago")) query_params = dict( use_first_unread_anchor='true', anchor=0, num_before=10, num_after=10, narrow='[]' ) request = POSTRequestMock(query_params, user_profile) first_visible_message_id = first_unread_message_id + 2 with first_visible_id_as(first_visible_message_id): with queries_captured() as all_queries: get_messages_backend(request, user_profile) queries = [q for q in all_queries if '/* get_messages */' in q['sql']] self.assertEqual(len(queries), 1) sql = queries[0]['sql'] self.assertNotIn('AND message_id = %s' % (LARGER_THAN_MAX_MESSAGE_ID,), sql) self.assertIn('ORDER BY message_id ASC', sql) cond = 'WHERE user_profile_id = %d AND message_id <= %d' % ( user_profile.id, first_unread_message_id - 1 ) self.assertIn(cond, sql) cond = 'WHERE user_profile_id = %d AND message_id >= %d' % ( user_profile.id, first_visible_message_id ) self.assertIn(cond, sql) def test_use_first_unread_anchor_with_no_unread_messages(self) -> None: user_profile = self.example_user('hamlet') query_params = dict( use_first_unread_anchor='true', anchor=0, num_before=10, num_after=10, narrow='[]' ) request = POSTRequestMock(query_params, user_profile) with queries_captured() as all_queries: get_messages_backend(request, user_profile) queries = [q for q in all_queries if '/* get_messages */' in q['sql']] self.assertEqual(len(queries), 1) sql = queries[0]['sql'] self.assertNotIn('AND message_id <=', sql) self.assertNotIn('AND message_id >=', sql) first_visible_message_id = 5 with first_visible_id_as(first_visible_message_id): with queries_captured() as all_queries: get_messages_backend(request, user_profile) queries = [q for q in all_queries if '/* get_messages */' in q['sql']] sql = queries[0]['sql'] self.assertNotIn('AND message_id <=', sql) self.assertNotIn('AND message_id >=', sql) def test_use_first_unread_anchor_with_muted_topics(self) -> None: """ Test that our logic related to `use_first_unread_anchor` invokes the `message_id = LARGER_THAN_MAX_MESSAGE_ID` hack for the `/* get_messages */` query when relevant muting is in effect. This is a very arcane test on arcane, but very heavily field-tested, logic in get_messages_backend(). If this test breaks, be absolutely sure you know what you're doing. """ realm = get_realm('zulip') self.make_stream('web stuff') self.make_stream('bogus') user_profile = self.example_user('hamlet') muted_topics = [ ['Scotland', 'golf'], ['web stuff', 'css'], ['bogus', 'bogus'] ] set_topic_mutes(user_profile, muted_topics) query_params = dict( use_first_unread_anchor='true', anchor=0, num_before=0, num_after=0, narrow='[["stream", "Scotland"]]' ) request = POSTRequestMock(query_params, user_profile) with queries_captured() as all_queries: get_messages_backend(request, user_profile) # Do some tests on the main query, to verify the muting logic # runs on this code path. queries = [q for q in all_queries if str(q['sql']).startswith("SELECT message_id, flags")] self.assertEqual(len(queries), 1) stream = get_stream('Scotland', realm) recipient_id = get_stream_recipient(stream.id).id cond = '''AND NOT (recipient_id = {scotland} AND upper(subject) = upper('golf'))'''.format(scotland=recipient_id) self.assertIn(cond, queries[0]['sql']) # Next, verify the use_first_unread_anchor setting invokes # the `message_id = LARGER_THAN_MAX_MESSAGE_ID` hack. queries = [q for q in all_queries if '/* get_messages */' in q['sql']] self.assertEqual(len(queries), 1) self.assertIn('AND zerver_message.id = %d' % (LARGER_THAN_MAX_MESSAGE_ID,), queries[0]['sql']) def test_exclude_muting_conditions(self) -> None: realm = get_realm('zulip') self.make_stream('web stuff') user_profile = self.example_user('hamlet') self.make_stream('irrelevant_stream') # Test the do-nothing case first. muted_topics = [ ['irrelevant_stream', 'irrelevant_topic'] ] set_topic_mutes(user_profile, muted_topics) # If nothing relevant is muted, then exclude_muting_conditions() # should return an empty list. narrow = [ dict(operator='stream', operand='Scotland'), ] muting_conditions = exclude_muting_conditions(user_profile, narrow) self.assertEqual(muting_conditions, []) # Ok, now set up our muted topics to include a topic relevant to our narrow. muted_topics = [ ['Scotland', 'golf'], ['web stuff', 'css'], ] set_topic_mutes(user_profile, muted_topics) # And verify that our query will exclude them. narrow = [ dict(operator='stream', operand='Scotland'), ] muting_conditions = exclude_muting_conditions(user_profile, narrow) query = select([column("id").label("message_id")], None, table("zerver_message")) query = query.where(*muting_conditions) expected_query = ''' SELECT id AS message_id FROM zerver_message WHERE NOT (recipient_id = :recipient_id_1 AND upper(subject) = upper(:param_1)) ''' self.assertEqual(fix_ws(query), fix_ws(expected_query)) params = get_sqlalchemy_query_params(query) self.assertEqual(params['recipient_id_1'], get_recipient_id_for_stream_name(realm, 'Scotland')) self.assertEqual(params['param_1'], 'golf') mute_stream(realm, user_profile, 'Verona') # Using a bogus stream name should be similar to using no narrow at # all, and we'll exclude all mutes. narrow = [ dict(operator='stream', operand='bogus-stream-name'), ] muting_conditions = exclude_muting_conditions(user_profile, narrow) query = select([column("id")], None, table("zerver_message")) query = query.where(and_(*muting_conditions)) expected_query = ''' SELECT id FROM zerver_message WHERE recipient_id NOT IN (:recipient_id_1) AND NOT (recipient_id = :recipient_id_2 AND upper(subject) = upper(:param_1) OR recipient_id = :recipient_id_3 AND upper(subject) = upper(:param_2))''' self.assertEqual(fix_ws(query), fix_ws(expected_query)) params = get_sqlalchemy_query_params(query) self.assertEqual(params['recipient_id_1'], get_recipient_id_for_stream_name(realm, 'Verona')) self.assertEqual(params['recipient_id_2'], get_recipient_id_for_stream_name(realm, 'Scotland')) self.assertEqual(params['param_1'], 'golf') self.assertEqual(params['recipient_id_3'], get_recipient_id_for_stream_name(realm, 'web stuff')) self.assertEqual(params['param_2'], 'css') def test_get_messages_queries(self) -> None: query_ids = self.get_query_ids() sql_template = 'SELECT anon_1.message_id, anon_1.flags \nFROM (SELECT message_id, flags \nFROM zerver_usermessage \nWHERE user_profile_id = {hamlet_id} AND message_id = 0) AS anon_1 ORDER BY message_id ASC' sql = sql_template.format(**query_ids) self.common_check_get_messages_query({'anchor': 0, 'num_before': 0, 'num_after': 0}, sql) sql_template = 'SELECT anon_1.message_id, anon_1.flags \nFROM (SELECT message_id, flags \nFROM zerver_usermessage \nWHERE user_profile_id = {hamlet_id} AND message_id = 0) AS anon_1 ORDER BY message_id ASC' sql = sql_template.format(**query_ids) self.common_check_get_messages_query({'anchor': 0, 'num_before': 1, 'num_after': 0}, sql) sql_template = 'SELECT anon_1.message_id, anon_1.flags \nFROM (SELECT message_id, flags \nFROM zerver_usermessage \nWHERE user_profile_id = {hamlet_id} ORDER BY message_id ASC \n LIMIT 2) AS anon_1 ORDER BY message_id ASC' sql = sql_template.format(**query_ids) self.common_check_get_messages_query({'anchor': 0, 'num_before': 0, 'num_after': 1}, sql) sql_template = 'SELECT anon_1.message_id, anon_1.flags \nFROM (SELECT message_id, flags \nFROM zerver_usermessage \nWHERE user_profile_id = {hamlet_id} ORDER BY message_id ASC \n LIMIT 11) AS anon_1 ORDER BY message_id ASC' sql = sql_template.format(**query_ids) self.common_check_get_messages_query({'anchor': 0, 'num_before': 0, 'num_after': 10}, sql) sql_template = 'SELECT anon_1.message_id, anon_1.flags \nFROM (SELECT message_id, flags \nFROM zerver_usermessage \nWHERE user_profile_id = {hamlet_id} AND message_id <= 100 ORDER BY message_id DESC \n LIMIT 11) AS anon_1 ORDER BY message_id ASC' sql = sql_template.format(**query_ids) self.common_check_get_messages_query({'anchor': 100, 'num_before': 10, 'num_after': 0}, sql) sql_template = 'SELECT anon_1.message_id, anon_1.flags \nFROM ((SELECT message_id, flags \nFROM zerver_usermessage \nWHERE user_profile_id = {hamlet_id} AND message_id <= 99 ORDER BY message_id DESC \n LIMIT 10) UNION ALL (SELECT message_id, flags \nFROM zerver_usermessage \nWHERE user_profile_id = {hamlet_id} AND message_id >= 100 ORDER BY message_id ASC \n LIMIT 11)) AS anon_1 ORDER BY message_id ASC' sql = sql_template.format(**query_ids) self.common_check_get_messages_query({'anchor': 100, 'num_before': 10, 'num_after': 10}, sql) def test_get_messages_with_narrow_queries(self) -> None: query_ids = self.get_query_ids() sql_template = 'SELECT anon_1.message_id, anon_1.flags \nFROM (SELECT message_id, flags \nFROM zerver_usermessage JOIN zerver_message ON zerver_usermessage.message_id = zerver_message.id \nWHERE user_profile_id = {hamlet_id} AND (sender_id = {othello_id} AND recipient_id = {hamlet_recipient} OR sender_id = {hamlet_id} AND recipient_id = {othello_recipient}) AND message_id = 0) AS anon_1 ORDER BY message_id ASC' sql = sql_template.format(**query_ids) self.common_check_get_messages_query({'anchor': 0, 'num_before': 0, 'num_after': 0, 'narrow': '[["pm-with", "%s"]]' % (self.example_email("othello"),)}, sql) sql_template = 'SELECT anon_1.message_id, anon_1.flags \nFROM (SELECT message_id, flags \nFROM zerver_usermessage JOIN zerver_message ON zerver_usermessage.message_id = zerver_message.id \nWHERE user_profile_id = {hamlet_id} AND (sender_id = {othello_id} AND recipient_id = {hamlet_recipient} OR sender_id = {hamlet_id} AND recipient_id = {othello_recipient}) AND message_id = 0) AS anon_1 ORDER BY message_id ASC' sql = sql_template.format(**query_ids) self.common_check_get_messages_query({'anchor': 0, 'num_before': 1, 'num_after': 0, 'narrow': '[["pm-with", "%s"]]' % (self.example_email("othello"),)}, sql) sql_template = 'SELECT anon_1.message_id, anon_1.flags \nFROM (SELECT message_id, flags \nFROM zerver_usermessage JOIN zerver_message ON zerver_usermessage.message_id = zerver_message.id \nWHERE user_profile_id = {hamlet_id} AND (sender_id = {othello_id} AND recipient_id = {hamlet_recipient} OR sender_id = {hamlet_id} AND recipient_id = {othello_recipient}) ORDER BY message_id ASC \n LIMIT 10) AS anon_1 ORDER BY message_id ASC' sql = sql_template.format(**query_ids) self.common_check_get_messages_query({'anchor': 0, 'num_before': 0, 'num_after': 9, 'narrow': '[["pm-with", "%s"]]' % (self.example_email("othello"),)}, sql) sql_template = 'SELECT anon_1.message_id, anon_1.flags \nFROM (SELECT message_id, flags \nFROM zerver_usermessage JOIN zerver_message ON zerver_usermessage.message_id = zerver_message.id \nWHERE user_profile_id = {hamlet_id} AND (flags & 2) != 0 ORDER BY message_id ASC \n LIMIT 10) AS anon_1 ORDER BY message_id ASC' sql = sql_template.format(**query_ids) self.common_check_get_messages_query({'anchor': 0, 'num_before': 0, 'num_after': 9, 'narrow': '[["is", "starred"]]'}, sql) sql_template = 'SELECT anon_1.message_id, anon_1.flags \nFROM (SELECT message_id, flags \nFROM zerver_usermessage JOIN zerver_message ON zerver_usermessage.message_id = zerver_message.id \nWHERE user_profile_id = {hamlet_id} AND sender_id = {othello_id} ORDER BY message_id ASC \n LIMIT 10) AS anon_1 ORDER BY message_id ASC' sql = sql_template.format(**query_ids) self.common_check_get_messages_query({'anchor': 0, 'num_before': 0, 'num_after': 9, 'narrow': '[["sender", "%s"]]' % (self.example_email("othello"),)}, sql) sql_template = 'SELECT anon_1.message_id \nFROM (SELECT id AS message_id \nFROM zerver_message \nWHERE recipient_id = {scotland_recipient} ORDER BY zerver_message.id ASC \n LIMIT 10) AS anon_1 ORDER BY message_id ASC' sql = sql_template.format(**query_ids) self.common_check_get_messages_query({'anchor': 0, 'num_before': 0, 'num_after': 9, 'narrow': '[["stream", "Scotland"]]'}, sql) sql_template = "SELECT anon_1.message_id, anon_1.flags \nFROM (SELECT message_id, flags \nFROM zerver_usermessage JOIN zerver_message ON zerver_usermessage.message_id = zerver_message.id \nWHERE user_profile_id = {hamlet_id} AND upper(subject) = upper('blah') ORDER BY message_id ASC \n LIMIT 10) AS anon_1 ORDER BY message_id ASC" sql = sql_template.format(**query_ids) self.common_check_get_messages_query({'anchor': 0, 'num_before': 0, 'num_after': 9, 'narrow': '[["topic", "blah"]]'}, sql) sql_template = "SELECT anon_1.message_id \nFROM (SELECT id AS message_id \nFROM zerver_message \nWHERE recipient_id = {scotland_recipient} AND upper(subject) = upper('blah') ORDER BY zerver_message.id ASC \n LIMIT 10) AS anon_1 ORDER BY message_id ASC" sql = sql_template.format(**query_ids) self.common_check_get_messages_query({'anchor': 0, 'num_before': 0, 'num_after': 9, 'narrow': '[["stream", "Scotland"], ["topic", "blah"]]'}, sql) # Narrow to pms with yourself sql_template = 'SELECT anon_1.message_id, anon_1.flags \nFROM (SELECT message_id, flags \nFROM zerver_usermessage JOIN zerver_message ON zerver_usermessage.message_id = zerver_message.id \nWHERE user_profile_id = {hamlet_id} AND sender_id = {hamlet_id} AND recipient_id = {hamlet_recipient} ORDER BY message_id ASC \n LIMIT 10) AS anon_1 ORDER BY message_id ASC' sql = sql_template.format(**query_ids) self.common_check_get_messages_query({'anchor': 0, 'num_before': 0, 'num_after': 9, 'narrow': '[["pm-with", "%s"]]' % (self.example_email("hamlet"),)}, sql) sql_template = 'SELECT anon_1.message_id, anon_1.flags \nFROM (SELECT message_id, flags \nFROM zerver_usermessage JOIN zerver_message ON zerver_usermessage.message_id = zerver_message.id \nWHERE user_profile_id = {hamlet_id} AND recipient_id = {scotland_recipient} AND (flags & 2) != 0 ORDER BY message_id ASC \n LIMIT 10) AS anon_1 ORDER BY message_id ASC' sql = sql_template.format(**query_ids) self.common_check_get_messages_query({'anchor': 0, 'num_before': 0, 'num_after': 9, 'narrow': '[["stream", "Scotland"], ["is", "starred"]]'}, sql) @override_settings(USING_PGROONGA=False) def test_get_messages_with_search_queries(self) -> None: query_ids = self.get_query_ids() sql_template = "SELECT anon_1.message_id, anon_1.flags, anon_1.subject, anon_1.rendered_content, anon_1.content_matches, anon_1.topic_matches \nFROM (SELECT message_id, flags, subject, rendered_content, ts_match_locs_array('zulip.english_us_search', rendered_content, plainto_tsquery('zulip.english_us_search', 'jumping')) AS content_matches, ts_match_locs_array('zulip.english_us_search', escape_html(subject), plainto_tsquery('zulip.english_us_search', 'jumping')) AS topic_matches \nFROM zerver_usermessage JOIN zerver_message ON zerver_usermessage.message_id = zerver_message.id \nWHERE user_profile_id = {hamlet_id} AND (search_tsvector @@ plainto_tsquery('zulip.english_us_search', 'jumping')) ORDER BY message_id ASC \n LIMIT 10) AS anon_1 ORDER BY message_id ASC" # type: str sql = sql_template.format(**query_ids) self.common_check_get_messages_query({'anchor': 0, 'num_before': 0, 'num_after': 9, 'narrow': '[["search", "jumping"]]'}, sql) sql_template = "SELECT anon_1.message_id, anon_1.subject, anon_1.rendered_content, anon_1.content_matches, anon_1.topic_matches \nFROM (SELECT id AS message_id, subject, rendered_content, ts_match_locs_array('zulip.english_us_search', rendered_content, plainto_tsquery('zulip.english_us_search', 'jumping')) AS content_matches, ts_match_locs_array('zulip.english_us_search', escape_html(subject), plainto_tsquery('zulip.english_us_search', 'jumping')) AS topic_matches \nFROM zerver_message \nWHERE recipient_id = {scotland_recipient} AND (search_tsvector @@ plainto_tsquery('zulip.english_us_search', 'jumping')) ORDER BY zerver_message.id ASC \n LIMIT 10) AS anon_1 ORDER BY message_id ASC" sql = sql_template.format(**query_ids) self.common_check_get_messages_query({'anchor': 0, 'num_before': 0, 'num_after': 9, 'narrow': '[["stream", "Scotland"], ["search", "jumping"]]'}, sql) sql_template = 'SELECT anon_1.message_id, anon_1.flags, anon_1.subject, anon_1.rendered_content, anon_1.content_matches, anon_1.topic_matches \nFROM (SELECT message_id, flags, subject, rendered_content, ts_match_locs_array(\'zulip.english_us_search\', rendered_content, plainto_tsquery(\'zulip.english_us_search\', \'"jumping" quickly\')) AS content_matches, ts_match_locs_array(\'zulip.english_us_search\', escape_html(subject), plainto_tsquery(\'zulip.english_us_search\', \'"jumping" quickly\')) AS topic_matches \nFROM zerver_usermessage JOIN zerver_message ON zerver_usermessage.message_id = zerver_message.id \nWHERE user_profile_id = {hamlet_id} AND (content ILIKE \'%jumping%\' OR subject ILIKE \'%jumping%\') AND (search_tsvector @@ plainto_tsquery(\'zulip.english_us_search\', \'"jumping" quickly\')) ORDER BY message_id ASC \n LIMIT 10) AS anon_1 ORDER BY message_id ASC' sql = sql_template.format(**query_ids) self.common_check_get_messages_query({'anchor': 0, 'num_before': 0, 'num_after': 9, 'narrow': '[["search", "\\"jumping\\" quickly"]]'}, sql) @override_settings(USING_PGROONGA=False) def test_get_messages_with_search_using_email(self) -> None: self.login(self.example_email("cordelia")) messages_to_search = [ ('say hello', 'How are you doing, @**Othello, the Moor of Venice**?'), ('lunch plans', 'I am hungry!'), ] next_message_id = self.get_last_message().id + 1 for topic, content in messages_to_search: self.send_stream_message( sender_email=self.example_email("cordelia"), stream_name="Verona", content=content, topic_name=topic, ) self._update_tsvector_index() narrow = [ dict(operator='sender', operand=self.example_email("cordelia")), dict(operator='search', operand=self.example_email("othello")), ] result = self.get_and_check_messages(dict( narrow=ujson.dumps(narrow), anchor=next_message_id, num_after=10, )) # type: Dict[str, Any] self.assertEqual(len(result['messages']), 0) narrow = [ dict(operator='sender', operand=self.example_email("cordelia")), dict(operator='search', operand='othello'), ] result = self.get_and_check_messages(dict( narrow=ujson.dumps(narrow), anchor=next_message_id, num_after=10, )) self.assertEqual(len(result['messages']), 1) messages = result['messages'] meeting_message = [m for m in messages if m[TOPIC_NAME] == 'say hello'][0] self.assertEqual( meeting_message[MATCH_TOPIC], 'say hello') othello = self.example_user('othello') self.assertEqual( meeting_message['match_content'], ('<p>How are you doing, <span class="user-mention" data-user-id="%s">' + '@<span class="highlight">Othello</span>, the Moor of Venice</span>?</p>') % ( othello.id))
[ "str", "str", "Realm", "str", "Realm", "str", "str", "int", "Dict[str, Any]", "str", "Dict[str, Any]", "List[int]", "int", "int", "int", "int", "bool", "bool", "List[int]", "bool", "bool", "bool", "bool", "Dict[str, Union[str, int]]", "Any", "List[Dict[str, str]]", "List[int]", "int", "bool", "Union[str, List[Dict[str, Any]]]", "str", "str", "List[Dict[str, Any]]", "List[int]", "str", "Sequence[Any]", "str", "Dict[str, object]", "str" ]
[ 1479, 1639, 1744, 1764, 1891, 1912, 1930, 2227, 17373, 17403, 17738, 25318, 25360, 25395, 25445, 25477, 25519, 25563, 25597, 25641, 25680, 25719, 25761, 40710, 40779, 41636, 41703, 41727, 43587, 46705, 61603, 77125, 79348, 79383, 91171, 91222, 91284, 93652, 93681 ]
[ 1482, 1642, 1749, 1767, 1896, 1915, 1933, 2230, 17387, 17406, 17752, 25327, 25363, 25398, 25448, 25480, 25523, 25567, 25606, 25645, 25684, 25723, 25765, 40736, 40782, 41656, 41712, 41730, 43591, 46737, 61606, 77128, 79368, 79392, 91174, 91235, 91287, 93669, 93684 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_new_users.py
import datetime from django.conf import settings from django.core import mail from django.contrib.auth.signals import user_logged_in from django.test import override_settings from zerver.lib.test_classes import ZulipTestCase from zerver.signals import get_device_browser, get_device_os, JUST_CREATED_THRESHOLD from zerver.lib.actions import notify_new_user, do_change_notification_settings from zerver.models import Recipient, Stream, Realm from zerver.lib.initial_password import initial_password from unittest import mock from zerver.lib.timezone import get_timezone class SendLoginEmailTest(ZulipTestCase): """ Uses django's user_logged_in signal to send emails on new login. The receiver handler for this signal is always registered in production, development and testing, but emails are only sent based on SEND_LOGIN_EMAILS setting. SEND_LOGIN_EMAILS is set to true in default settings. It is turned off during testing. """ def test_send_login_emails_if_send_login_email_setting_is_true(self) -> None: with self.settings(SEND_LOGIN_EMAILS=True): self.assertTrue(settings.SEND_LOGIN_EMAILS) # we don't use the self.login method since we spoof the user-agent utc = get_timezone('utc') mock_time = datetime.datetime(year=2018, month=1, day=1, tzinfo=utc) user = self.example_user('hamlet') user.timezone = 'US/Pacific' user.twenty_four_hour_time = False user.date_joined = mock_time - datetime.timedelta(seconds=JUST_CREATED_THRESHOLD + 1) user.save() password = initial_password(user.email) firefox_windows = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0" user_tz = get_timezone(user.timezone) mock_time = datetime.datetime(year=2018, month=1, day=1, tzinfo=utc) reference_time = mock_time.astimezone(user_tz).strftime('%A, %B %d, %Y at %I:%M%p %Z') with mock.patch('zerver.signals.timezone_now', return_value=mock_time): self.client_post("/accounts/login/", info={"username": user.email, "password": password}, HTTP_USER_AGENT=firefox_windows) # email is sent and correct subject self.assertEqual(len(mail.outbox), 1) subject = 'New login from Firefox on Windows' self.assertEqual(mail.outbox[0].subject, subject) # local time is correct and in email's body self.assertIn(reference_time, mail.outbox[0].body) # Try again with the 24h time format setting enabled for this user self.logout() # We just logged in, we'd be redirected without this user.twenty_four_hour_time = True user.save() with mock.patch('zerver.signals.timezone_now', return_value=mock_time): self.client_post("/accounts/login/", info={"username": user.email, "password": password}, HTTP_USER_AGENT=firefox_windows) reference_time = mock_time.astimezone(user_tz).strftime('%A, %B %d, %Y at %H:%M %Z') self.assertIn(reference_time, mail.outbox[1].body) def test_dont_send_login_emails_if_send_login_emails_is_false(self) -> None: self.assertFalse(settings.SEND_LOGIN_EMAILS) email = self.example_email('hamlet') self.login(email) self.assertEqual(len(mail.outbox), 0) def test_dont_send_login_emails_for_new_user_registration_logins(self) -> None: with self.settings(SEND_LOGIN_EMAILS=True): self.register("test@zulip.com", "test") # Verify that there's just 1 email for new user registration. self.assertEqual(mail.outbox[0].subject, "Activate your Zulip account") self.assertEqual(len(mail.outbox), 1) def test_without_path_info_dont_send_login_emails_for_new_user_registration_logins(self) -> None: with self.settings(SEND_LOGIN_EMAILS=True): self.client_post('/accounts/home/', {'email': "orange@zulip.com"}) self.submit_reg_form_for_user("orange@zulip.com", "orange", PATH_INFO='') for email in mail.outbox: subject = 'New login from an unknown browser on an unknown operating system' self.assertNotEqual(email.subject, subject) @override_settings(SEND_LOGIN_EMAILS=True) def test_enable_login_emails_user_setting(self) -> None: user = self.example_user('hamlet') utc = get_timezone('utc') mock_time = datetime.datetime(year=2018, month=1, day=1, tzinfo=utc) user.timezone = 'US/Pacific' user.date_joined = mock_time - datetime.timedelta(seconds=JUST_CREATED_THRESHOLD + 1) user.save() do_change_notification_settings(user, "enable_login_emails", False) self.assertFalse(user.enable_login_emails) with mock.patch('zerver.signals.timezone_now', return_value=mock_time): self.login(user.email) self.assertEqual(len(mail.outbox), 0) do_change_notification_settings(user, "enable_login_emails", True) self.assertTrue(user.enable_login_emails) with mock.patch('zerver.signals.timezone_now', return_value=mock_time): self.login(user.email) self.assertEqual(len(mail.outbox), 1) class TestBrowserAndOsUserAgentStrings(ZulipTestCase): def setUp(self) -> None: self.user_agents = [ ('mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) ' + 'Chrome/54.0.2840.59 Safari/537.36', 'Chrome', 'Linux',), ('mozilla/5.0 (windows nt 6.1; win64; x64) applewebkit/537.36 (khtml, like gecko) ' + 'chrome/56.0.2924.87 safari/537.36', 'Chrome', 'Windows',), ('mozilla/5.0 (windows nt 6.1; wow64; rv:51.0) ' + 'gecko/20100101 firefox/51.0', 'Firefox', 'Windows',), ('mozilla/5.0 (windows nt 6.1; wow64; trident/7.0; rv:11.0) ' + 'like gecko', 'Internet Explorer', 'Windows'), ('Mozilla/5.0 (Android; Mobile; rv:27.0) ' + 'Gecko/27.0 Firefox/27.0', 'Firefox', 'Android'), ('Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X) ' 'AppleWebKit/602.1.50 (KHTML, like Gecko) ' 'CriOS/56.0.2924.75 Mobile/14E5239e Safari/602.1', 'Chrome', 'iOS'), ('Mozilla/5.0 (iPad; CPU OS 6_1_3 like Mac OS X) ' + 'AppleWebKit/536.26 (KHTML, like Gecko) ' + 'Version/6.0 Mobile/10B329 Safari/8536.25', 'Safari', 'iOS'), ('Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_4 like Mac OS X) ' + 'AppleWebKit/536.26 (KHTML, like Gecko) Mobile/10B350', None, 'iOS'), ('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) ' + 'AppleWebKit/537.36 (KHTML, like Gecko) ' + 'Chrome/56.0.2924.87 Safari/537.36', 'Chrome', 'macOS'), ('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) ' + 'AppleWebKit/602.3.12 (KHTML, like Gecko) ' + 'Version/10.0.2 Safari/602.3.12', 'Safari', 'macOS'), ('ZulipAndroid/1.0', 'Zulip', 'Android'), ('ZulipMobile/1.0.12 (Android 7.1.1)', 'Zulip', 'Android'), ('ZulipMobile/0.7.1.1 (iOS 10.3.1)', 'Zulip', 'iOS'), ('ZulipElectron/1.1.0-beta Mozilla/5.0 (Windows NT 10.0; Win64; x64) ' + 'AppleWebKit/537.36 (KHTML, like Gecko) Zulip/1.1.0-beta ' + 'Chrome/56.0.2924.87 Electron/1.6.8 Safari/537.36', 'Zulip', 'Windows'), ('Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.7 (KHTML, ' 'like Gecko) Ubuntu/11.10 Chromium/16.0.912.77 ' 'Chrome/16.0.912.77 Safari/535.7', 'Chromium', 'Linux'), ('Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 ' '(KHTML, like Gecko) Chrome/28.0.1500.52 Safari/537.36 ' 'OPR/15.0.1147.100', 'Opera', 'Windows'), ('Mozilla/5.0 (Windows NT 10.0; <64-bit tags>) AppleWebKit/' '<WebKit Rev> (KHTML, like Gecko) Chrome/<Chrome Rev> Safari' '/<WebKit Rev> Edge/<EdgeHTML Rev>.' '<Windows Build>', 'Edge', 'Windows'), ('Mozilla/5.0 (X11; CrOS x86_64 10895.56.0) AppleWebKit/537.36' '(KHTML, like Gecko) Chrome/69.0.3497.95 Safari/537.36', 'Chrome', 'ChromeOS'), ('', None, None), ] def test_get_browser_on_new_login(self) -> None: for user_agent in self.user_agents: device_browser = get_device_browser(user_agent[0]) self.assertEqual(device_browser, user_agent[1]) def test_get_os_on_new_login(self) -> None: for user_agent in self.user_agents: device_os = get_device_os(user_agent[0]) self.assertEqual(device_os, user_agent[2]) class TestNotifyNewUser(ZulipTestCase): def test_notify_of_new_user_internally(self) -> None: new_user = self.example_user('cordelia') self.make_stream('signups') notify_new_user(new_user, internal=True) message = self.get_last_message() actual_stream = Stream.objects.get(id=message.recipient.type_id) self.assertEqual(actual_stream.name, 'signups') self.assertEqual(message.recipient.type, Recipient.STREAM) self.assertIn("**INTERNAL SIGNUP**", message.content) def test_notify_realm_of_new_user(self) -> None: new_user = self.example_user('cordelia') stream = self.make_stream(Realm.INITIAL_PRIVATE_STREAM_NAME) new_user.realm.signup_notifications_stream_id = stream.id new_user.realm.save() new_user = self.example_user('cordelia') notify_new_user(new_user) message = self.get_last_message() self.assertEqual(message.recipient.type, Recipient.STREAM) actual_stream = Stream.objects.get(id=message.recipient.type_id) self.assertEqual(actual_stream.name, Realm.INITIAL_PRIVATE_STREAM_NAME)
[]
[]
[]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_notifications.py
import os import random import re import ujson from django.conf import settings from django.core import mail from django.http import HttpResponse from django.test import override_settings from email.utils import formataddr from mock import patch, MagicMock from typing import Any, Dict, List, Optional from zerver.lib.notifications import fix_emojis, handle_missedmessage_emails, \ enqueue_welcome_emails, relative_to_full_url from zerver.lib.actions import do_update_message, do_change_notification_settings from zerver.lib.message import access_message from zerver.lib.test_classes import ZulipTestCase from zerver.lib.send_email import FromAddress from zerver.lib.test_helpers import MockLDAP from zerver.models import ( get_realm, get_stream, Recipient, UserMessage, UserProfile, ScheduledEmail ) from zerver.lib.test_helpers import get_test_image_file class TestFollowupEmails(ZulipTestCase): def test_day1_email_context(self) -> None: hamlet = self.example_user("hamlet") enqueue_welcome_emails(hamlet) scheduled_emails = ScheduledEmail.objects.filter(user=hamlet) email_data = ujson.loads(scheduled_emails[0].data) self.assertEqual(email_data["context"]["email"], self.example_email("hamlet")) self.assertEqual(email_data["context"]["is_realm_admin"], False) self.assertEqual(email_data["context"]["getting_started_link"], "https://zulipchat.com") self.assertNotIn("ldap_username", email_data["context"]) ScheduledEmail.objects.all().delete() iago = self.example_user("iago") enqueue_welcome_emails(iago) scheduled_emails = ScheduledEmail.objects.filter(user=iago) email_data = ujson.loads(scheduled_emails[0].data) self.assertEqual(email_data["context"]["email"], self.example_email("iago")) self.assertEqual(email_data["context"]["is_realm_admin"], True) self.assertEqual(email_data["context"]["getting_started_link"], "http://zulip.testserver/help/getting-your-organization-started-with-zulip") self.assertNotIn("ldap_username", email_data["context"]) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend', 'zproject.backends.ZulipDummyBackend')) def test_day1_email_ldap_login_credentials(self) -> None: password = "testing" email = "newuser@zulip.com" ldap_user_attr_map = {'full_name': 'fn', 'short_name': 'sn'} ldap_patcher = patch('django_auth_ldap.config.ldap.initialize') mock_initialize = ldap_patcher.start() mock_ldap = MockLDAP() mock_initialize.return_value = mock_ldap full_name = 'New LDAP fullname' mock_ldap.directory = { 'uid=newuser,ou=users,dc=zulip,dc=com': { 'userPassword': 'testing', 'fn': [full_name], 'sn': ['shortname'], } } with self.settings( LDAP_APPEND_DOMAIN='zulip.com', AUTH_LDAP_USER_ATTR_MAP=ldap_user_attr_map, AUTH_LDAP_USER_DN_TEMPLATE='uid=%(user)s,ou=users,dc=zulip,dc=com'): self.login_with_return(email, password) user = UserProfile.objects.get(email=email) scheduled_emails = ScheduledEmail.objects.filter(user=user) self.assertEqual(len(scheduled_emails), 2) email_data = ujson.loads(scheduled_emails[0].data) self.assertEqual(email_data["context"]["ldap_username"], True) def test_followup_emails_count(self) -> None: hamlet = self.example_user("hamlet") cordelia = self.example_user("cordelia") enqueue_welcome_emails(self.example_user("hamlet")) # Hamlet has account only in Zulip realm so both day1 and day2 emails should be sent scheduled_emails = ScheduledEmail.objects.filter(user=hamlet) self.assertEqual(2, len(scheduled_emails)) self.assertEqual(ujson.loads(scheduled_emails[0].data)["template_prefix"], 'zerver/emails/followup_day2') self.assertEqual(ujson.loads(scheduled_emails[1].data)["template_prefix"], 'zerver/emails/followup_day1') ScheduledEmail.objects.all().delete() enqueue_welcome_emails(cordelia) scheduled_emails = ScheduledEmail.objects.filter(user=cordelia) # Cordelia has account in more than 1 realm so day2 email should not be sent self.assertEqual(len(scheduled_emails), 1) email_data = ujson.loads(scheduled_emails[0].data) self.assertEqual(email_data["template_prefix"], 'zerver/emails/followup_day1') class TestMissedMessages(ZulipTestCase): def normalize_string(self, s: str) -> str: s = s.strip() return re.sub(r'\s+', ' ', s) def _get_tokens(self) -> List[str]: return [str(random.getrandbits(32)) for _ in range(30)] def _test_cases(self, tokens: List[str], msg_id: int, body: str, email_subject: str, send_as_user: bool, verify_html_body: bool=False, show_message_content: bool=True, verify_body_does_not_include: Optional[List[str]]=None, trigger: str='') -> None: othello = self.example_user('othello') hamlet = self.example_user('hamlet') handle_missedmessage_emails(hamlet.id, [{'message_id': msg_id, 'trigger': trigger}]) if settings.EMAIL_GATEWAY_PATTERN != "": reply_to_addresses = [settings.EMAIL_GATEWAY_PATTERN % (u'mm' + t) for t in tokens] reply_to_emails = [formataddr(("Zulip", address)) for address in reply_to_addresses] else: reply_to_emails = ["noreply@testserver"] msg = mail.outbox[0] from_email = formataddr(("Zulip missed messages", FromAddress.NOREPLY)) self.assertEqual(len(mail.outbox), 1) if send_as_user: from_email = '"%s" <%s>' % (othello.full_name, othello.email) self.assertEqual(msg.from_email, from_email) self.assertEqual(msg.subject, email_subject) self.assertEqual(len(msg.reply_to), 1) self.assertIn(msg.reply_to[0], reply_to_emails) if verify_html_body: self.assertIn(body, self.normalize_string(msg.alternatives[0][0])) else: self.assertIn(body, self.normalize_string(msg.body)) if verify_body_does_not_include is not None: for text in verify_body_does_not_include: self.assertNotIn(text, self.normalize_string(msg.body)) @patch('zerver.lib.email_mirror.generate_random_token') def _realm_name_in_missed_message_email_subject(self, realm_name_in_notifications: bool, mock_random_token: MagicMock) -> None: tokens = self._get_tokens() mock_random_token.side_effect = tokens msg_id = self.send_personal_message( self.example_email('othello'), self.example_email('hamlet'), 'Extremely personal message!', ) body = 'You and Othello, the Moor of Venice Extremely personal message!' email_subject = 'Othello, the Moor of Venice sent you a message' if realm_name_in_notifications: email_subject = 'Othello, the Moor of Venice sent you a message in Zulip Dev' self._test_cases(tokens, msg_id, body, email_subject, False) @patch('zerver.lib.email_mirror.generate_random_token') def _extra_context_in_missed_stream_messages_mention(self, send_as_user: bool, mock_random_token: MagicMock, show_message_content: bool=True) -> None: tokens = self._get_tokens() mock_random_token.side_effect = tokens for i in range(0, 11): self.send_stream_message(self.example_email('othello'), "Denmark", content=str(i)) self.send_stream_message( self.example_email('othello'), "Denmark", '11', topic_name='test2') msg_id = self.send_stream_message( self.example_email('othello'), "denmark", '@**King Hamlet**') if show_message_content: body = 'Denmark > test Othello, the Moor of Venice 1 2 3 4 5 6 7 8 9 10 @**King Hamlet**' email_subject = 'Othello, the Moor of Venice mentioned you' verify_body_does_not_include = [] # type: List[str] else: # Test in case if message content in missed email message are disabled. body = 'While you were away you received 1 new message in which you were mentioned!' email_subject = 'New missed message' verify_body_does_not_include = ['Denmark > test', 'Othello, the Moor of Venice', '1 2 3 4 5 6 7 8 9 10 @**King Hamlet**', 'private', 'group', 'Or just reply to this email.'] self._test_cases(tokens, msg_id, body, email_subject, send_as_user, show_message_content=show_message_content, verify_body_does_not_include=verify_body_does_not_include, trigger='mentioned') @patch('zerver.lib.email_mirror.generate_random_token') def _extra_context_in_missed_stream_messages_email_notify(self, send_as_user: bool, mock_random_token: MagicMock) -> None: tokens = self._get_tokens() mock_random_token.side_effect = tokens for i in range(0, 11): self.send_stream_message(self.example_email('othello'), "Denmark", content=str(i)) self.send_stream_message( self.example_email('othello'), "Denmark", '11', topic_name='test2') msg_id = self.send_stream_message( self.example_email('othello'), "denmark", '12') body = 'Denmark > test Othello, the Moor of Venice 1 2 3 4 5 6 7 8 9 10 12' email_subject = 'New messages in Denmark > test' self._test_cases(tokens, msg_id, body, email_subject, send_as_user, trigger='stream_email_notify') @patch('zerver.lib.email_mirror.generate_random_token') def _extra_context_in_missed_stream_messages_mention_two_senders( self, send_as_user: bool, mock_random_token: MagicMock) -> None: tokens = self._get_tokens() mock_random_token.side_effect = tokens for i in range(0, 3): self.send_stream_message(self.example_email('cordelia'), "Denmark", str(i)) msg_id = self.send_stream_message( self.example_email('othello'), "Denmark", '@**King Hamlet**') body = 'Denmark > test Cordelia Lear 0 1 2 Othello, the Moor of Venice @**King Hamlet**' email_subject = 'Othello, the Moor of Venice mentioned you' self._test_cases(tokens, msg_id, body, email_subject, send_as_user, trigger='mentioned') @patch('zerver.lib.email_mirror.generate_random_token') def _extra_context_in_personal_missed_stream_messages(self, send_as_user: bool, mock_random_token: MagicMock, show_message_content: bool=True) -> None: tokens = self._get_tokens() mock_random_token.side_effect = tokens msg_id = self.send_personal_message( self.example_email('othello'), self.example_email('hamlet'), 'Extremely personal message!', ) if show_message_content: body = 'You and Othello, the Moor of Venice Extremely personal message!' email_subject = 'Othello, the Moor of Venice sent you a message' verify_body_does_not_include = [] # type: List[str] else: body = 'While you were away you received 1 new private message!' email_subject = 'New missed message' verify_body_does_not_include = ['Othello, the Moor of Venice', 'Extremely personal message!', 'mentioned', 'group', 'Or just reply to this email.'] self._test_cases(tokens, msg_id, body, email_subject, send_as_user, show_message_content=show_message_content, verify_body_does_not_include=verify_body_does_not_include) @patch('zerver.lib.email_mirror.generate_random_token') def _reply_to_email_in_personal_missed_stream_messages(self, send_as_user: bool, mock_random_token: MagicMock) -> None: tokens = self._get_tokens() mock_random_token.side_effect = tokens msg_id = self.send_personal_message( self.example_email('othello'), self.example_email('hamlet'), 'Extremely personal message!', ) body = 'Or just reply to this email.' email_subject = 'Othello, the Moor of Venice sent you a message' self._test_cases(tokens, msg_id, body, email_subject, send_as_user) @patch('zerver.lib.email_mirror.generate_random_token') def _reply_warning_in_personal_missed_stream_messages(self, send_as_user: bool, mock_random_token: MagicMock) -> None: tokens = self._get_tokens() mock_random_token.side_effect = tokens msg_id = self.send_personal_message( self.example_email('othello'), self.example_email('hamlet'), 'Extremely personal message!', ) body = 'Please do not reply to this automated message.' email_subject = 'Othello, the Moor of Venice sent you a message' self._test_cases(tokens, msg_id, body, email_subject, send_as_user) @patch('zerver.lib.email_mirror.generate_random_token') def _extra_context_in_huddle_missed_stream_messages_two_others(self, send_as_user: bool, mock_random_token: MagicMock, show_message_content: bool=True) -> None: tokens = self._get_tokens() mock_random_token.side_effect = tokens msg_id = self.send_huddle_message( self.example_email('othello'), [ self.example_email('hamlet'), self.example_email('iago'), ], 'Group personal message!', ) if show_message_content: body = ('You and Iago, Othello, the Moor of Venice Othello,' ' the Moor of Venice Group personal message') email_subject = 'Group PMs with Iago and Othello, the Moor of Venice' verify_body_does_not_include = [] # type: List[str] else: body = 'While you were away you received 1 new group private message!' email_subject = 'New missed message' verify_body_does_not_include = ['Iago', 'Othello, the Moor of Venice Othello, the Moor of Venice', 'Group personal message!', 'mentioned', 'Or just reply to this email.'] self._test_cases(tokens, msg_id, body, email_subject, send_as_user, show_message_content=show_message_content, verify_body_does_not_include=verify_body_does_not_include) @patch('zerver.lib.email_mirror.generate_random_token') def _extra_context_in_huddle_missed_stream_messages_three_others(self, send_as_user: bool, mock_random_token: MagicMock) -> None: tokens = self._get_tokens() mock_random_token.side_effect = tokens msg_id = self.send_huddle_message( self.example_email('othello'), [ self.example_email('hamlet'), self.example_email('iago'), self.example_email('cordelia'), ], 'Group personal message!', ) body = ('You and Cordelia Lear, Iago, Othello, the Moor of Venice Othello,' ' the Moor of Venice Group personal message') email_subject = 'Group PMs with Cordelia Lear, Iago, and Othello, the Moor of Venice' self._test_cases(tokens, msg_id, body, email_subject, send_as_user) @patch('zerver.lib.email_mirror.generate_random_token') def _extra_context_in_huddle_missed_stream_messages_many_others(self, send_as_user: bool, mock_random_token: MagicMock) -> None: tokens = self._get_tokens() mock_random_token.side_effect = tokens msg_id = self.send_huddle_message(self.example_email('othello'), [self.example_email('hamlet'), self.example_email('iago'), self.example_email('cordelia'), self.example_email('prospero')], 'Group personal message!') body = ('You and Cordelia Lear, Iago, Othello, the Moor of Venice, Prospero from The Tempest' ' Othello, the Moor of Venice Group personal message') email_subject = 'Group PMs with Cordelia Lear, Iago, and 2 others' self._test_cases(tokens, msg_id, body, email_subject, send_as_user) @patch('zerver.lib.email_mirror.generate_random_token') def _deleted_message_in_missed_stream_messages(self, send_as_user: bool, mock_random_token: MagicMock) -> None: tokens = self._get_tokens() mock_random_token.side_effect = tokens msg_id = self.send_stream_message( self.example_email('othello'), "denmark", '@**King Hamlet** to be deleted') hamlet = self.example_user('hamlet') email = self.example_email('othello') self.login(email) result = self.client_patch('/json/messages/' + str(msg_id), {'message_id': msg_id, 'content': ' '}) self.assert_json_success(result) handle_missedmessage_emails(hamlet.id, [{'message_id': msg_id}]) self.assertEqual(len(mail.outbox), 0) @patch('zerver.lib.email_mirror.generate_random_token') def _deleted_message_in_personal_missed_stream_messages(self, send_as_user: bool, mock_random_token: MagicMock) -> None: tokens = self._get_tokens() mock_random_token.side_effect = tokens msg_id = self.send_personal_message(self.example_email('othello'), self.example_email('hamlet'), 'Extremely personal message! to be deleted!') hamlet = self.example_user('hamlet') email = self.example_email('othello') self.login(email) result = self.client_patch('/json/messages/' + str(msg_id), {'message_id': msg_id, 'content': ' '}) self.assert_json_success(result) handle_missedmessage_emails(hamlet.id, [{'message_id': msg_id}]) self.assertEqual(len(mail.outbox), 0) @patch('zerver.lib.email_mirror.generate_random_token') def _deleted_message_in_huddle_missed_stream_messages(self, send_as_user: bool, mock_random_token: MagicMock) -> None: tokens = self._get_tokens() mock_random_token.side_effect = tokens msg_id = self.send_huddle_message( self.example_email('othello'), [ self.example_email('hamlet'), self.example_email('iago'), ], 'Group personal message!', ) hamlet = self.example_user('hamlet') iago = self.example_user('iago') email = self.example_email('othello') self.login(email) result = self.client_patch('/json/messages/' + str(msg_id), {'message_id': msg_id, 'content': ' '}) self.assert_json_success(result) handle_missedmessage_emails(hamlet.id, [{'message_id': msg_id}]) self.assertEqual(len(mail.outbox), 0) handle_missedmessage_emails(iago.id, [{'message_id': msg_id}]) self.assertEqual(len(mail.outbox), 0) def test_realm_name_in_notifications(self) -> None: # Test with realm_name_in_notifications for hamlet disabled. self._realm_name_in_missed_message_email_subject(False) # Enable realm_name_in_notifications for hamlet and test again. hamlet = self.example_user('hamlet') hamlet.realm_name_in_notifications = True hamlet.save(update_fields=['realm_name_in_notifications']) # Empty the test outbox mail.outbox = [] self._realm_name_in_missed_message_email_subject(True) def test_message_content_disabled_in_missed_message_notifications(self) -> None: # Test when user disabled message content in email notifications. do_change_notification_settings(self.example_user("hamlet"), "message_content_in_email_notifications", False) self._extra_context_in_missed_stream_messages_mention(False, show_message_content=False) mail.outbox = [] self._extra_context_in_personal_missed_stream_messages(False, show_message_content=False) mail.outbox = [] self._extra_context_in_huddle_missed_stream_messages_two_others(False, show_message_content=False) @override_settings(SEND_MISSED_MESSAGE_EMAILS_AS_USER=True) def test_extra_context_in_missed_stream_messages_as_user(self) -> None: self._extra_context_in_missed_stream_messages_mention(True) def test_extra_context_in_missed_stream_messages(self) -> None: self._extra_context_in_missed_stream_messages_mention(False) @override_settings(SEND_MISSED_MESSAGE_EMAILS_AS_USER=True) def test_extra_context_in_missed_stream_messages_as_user_two_senders(self) -> None: self._extra_context_in_missed_stream_messages_mention_two_senders(True) def test_extra_context_in_missed_stream_messages_two_senders(self) -> None: self._extra_context_in_missed_stream_messages_mention_two_senders(False) def test_reply_to_email_in_personal_missed_stream_messages(self) -> None: self._reply_to_email_in_personal_missed_stream_messages(False) @override_settings(SEND_MISSED_MESSAGE_EMAILS_AS_USER=True) def test_extra_context_in_missed_stream_messages_email_notify_as_user(self) -> None: self._extra_context_in_missed_stream_messages_email_notify(True) def test_extra_context_in_missed_stream_messages_email_notify(self) -> None: self._extra_context_in_missed_stream_messages_email_notify(False) @override_settings(EMAIL_GATEWAY_PATTERN="") def test_reply_warning_in_personal_missed_stream_messages(self) -> None: self._reply_warning_in_personal_missed_stream_messages(False) @override_settings(SEND_MISSED_MESSAGE_EMAILS_AS_USER=True) def test_extra_context_in_personal_missed_stream_messages_as_user(self) -> None: self._extra_context_in_personal_missed_stream_messages(True) def test_extra_context_in_personal_missed_stream_messages(self) -> None: self._extra_context_in_personal_missed_stream_messages(False) @override_settings(SEND_MISSED_MESSAGE_EMAILS_AS_USER=True) def test_extra_context_in_huddle_missed_stream_messages_two_others_as_user(self) -> None: self._extra_context_in_huddle_missed_stream_messages_two_others(True) def test_extra_context_in_huddle_missed_stream_messages_two_others(self) -> None: self._extra_context_in_huddle_missed_stream_messages_two_others(False) @override_settings(SEND_MISSED_MESSAGE_EMAILS_AS_USER=True) def test_extra_context_in_huddle_missed_stream_messages_three_others_as_user(self) -> None: self._extra_context_in_huddle_missed_stream_messages_three_others(True) def test_extra_context_in_huddle_missed_stream_messages_three_others(self) -> None: self._extra_context_in_huddle_missed_stream_messages_three_others(False) @override_settings(SEND_MISSED_MESSAGE_EMAILS_AS_USER=True) def test_extra_context_in_huddle_missed_stream_messages_many_others_as_user(self) -> None: self._extra_context_in_huddle_missed_stream_messages_many_others(True) def test_extra_context_in_huddle_missed_stream_messages_many_others(self) -> None: self._extra_context_in_huddle_missed_stream_messages_many_others(False) @override_settings(SEND_MISSED_MESSAGE_EMAILS_AS_USER=True) def test_deleted_message_in_missed_stream_messages_as_user(self) -> None: self._deleted_message_in_missed_stream_messages(True) def test_deleted_message_in_missed_stream_messages(self) -> None: self._deleted_message_in_missed_stream_messages(False) @override_settings(SEND_MISSED_MESSAGE_EMAILS_AS_USER=True) def test_deleted_message_in_personal_missed_stream_messages_as_user(self) -> None: self._deleted_message_in_personal_missed_stream_messages(True) def test_deleted_message_in_personal_missed_stream_messages(self) -> None: self._deleted_message_in_personal_missed_stream_messages(False) @override_settings(SEND_MISSED_MESSAGE_EMAILS_AS_USER=True) def test_deleted_message_in_huddle_missed_stream_messages_as_user(self) -> None: self._deleted_message_in_huddle_missed_stream_messages(True) def test_deleted_message_in_huddle_missed_stream_messages(self) -> None: self._deleted_message_in_huddle_missed_stream_messages(False) @patch('zerver.lib.email_mirror.generate_random_token') def test_realm_emoji_in_missed_message(self, mock_random_token: MagicMock) -> None: tokens = self._get_tokens() mock_random_token.side_effect = tokens msg_id = self.send_personal_message( self.example_email('othello'), self.example_email('hamlet'), 'Extremely personal message with a realm emoji :green_tick:!') realm_emoji_id = get_realm('zulip').get_active_emoji()['green_tick']['id'] realm_emoji_url = "http://zulip.testserver/user_avatars/1/emoji/images/%s.png" % (realm_emoji_id,) body = '<img alt=":green_tick:" src="%s" title="green tick" style="height: 20px;">' % (realm_emoji_url,) email_subject = 'Othello, the Moor of Venice sent you a message' self._test_cases(tokens, msg_id, body, email_subject, send_as_user=False, verify_html_body=True) @patch('zerver.lib.email_mirror.generate_random_token') def test_emojiset_in_missed_message(self, mock_random_token: MagicMock) -> None: tokens = self._get_tokens() mock_random_token.side_effect = tokens hamlet = self.example_user('hamlet') hamlet.emojiset = 'apple' hamlet.save(update_fields=['emojiset']) msg_id = self.send_personal_message( self.example_email('othello'), self.example_email('hamlet'), 'Extremely personal message with a hamburger :hamburger:!') body = '<img alt=":hamburger:" src="http://zulip.testserver/static/generated/emoji/images-apple-64/1f354.png" title="hamburger" style="height: 20px;">' email_subject = 'Othello, the Moor of Venice sent you a message' self._test_cases(tokens, msg_id, body, email_subject, send_as_user=False, verify_html_body=True) @patch('zerver.lib.email_mirror.generate_random_token') def test_stream_link_in_missed_message(self, mock_random_token: MagicMock) -> None: tokens = self._get_tokens() mock_random_token.side_effect = tokens msg_id = self.send_personal_message( self.example_email('othello'), self.example_email('hamlet'), 'Come and join us in #**Verona**.') stream_id = get_stream('Verona', get_realm('zulip')).id href = "http://zulip.testserver/#narrow/stream/{stream_id}-Verona".format(stream_id=stream_id) body = '<a class="stream" data-stream-id="5" href="{href}">#Verona</a'.format(href=href) email_subject = 'Othello, the Moor of Venice sent you a message' self._test_cases(tokens, msg_id, body, email_subject, send_as_user=False, verify_html_body=True) @patch('zerver.lib.email_mirror.generate_random_token') def test_multiple_missed_personal_messages(self, mock_random_token: MagicMock) -> None: tokens = self._get_tokens() mock_random_token.side_effect = tokens hamlet = self.example_user('hamlet') msg_id_1 = self.send_personal_message(self.example_email('othello'), hamlet.email, 'Personal Message 1') msg_id_2 = self.send_personal_message(self.example_email('iago'), hamlet.email, 'Personal Message 2') handle_missedmessage_emails(hamlet.id, [ {'message_id': msg_id_1}, {'message_id': msg_id_2}, ]) self.assertEqual(len(mail.outbox), 2) email_subject = 'Othello, the Moor of Venice sent you a message' self.assertEqual(mail.outbox[0].subject, email_subject) email_subject = 'Iago sent you a message' self.assertEqual(mail.outbox[1].subject, email_subject) @patch('zerver.lib.email_mirror.generate_random_token') def test_multiple_stream_messages(self, mock_random_token: MagicMock) -> None: tokens = self._get_tokens() mock_random_token.side_effect = tokens hamlet = self.example_user('hamlet') msg_id_1 = self.send_stream_message(self.example_email('othello'), "Denmark", 'Message1') msg_id_2 = self.send_stream_message(self.example_email('iago'), "Denmark", 'Message2') handle_missedmessage_emails(hamlet.id, [ {'message_id': msg_id_1, "trigger": "stream_email_notify"}, {'message_id': msg_id_2, "trigger": "stream_email_notify"}, ]) self.assertEqual(len(mail.outbox), 1) email_subject = 'New messages in Denmark > test' self.assertEqual(mail.outbox[0].subject, email_subject) @patch('zerver.lib.email_mirror.generate_random_token') def test_multiple_stream_messages_and_mentions(self, mock_random_token: MagicMock) -> None: """A mention should take precedence over regular stream messages for email subjects.""" tokens = self._get_tokens() mock_random_token.side_effect = tokens hamlet = self.example_user('hamlet') msg_id_1 = self.send_stream_message(self.example_email('iago'), "Denmark", 'Regular message') msg_id_2 = self.send_stream_message(self.example_email('othello'), "Denmark", '@**King Hamlet**') handle_missedmessage_emails(hamlet.id, [ {'message_id': msg_id_1, "trigger": "stream_email_notify"}, {'message_id': msg_id_2, "trigger": "mentioned"}, ]) self.assertEqual(len(mail.outbox), 1) email_subject = 'Othello, the Moor of Venice mentioned you' self.assertEqual(mail.outbox[0].subject, email_subject) @patch('zerver.lib.email_mirror.generate_random_token') def test_message_access_in_emails(self, mock_random_token: MagicMock) -> None: # Messages sent to a protected history-private stream shouldn't be # accessible/available in emails before subscribing tokens = self._get_tokens() mock_random_token.side_effect = tokens stream_name = "private_stream" self.make_stream(stream_name, invite_only=True, history_public_to_subscribers=False) user = self.example_user('iago') self.subscribe(user, stream_name) late_subscribed_user = self.example_user('hamlet') self.send_stream_message(user.email, stream_name, 'Before subscribing') self.subscribe(late_subscribed_user, stream_name) self.send_stream_message(user.email, stream_name, "After subscribing") mention_msg_id = self.send_stream_message(user.email, stream_name, '@**King Hamlet**') handle_missedmessage_emails(late_subscribed_user.id, [ {'message_id': mention_msg_id, "trigger": "mentioned"}, ]) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, 'Iago mentioned you') # email subject email_text = mail.outbox[0].message().as_string() self.assertNotIn('Before subscribing', email_text) self.assertIn('After subscribing', email_text) self.assertIn('@**King Hamlet**', email_text) @patch('zerver.lib.email_mirror.generate_random_token') def test_stream_mentions_multiple_people(self, mock_random_token: MagicMock) -> None: """A mention should take precedence over regular stream messages for email subjects. Each sender who has mentioned a user should appear in the email subject line. """ tokens = self._get_tokens() mock_random_token.side_effect = tokens hamlet = self.example_user('hamlet') msg_id_1 = self.send_stream_message(self.example_email('iago'), "Denmark", '@**King Hamlet**') msg_id_2 = self.send_stream_message(self.example_email('othello'), "Denmark", '@**King Hamlet**') msg_id_3 = self.send_stream_message(self.example_email('cordelia'), "Denmark", 'Regular message') handle_missedmessage_emails(hamlet.id, [ {'message_id': msg_id_1, "trigger": "mentioned"}, {'message_id': msg_id_2, "trigger": "mentioned"}, {'message_id': msg_id_3, "trigger": "stream_email_notify"}, ]) self.assertEqual(len(mail.outbox), 1) email_subject = 'Iago, Othello, the Moor of Venice mentioned you' self.assertEqual(mail.outbox[0].subject, email_subject) @patch('zerver.lib.email_mirror.generate_random_token') def test_multiple_stream_messages_different_topics(self, mock_random_token: MagicMock) -> None: """Should receive separate emails for each topic within a stream.""" tokens = self._get_tokens() mock_random_token.side_effect = tokens hamlet = self.example_user('hamlet') msg_id_1 = self.send_stream_message(self.example_email('othello'), "Denmark", 'Message1') msg_id_2 = self.send_stream_message(self.example_email('iago'), "Denmark", 'Message2', topic_name="test2") handle_missedmessage_emails(hamlet.id, [ {'message_id': msg_id_1, "trigger": "stream_email_notify"}, {'message_id': msg_id_2, "trigger": "stream_email_notify"}, ]) self.assertEqual(len(mail.outbox), 2) email_subjects = {mail.outbox[0].subject, mail.outbox[1].subject} valid_email_subjects = {'New messages in Denmark > test', 'New messages in Denmark > test2'} self.assertEqual(email_subjects, valid_email_subjects) def test_relative_to_full_url(self) -> None: # Run `relative_to_full_url()` function over test fixtures present in # 'markdown_test_cases.json' and check that it converts all the relative # URLs to absolute URLs. fixtures = ujson.loads(self.fixture_data("markdown_test_cases.json")) test_fixtures = {} for test in fixtures['regular_tests']: test_fixtures[test['name']] = test for test_name in test_fixtures: test_data = test_fixtures[test_name]["expected_output"] output_data = relative_to_full_url("http://example.com", test_data) if re.search(r"""(?<=\=['"])/(?=[^<]+>)""", output_data) is not None: raise AssertionError("Relative URL present in email: " + output_data + "\nFailed test case's name is: " + test_name + "\nIt is present in markdown_test_cases.json") # Specific test cases. # A path similar to our emoji path, but not in a link: test_data = "<p>Check out the file at: '/static/generated/emoji/images/emoji/'</p>" actual_output = relative_to_full_url("http://example.com", test_data) expected_output = "<p>Check out the file at: '/static/generated/emoji/images/emoji/'</p>" self.assertEqual(actual_output, expected_output) # An uploaded file test_data = '<a href="/user_uploads/2/1f/some_random_value">/user_uploads/2/1f/some_random_value</a>' actual_output = relative_to_full_url("http://example.com", test_data) expected_output = '<a href="http://example.com/user_uploads/2/1f/some_random_value">' + \ '/user_uploads/2/1f/some_random_value</a>' self.assertEqual(actual_output, expected_output) # A user avatar like syntax, but not actually in an HTML tag test_data = '<p>Set src="/avatar/username@example.com?s=30"</p>' actual_output = relative_to_full_url("http://example.com", test_data) expected_output = '<p>Set src="/avatar/username@example.com?s=30"</p>' self.assertEqual(actual_output, expected_output) # A narrow URL which begins with a '#'. test_data = '<p><a href="#narrow/stream/test/topic/test.20topic/near/142"' + \ 'title="#narrow/stream/test/topic/test.20topic/near/142">Conversation</a></p>' actual_output = relative_to_full_url("http://example.com", test_data) expected_output = '<p><a href="http://example.com/#narrow/stream/test/topic/test.20topic/near/142" ' + \ 'title="http://example.com/#narrow/stream/test/topic/test.20topic/near/142">Conversation</a></p>' self.assertEqual(actual_output, expected_output) # Scrub inline images. test_data = '<p>See this <a href="/user_uploads/1/52/fG7GM9e3afz_qsiUcSce2tl_/avatar_103.jpeg" target="_blank" ' + \ 'title="avatar_103.jpeg">avatar_103.jpeg</a>.</p>' + \ '<div class="message_inline_image"><a href="/user_uploads/1/52/fG7GM9e3afz_qsiUcSce2tl_/avatar_103.jpeg" ' + \ 'target="_blank" title="avatar_103.jpeg"><img src="/user_uploads/1/52/fG7GM9e3afz_qsiUcSce2tl_/avatar_103.jpeg"></a></div>' actual_output = relative_to_full_url("http://example.com", test_data) expected_output = '<div><p>See this <a href="http://example.com/user_uploads/1/52/fG7GM9e3afz_qsiUcSce2tl_/avatar_103.jpeg" target="_blank" ' + \ 'title="avatar_103.jpeg">avatar_103.jpeg</a>.</p></div>' self.assertEqual(actual_output, expected_output) # A message containing only an inline image URL preview, we do # somewhat more extensive surgery. test_data = '<div class="message_inline_image"><a href="https://www.google.com/images/srpr/logo4w.png" ' + \ 'target="_blank" title="https://www.google.com/images/srpr/logo4w.png">' + \ '<img data-src-fullsize="/thumbnail/https%3A//www.google.com/images/srpr/logo4w.png?size=0x0" ' + \ 'src="/thumbnail/https%3A//www.google.com/images/srpr/logo4w.png?size=0x100"></a></div>' actual_output = relative_to_full_url("http://example.com", test_data) expected_output = '<p><a href="https://www.google.com/images/srpr/logo4w.png" ' + \ 'target="_blank" title="https://www.google.com/images/srpr/logo4w.png">' + \ 'https://www.google.com/images/srpr/logo4w.png</a></p>' self.assertEqual(actual_output, expected_output) def test_fix_emoji(self) -> None: # An emoji. test_data = '<p>See <span class="emoji emoji-26c8" title="cloud with lightning and rain">' + \ ':cloud_with_lightning_and_rain:</span>.</p>' actual_output = fix_emojis(test_data, "http://example.com", "google") expected_output = '<p>See <img alt=":cloud_with_lightning_and_rain:" src="http://example.com/static/generated/emoji/images-google-64/26c8.png" ' + \ 'title="cloud with lightning and rain" style="height: 20px;">.</p>' self.assertEqual(actual_output, expected_output)
[ "str", "List[str]", "int", "str", "str", "bool", "bool", "MagicMock", "bool", "MagicMock", "bool", "MagicMock", "bool", "MagicMock", "bool", "MagicMock", "bool", "MagicMock", "bool", "MagicMock", "bool", "MagicMock", "bool", "MagicMock", "bool", "MagicMock", "bool", "MagicMock", "bool", "MagicMock", "bool", "MagicMock", "MagicMock", "MagicMock", "MagicMock", "MagicMock", "MagicMock", "MagicMock", "MagicMock", "MagicMock", "MagicMock" ]
[ 4767, 4980, 4999, 5010, 5030, 5069, 6803, 6880, 7659, 7741, 9524, 9611, 10493, 10518, 11270, 11353, 12704, 12788, 13409, 13492, 14140, 14232, 15805, 15899, 16771, 16864, 17862, 17938, 18747, 18832, 19735, 19818, 26241, 27145, 28033, 28878, 29992, 31019, 32145, 33866, 35368 ]
[ 4770, 4989, 5002, 5013, 5033, 5073, 6807, 6889, 7663, 7750, 9528, 9620, 10497, 10527, 11274, 11362, 12708, 12797, 13413, 13501, 14144, 14241, 15809, 15908, 16775, 16873, 17866, 17947, 18751, 18841, 19739, 19827, 26250, 27154, 28042, 28887, 30001, 31028, 32154, 33875, 35377 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_onboarding.py
# -*- coding: utf-8 -*- from zerver.models import Realm, UserProfile from zerver.lib.onboarding import create_if_missing_realm_internal_bots from zerver.lib.test_classes import ( ZulipTestCase, ) class TestRealmInternalBotCreation(ZulipTestCase): def test_create_if_missing_realm_internal_bots(self) -> None: realm_internal_bots_dict = [{'var_name': 'TEST_BOT', 'email_template': 'test-bot@%s', 'name': 'Test Bot'}] def check_test_bot_exists() -> bool: all_realms_count = Realm.objects.count() all_test_bot_count = UserProfile.objects.filter( email='test-bot@zulip.com' ).count() return all_realms_count == all_test_bot_count self.assertFalse(check_test_bot_exists()) with self.settings(REALM_INTERNAL_BOTS=realm_internal_bots_dict): create_if_missing_realm_internal_bots() self.assertTrue(check_test_bot_exists())
[]
[]
[]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_openapi.py
# -*- coding: utf-8 -*- import mock from typing import Dict, Any import zerver.lib.openapi as openapi from zerver.lib.test_classes import ZulipTestCase from zerver.lib.openapi import ( get_openapi_fixture, get_openapi_parameters, validate_against_openapi_schema, to_python_type, SchemaError, openapi_spec ) TEST_ENDPOINT = '/messages/{message_id}' TEST_METHOD = 'patch' TEST_RESPONSE_BAD_REQ = '400' TEST_RESPONSE_SUCCESS = '200' class OpenAPIToolsTest(ZulipTestCase): """Make sure that the tools we use to handle our OpenAPI specification (located in zerver/lib/openapi.py) work as expected. These tools are mostly dedicated to fetching parts of the -already parsed- specification, and comparing them to objects returned by our REST API. """ def test_get_openapi_fixture(self) -> None: actual = get_openapi_fixture(TEST_ENDPOINT, TEST_METHOD, TEST_RESPONSE_BAD_REQ) expected = { 'code': 'BAD_REQUEST', 'msg': 'You don\'t have permission to edit this message', 'result': 'error' } self.assertEqual(actual, expected) def test_get_openapi_parameters(self) -> None: actual = get_openapi_parameters(TEST_ENDPOINT, TEST_METHOD) expected_item = { 'name': 'message_id', 'in': 'path', 'description': 'The ID of the message that you wish to edit/update.', 'example': 42, 'required': True, 'schema': {'type': 'integer'} } assert(expected_item in actual) def test_validate_against_openapi_schema(self) -> None: with self.assertRaises(SchemaError, msg=('Extraneous key "foo" in ' 'the response\'scontent')): bad_content = { 'msg': '', 'result': 'success', 'foo': 'bar' } # type: Dict[str, Any] validate_against_openapi_schema(bad_content, TEST_ENDPOINT, TEST_METHOD, TEST_RESPONSE_SUCCESS) with self.assertRaises(SchemaError, msg=("Expected type <class 'str'> for key " "\"msg\", but actually got " "<class 'int'>")): bad_content = { 'msg': 42, 'result': 'success', } validate_against_openapi_schema(bad_content, TEST_ENDPOINT, TEST_METHOD, TEST_RESPONSE_SUCCESS) with self.assertRaises(SchemaError, msg='Expected to find the "msg" required key'): bad_content = { 'result': 'success', } validate_against_openapi_schema(bad_content, TEST_ENDPOINT, TEST_METHOD, TEST_RESPONSE_SUCCESS) # No exceptions should be raised here. good_content = { 'msg': '', 'result': 'success', } validate_against_openapi_schema(good_content, TEST_ENDPOINT, TEST_METHOD, TEST_RESPONSE_SUCCESS) # Overwrite the exception list with a mocked one openapi.EXCLUDE_PROPERTIES = { TEST_ENDPOINT: { TEST_METHOD: { TEST_RESPONSE_SUCCESS: ['foo'] } } } good_content = { 'msg': '', 'result': 'success', 'foo': 'bar' } validate_against_openapi_schema(good_content, TEST_ENDPOINT, TEST_METHOD, TEST_RESPONSE_SUCCESS) def test_to_python_type(self) -> None: TYPES = { 'string': str, 'number': float, 'integer': int, 'boolean': bool, 'array': list, 'object': dict } for oa_type, py_type in TYPES.items(): self.assertEqual(to_python_type(oa_type), py_type) def test_live_reload(self) -> None: # Force the reload by making the last update date < the file's last # modified date openapi_spec.last_update = 0 get_openapi_fixture(TEST_ENDPOINT, TEST_METHOD) # Check that the file has been reloaded by verifying that the last # update date isn't zero anymore self.assertNotEqual(openapi_spec.last_update, 0) # Now verify calling it again doesn't call reload with mock.patch('zerver.lib.openapi.openapi_spec.reload') as mock_reload: get_openapi_fixture(TEST_ENDPOINT, TEST_METHOD) self.assertFalse(mock_reload.called)
[]
[]
[]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_outgoing_webhook_interfaces.py
# -*- coding: utf-8 -*- from typing import cast, Any, Dict import mock import json import requests from zerver.lib.outgoing_webhook import ( get_service_interface_class, process_success_response, ) from zerver.lib.test_classes import ZulipTestCase from zerver.lib.topic import TOPIC_NAME from zerver.models import Service, get_realm, get_user, SLACK_INTERFACE class TestGenericOutgoingWebhookService(ZulipTestCase): def setUp(self) -> None: self.event = { u'command': '@**test**', u'message': { 'content': '@**test**', }, u'trigger': 'mention', } self.bot_user = get_user("outgoing-webhook@zulip.com", get_realm("zulip")) service_class = get_service_interface_class('whatever') # GenericOutgoingWebhookService self.handler = service_class(service_name='test-service', token='abcdef', user_profile=self.bot_user) def test_process_success_response(self) -> None: class Stub: def __init__(self, text: str) -> None: self.text = text # type: ignore def make_response(text: str) -> requests.Response: return cast(requests.Response, Stub(text=text)) event = dict( user_profile_id=99, message=dict(type='private') ) service_handler = self.handler response = make_response(text=json.dumps(dict(content='whatever'))) with mock.patch('zerver.lib.outgoing_webhook.send_response_message') as m: process_success_response( event=event, service_handler=service_handler, response=response, ) self.assertTrue(m.called) response = make_response(text='unparsable text') with mock.patch('zerver.lib.outgoing_webhook.fail_with_message') as m: process_success_response( event=event, service_handler=service_handler, response=response ) self.assertTrue(m.called) def test_build_bot_request(self) -> None: request_data = self.handler.build_bot_request(self.event) request_data = json.loads(request_data) self.assertEqual(request_data['data'], "@**test**") self.assertEqual(request_data['token'], "abcdef") self.assertEqual(request_data['message'], self.event['message']) def test_process_success(self) -> None: response = dict(response_not_required=True) # type: Dict[str, Any] success_response = self.handler.process_success(response, self.event) self.assertEqual(success_response, None) response = dict(response_string='test_content') success_response = self.handler.process_success(response, self.event) self.assertEqual(success_response, dict(content='test_content')) response = dict( content='test_content', widget_content='test_widget_content', red_herring='whatever', ) success_response = self.handler.process_success(response, self.event) expected_response = dict( content='test_content', widget_content='test_widget_content', ) self.assertEqual(success_response, expected_response) response = dict() success_response = self.handler.process_success(response, self.event) self.assertEqual(success_response, None) mock_service = Service() class TestSlackOutgoingWebhookService(ZulipTestCase): def setUp(self) -> None: self.stream_message_event = { u'command': '@**test**', u'user_profile_id': 12, u'service_name': 'test-service', u'trigger': 'mention', u'message': { 'content': 'test_content', 'type': 'stream', 'sender_realm_str': 'zulip', 'sender_email': 'sampleuser@zulip.com', 'stream_id': '123', 'display_recipient': 'integrations', 'timestamp': 123456, 'sender_id': 21, 'sender_full_name': 'Sample User', } } self.private_message_event = { u'user_profile_id': 24, u'service_name': 'test-service', u'command': 'test content', u'trigger': 'private_message', u'message': { 'sender_id': 3, 'sender_realm_str': 'zulip', 'timestamp': 1529821610, 'sender_email': 'cordelia@zulip.com', 'type': 'private', 'sender_realm_id': 1, 'id': 219, TOPIC_NAME: 'test', 'content': 'test content', } } service_class = get_service_interface_class(SLACK_INTERFACE) self.handler = service_class(token="abcdef", user_profile=None, service_name='test-service') def test_build_bot_request_stream_message(self) -> None: request_data = self.handler.build_bot_request(self.stream_message_event) self.assertEqual(request_data[0][1], "abcdef") # token self.assertEqual(request_data[1][1], "zulip") # team_id self.assertEqual(request_data[2][1], "zulip.com") # team_domain self.assertEqual(request_data[3][1], "123") # channel_id self.assertEqual(request_data[4][1], "integrations") # channel_name self.assertEqual(request_data[5][1], 123456) # timestamp self.assertEqual(request_data[6][1], 21) # user_id self.assertEqual(request_data[7][1], "Sample User") # user_name self.assertEqual(request_data[8][1], "@**test**") # text self.assertEqual(request_data[9][1], "mention") # trigger_word self.assertEqual(request_data[10][1], 12) # user_profile_id @mock.patch('zerver.lib.outgoing_webhook.get_service_profile', return_value=mock_service) @mock.patch('zerver.lib.outgoing_webhook.fail_with_message') def test_build_bot_request_private_message(self, mock_fail_with_message: mock.Mock, mock_get_service_profile: mock.Mock) -> None: request_data = self.handler.build_bot_request(self.private_message_event) self.assertIsNone(request_data) self.assertTrue(mock_fail_with_message.called) def test_process_success(self) -> None: response = dict(response_not_required=True) # type: Dict[str, Any] success_response = self.handler.process_success(response, self.stream_message_event) self.assertEqual(success_response, None) response = dict(text='test_content') success_response = self.handler.process_success(response, self.stream_message_event) self.assertEqual(success_response, dict(content='test_content'))
[ "str", "str", "mock.Mock", "mock.Mock" ]
[ 1118, 1214, 6254, 6338 ]
[ 1121, 1217, 6263, 6347 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_outgoing_webhook_system.py
# -*- coding: utf-8 -*- import ujson import logging import mock import requests from builtins import object from django.test import override_settings from requests import Response from typing import Any, Dict, Tuple, Optional from zerver.lib.outgoing_webhook import ( do_rest_call, GenericOutgoingWebhookService, SlackOutgoingWebhookService, ) from zerver.lib.test_classes import ZulipTestCase from zerver.lib.topic import TOPIC_NAME from zerver.models import get_realm, get_user, UserProfile, get_display_recipient class ResponseMock: def __init__(self, status_code: int, content: Optional[Any]=None) -> None: self.status_code = status_code self.content = content self.text = ujson.dumps(content) def request_exception_error(http_method: Any, final_url: Any, data: Any, **request_kwargs: Any) -> Any: raise requests.exceptions.RequestException("I'm a generic exception :(") def timeout_error(http_method: Any, final_url: Any, data: Any, **request_kwargs: Any) -> Any: raise requests.exceptions.Timeout("Time is up!") def connection_error(http_method: Any, final_url: Any, data: Any, **request_kwargs: Any) -> Any: raise requests.exceptions.ConnectionError() service_handler = GenericOutgoingWebhookService(None, None, None) class DoRestCallTests(ZulipTestCase): def setUp(self) -> None: realm = get_realm("zulip") user_profile = get_user("outgoing-webhook@zulip.com", realm) self.mock_event = { # In the tests there is no active queue processor, so retries don't get processed. # Therefore, we need to emulate `retry_event` in the last stage when the maximum # retries have been exceeded. 'failed_tries': 3, 'message': {'display_recipient': 'Verona', 'stream_id': 999, TOPIC_NAME: 'Foo', 'id': '', 'type': 'stream'}, 'user_profile_id': user_profile.id, 'command': '', 'service_name': ''} self.bot_user = self.example_user('outgoing_webhook_bot') logging.disable(logging.WARNING) @mock.patch('zerver.lib.outgoing_webhook.send_response_message') def test_successful_request(self, mock_send: mock.Mock) -> None: response = ResponseMock(200, dict(content='whatever')) with mock.patch('requests.request', return_value=response): do_rest_call('', None, self.mock_event, service_handler) self.assertTrue(mock_send.called) for service_class in [GenericOutgoingWebhookService, SlackOutgoingWebhookService]: handler = service_class(None, None, None) with mock.patch('requests.request', return_value=response): do_rest_call('', None, self.mock_event, handler) self.assertTrue(mock_send.called) def test_retry_request(self: mock.Mock) -> None: response = ResponseMock(500) self.mock_event['failed_tries'] = 3 with mock.patch('requests.request', return_value=response): do_rest_call('', None, self.mock_event, service_handler) bot_owner_notification = self.get_last_message() self.assertEqual(bot_owner_notification.content, '''[A message](http://zulip.testserver/#narrow/stream/999-Verona/topic/Foo/near/) triggered an outgoing webhook. The webhook got a response with status code *500*.''') self.assertEqual(bot_owner_notification.recipient_id, self.bot_user.bot_owner.id) self.mock_event['failed_tries'] = 0 @mock.patch('zerver.lib.outgoing_webhook.fail_with_message') def test_fail_request(self, mock_fail_with_message: mock.Mock) -> None: response = ResponseMock(400) with mock.patch('requests.request', return_value=response): do_rest_call('', None, self.mock_event, service_handler) bot_owner_notification = self.get_last_message() self.assertTrue(mock_fail_with_message.called) self.assertEqual(bot_owner_notification.content, '''[A message](http://zulip.testserver/#narrow/stream/999-Verona/topic/Foo/near/) triggered an outgoing webhook. The webhook got a response with status code *400*.''') self.assertEqual(bot_owner_notification.recipient_id, self.bot_user.bot_owner.id) def test_error_handling(self) -> None: def helper(side_effect: Any, error_text: str) -> None: with mock.patch('logging.info'): with mock.patch('requests.request', side_effect=side_effect): do_rest_call('', None, self.mock_event, service_handler) bot_owner_notification = self.get_last_message() self.assertIn(error_text, bot_owner_notification.content) self.assertIn('triggered', bot_owner_notification.content) self.assertEqual(bot_owner_notification.recipient_id, self.bot_user.bot_owner.id) helper(side_effect=timeout_error, error_text='A timeout occurred.') helper(side_effect=connection_error, error_text='A connection error occurred.') @mock.patch('logging.exception') @mock.patch('requests.request', side_effect=request_exception_error) @mock.patch('zerver.lib.outgoing_webhook.fail_with_message') def test_request_exception(self, mock_fail_with_message: mock.Mock, mock_requests_request: mock.Mock, mock_logger: mock.Mock) -> None: do_rest_call('', None, self.mock_event, service_handler) bot_owner_notification = self.get_last_message() self.assertTrue(mock_fail_with_message.called) self.assertEqual(bot_owner_notification.content, '''[A message](http://zulip.testserver/#narrow/stream/999-Verona/topic/Foo/near/) triggered an outgoing webhook. When trying to send a request to the webhook service, an exception of type RequestException occurred: ``` I'm a generic exception :( ```''') self.assertEqual(bot_owner_notification.recipient_id, self.bot_user.bot_owner.id) class TestOutgoingWebhookMessaging(ZulipTestCase): def setUp(self) -> None: self.user_profile = self.example_user("othello") self.bot_profile = self.create_test_bot('outgoing-webhook', self.user_profile, full_name='Outgoing Webhook bot', bot_type=UserProfile.OUTGOING_WEBHOOK_BOT, service_name='foo-service') @mock.patch('requests.request', return_value=ResponseMock(200, {"response_string": "Hidley ho, I'm a webhook responding!"})) def test_pm_to_outgoing_webhook_bot(self, mock_requests_request: mock.Mock) -> None: self.send_personal_message(self.user_profile.email, self.bot_profile.email, content="foo") last_message = self.get_last_message() self.assertEqual(last_message.content, "Hidley ho, I'm a webhook responding!") self.assertEqual(last_message.sender_id, self.bot_profile.id) display_recipient = get_display_recipient(last_message.recipient) # The next two lines error on mypy because the display_recipient is of type Union[str, List[Dict[str, Any]]]. # In this case, we know that display_recipient will be of type List[Dict[str, Any]]. # Otherwise this test will error, which is wanted behavior anyway. self.assert_length(display_recipient, 1) # type: ignore self.assertEqual(display_recipient[0]['email'], self.user_profile.email) # type: ignore @mock.patch('requests.request', return_value=ResponseMock(200, {"response_string": "Hidley ho, I'm a webhook responding!"})) def test_stream_message_to_outgoing_webhook_bot(self, mock_requests_request: mock.Mock) -> None: self.send_stream_message(self.user_profile.email, "Denmark", content="@**{}** foo".format(self.bot_profile.full_name), topic_name="bar") last_message = self.get_last_message() self.assertEqual(last_message.content, "Hidley ho, I'm a webhook responding!") self.assertEqual(last_message.sender_id, self.bot_profile.id) self.assertEqual(last_message.topic_name(), "bar") display_recipient = get_display_recipient(last_message.recipient) self.assertEqual(display_recipient, "Denmark")
[ "int", "Any", "Any", "Any", "Any", "Any", "Any", "Any", "Any", "Any", "Any", "Any", "Any", "mock.Mock", "mock.Mock", "mock.Mock", "Any", "str", "mock.Mock", "mock.Mock", "mock.Mock", "mock.Mock", "mock.Mock" ]
[ 589, 785, 801, 812, 835, 957, 973, 984, 1007, 1108, 1124, 1135, 1158, 2298, 2931, 3750, 4492, 4509, 5453, 5518, 5542, 6838, 7930 ]
[ 592, 788, 804, 815, 838, 960, 976, 987, 1010, 1111, 1127, 1138, 1161, 2307, 2940, 3759, 4495, 4512, 5462, 5527, 5551, 6847, 7939 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_presence.py
# -*- coding: utf-8 -*- from datetime import timedelta from django.http import HttpResponse from django.test import override_settings from django.utils.timezone import now as timezone_now import mock from typing import Any, Dict from zerver.lib.actions import do_deactivate_user from zerver.lib.statistics import seconds_usage_between from zerver.lib.test_helpers import ( make_client, queries_captured, ) from zerver.lib.test_classes import ( ZulipTestCase, ) from zerver.lib.timestamp import datetime_to_timestamp from zerver.models import ( email_to_domain, Client, PushDeviceToken, UserActivity, UserActivityInterval, UserProfile, UserPresence, flush_per_request_caches, get_realm, ) import datetime class ActivityTest(ZulipTestCase): @mock.patch("stripe.Customer.list", return_value=[]) def test_activity(self, unused_mock: mock.Mock) -> None: self.login(self.example_email("hamlet")) client, _ = Client.objects.get_or_create(name='website') query = '/json/users/me/pointer' last_visit = timezone_now() count = 150 for activity_user_profile in UserProfile.objects.all(): UserActivity.objects.get_or_create( user_profile=activity_user_profile, client=client, query=query, count=count, last_visit=last_visit ) # Fails when not staff result = self.client_get('/activity') self.assertEqual(result.status_code, 302) user_profile = self.example_user("hamlet") user_profile.is_staff = True user_profile.save() flush_per_request_caches() with queries_captured() as queries: result = self.client_get('/activity') self.assertEqual(result.status_code, 200) self.assert_length(queries, 13) flush_per_request_caches() with queries_captured() as queries: result = self.client_get('/realm_activity/zulip/') self.assertEqual(result.status_code, 200) self.assert_length(queries, 9) flush_per_request_caches() with queries_captured() as queries: result = self.client_get('/user_activity/iago@zulip.com/') self.assertEqual(result.status_code, 200) self.assert_length(queries, 5) class TestClientModel(ZulipTestCase): def test_client_stringification(self) -> None: ''' This test is designed to cover __str__ method for Client. ''' client = make_client('some_client') self.assertEqual(str(client), '<Client: some_client>') class UserPresenceModelTests(ZulipTestCase): def test_date_logic(self) -> None: UserPresence.objects.all().delete() user_profile = self.example_user('hamlet') email = user_profile.email presence_dct = UserPresence.get_status_dict_by_realm(user_profile.realm_id) self.assertEqual(len(presence_dct), 0) self.login(email) result = self.client_post("/json/users/me/presence", {'status': 'active'}) self.assert_json_success(result) presence_dct = UserPresence.get_status_dict_by_realm(user_profile.realm_id) self.assertEqual(len(presence_dct), 1) self.assertEqual(presence_dct[email]['website']['status'], 'active') def back_date(num_weeks: int) -> None: user_presence = UserPresence.objects.filter(user_profile=user_profile)[0] user_presence.timestamp = timezone_now() - datetime.timedelta(weeks=num_weeks) user_presence.save() # Simulate the presence being a week old first. Nothing should change. back_date(num_weeks=1) presence_dct = UserPresence.get_status_dict_by_realm(user_profile.realm_id) self.assertEqual(len(presence_dct), 1) # If the UserPresence row is three weeks old, we ignore it. back_date(num_weeks=3) presence_dct = UserPresence.get_status_dict_by_realm(user_profile.realm_id) self.assertEqual(len(presence_dct), 0) def test_push_tokens(self) -> None: UserPresence.objects.all().delete() user_profile = self.example_user('hamlet') email = user_profile.email self.login(email) result = self.client_post("/json/users/me/presence", {'status': 'active'}) self.assert_json_success(result) def pushable() -> bool: presence_dct = UserPresence.get_status_dict_by_realm(user_profile.realm_id) self.assertEqual(len(presence_dct), 1) return presence_dct[email]['website']['pushable'] self.assertFalse(pushable()) user_profile.enable_offline_push_notifications = True user_profile.save() self.assertFalse(pushable()) PushDeviceToken.objects.create( user=user_profile, kind=PushDeviceToken.APNS ) self.assertTrue(pushable()) class UserPresenceTests(ZulipTestCase): def test_invalid_presence(self) -> None: email = self.example_email("hamlet") self.login(email) result = self.client_post("/json/users/me/presence", {'status': 'foo'}) self.assert_json_error(result, 'Invalid status: foo') def test_set_idle(self) -> None: email = self.example_email("hamlet") self.login(email) client = 'website' result = self.client_post("/json/users/me/presence", {'status': 'idle'}) self.assert_json_success(result) json = result.json() self.assertEqual(json['presences'][email][client]['status'], 'idle') self.assertIn('timestamp', json['presences'][email][client]) self.assertIsInstance(json['presences'][email][client]['timestamp'], int) self.assertEqual(list(json['presences'].keys()), [self.example_email("hamlet")]) timestamp = json['presences'][email][client]['timestamp'] email = self.example_email("othello") self.login(email) result = self.client_post("/json/users/me/presence", {'status': 'idle'}) json = result.json() self.assertEqual(json['presences'][email][client]['status'], 'idle') self.assertEqual(json['presences'][self.example_email("hamlet")][client]['status'], 'idle') self.assertEqual(sorted(json['presences'].keys()), [self.example_email("hamlet"), self.example_email("othello")]) newer_timestamp = json['presences'][email][client]['timestamp'] self.assertGreaterEqual(newer_timestamp, timestamp) def test_set_active(self) -> None: self.login(self.example_email("hamlet")) client = 'website' result = self.client_post("/json/users/me/presence", {'status': 'idle'}) self.assert_json_success(result) self.assertEqual(result.json()['presences'][self.example_email("hamlet")][client]['status'], 'idle') email = self.example_email("othello") self.login(self.example_email("othello")) result = self.client_post("/json/users/me/presence", {'status': 'idle'}) self.assert_json_success(result) json = result.json() self.assertEqual(json['presences'][email][client]['status'], 'idle') self.assertEqual(json['presences'][self.example_email("hamlet")][client]['status'], 'idle') result = self.client_post("/json/users/me/presence", {'status': 'active'}) self.assert_json_success(result) json = result.json() self.assertEqual(json['presences'][email][client]['status'], 'active') self.assertEqual(json['presences'][self.example_email("hamlet")][client]['status'], 'idle') @mock.patch("stripe.Customer.list", return_value=[]) def test_new_user_input(self, unused_mock: mock.Mock) -> None: """Mostly a test for UserActivityInterval""" user_profile = self.example_user("hamlet") self.login(self.example_email("hamlet")) self.assertEqual(UserActivityInterval.objects.filter(user_profile=user_profile).count(), 0) time_zero = timezone_now().replace(microsecond=0) with mock.patch('zerver.views.presence.timezone_now', return_value=time_zero): result = self.client_post("/json/users/me/presence", {'status': 'active', 'new_user_input': 'true'}) self.assert_json_success(result) self.assertEqual(UserActivityInterval.objects.filter(user_profile=user_profile).count(), 1) interval = UserActivityInterval.objects.get(user_profile=user_profile) self.assertEqual(interval.start, time_zero) self.assertEqual(interval.end, time_zero + UserActivityInterval.MIN_INTERVAL_LENGTH) second_time = time_zero + timedelta(seconds=600) # Extent the interval with mock.patch('zerver.views.presence.timezone_now', return_value=second_time): result = self.client_post("/json/users/me/presence", {'status': 'active', 'new_user_input': 'true'}) self.assert_json_success(result) self.assertEqual(UserActivityInterval.objects.filter(user_profile=user_profile).count(), 1) interval = UserActivityInterval.objects.get(user_profile=user_profile) self.assertEqual(interval.start, time_zero) self.assertEqual(interval.end, second_time + UserActivityInterval.MIN_INTERVAL_LENGTH) third_time = time_zero + timedelta(seconds=6000) with mock.patch('zerver.views.presence.timezone_now', return_value=third_time): result = self.client_post("/json/users/me/presence", {'status': 'active', 'new_user_input': 'true'}) self.assert_json_success(result) self.assertEqual(UserActivityInterval.objects.filter(user_profile=user_profile).count(), 2) interval = UserActivityInterval.objects.filter(user_profile=user_profile).order_by('start')[0] self.assertEqual(interval.start, time_zero) self.assertEqual(interval.end, second_time + UserActivityInterval.MIN_INTERVAL_LENGTH) interval = UserActivityInterval.objects.filter(user_profile=user_profile).order_by('start')[1] self.assertEqual(interval.start, third_time) self.assertEqual(interval.end, third_time + UserActivityInterval.MIN_INTERVAL_LENGTH) self.assertEqual( seconds_usage_between( user_profile, time_zero, third_time).total_seconds(), 1500) self.assertEqual( seconds_usage_between( user_profile, time_zero, third_time+timedelta(seconds=10)).total_seconds(), 1510) self.assertEqual( seconds_usage_between( user_profile, time_zero, third_time+timedelta(seconds=1000)).total_seconds(), 2400) self.assertEqual( seconds_usage_between( user_profile, time_zero, third_time - timedelta(seconds=100)).total_seconds(), 1500) self.assertEqual( seconds_usage_between( user_profile, time_zero + timedelta(seconds=100), third_time - timedelta(seconds=100)).total_seconds(), 1400) self.assertEqual( seconds_usage_between( user_profile, time_zero + timedelta(seconds=1200), third_time - timedelta(seconds=100)).total_seconds(), 300) # Now test /activity with actual data user_profile.is_staff = True user_profile.save() result = self.client_get('/activity') self.assertEqual(result.status_code, 200) def test_filter_presence_idle_user_ids(self) -> None: user_profile = self.example_user("hamlet") from zerver.lib.actions import filter_presence_idle_user_ids self.login(self.example_email("hamlet")) self.assertEqual(filter_presence_idle_user_ids({user_profile.id}), [user_profile.id]) self.client_post("/json/users/me/presence", {'status': 'idle'}) self.assertEqual(filter_presence_idle_user_ids({user_profile.id}), [user_profile.id]) self.client_post("/json/users/me/presence", {'status': 'active'}) self.assertEqual(filter_presence_idle_user_ids({user_profile.id}), []) def test_no_mit(self) -> None: """Zephyr mirror realms such as MIT never get a list of users""" self.login(self.mit_email("espuser"), realm=get_realm("zephyr")) result = self.client_post("/json/users/me/presence", {'status': 'idle'}, subdomain="zephyr") self.assert_json_success(result) self.assertEqual(result.json()['presences'], {}) def test_mirror_presence(self) -> None: """Zephyr mirror realms find out the status of their mirror bot""" user_profile = self.mit_user('espuser') email = user_profile.email self.login(email, realm=user_profile.realm) def post_presence() -> Dict[str, Any]: result = self.client_post("/json/users/me/presence", {'status': 'idle'}, subdomain="zephyr") self.assert_json_success(result) json = result.json() return json json = post_presence() self.assertEqual(json['zephyr_mirror_active'], False) self._simulate_mirror_activity_for_user(user_profile) json = post_presence() self.assertEqual(json['zephyr_mirror_active'], True) def _simulate_mirror_activity_for_user(self, user_profile: UserProfile) -> None: last_visit = timezone_now() client = make_client('zephyr_mirror') UserActivity.objects.get_or_create( user_profile=user_profile, client=client, query='get_events', count=2, last_visit=last_visit ) def test_same_realm(self) -> None: self.login(self.mit_email("espuser"), realm=get_realm("zephyr")) self.client_post("/json/users/me/presence", {'status': 'idle'}, subdomain="zephyr") self.logout() # Ensure we don't see hamlet@zulip.com information leakage self.login(self.example_email("hamlet")) result = self.client_post("/json/users/me/presence", {'status': 'idle'}) self.assert_json_success(result) json = result.json() self.assertEqual(json['presences'][self.example_email("hamlet")]["website"]['status'], 'idle') # We only want @zulip.com emails for email in json['presences'].keys(): self.assertEqual(email_to_domain(email), 'zulip.com') class SingleUserPresenceTests(ZulipTestCase): def test_single_user_get(self) -> None: # First, we setup the test with some data email = self.example_email("othello") self.login(self.example_email("othello")) result = self.client_post("/json/users/me/presence", {'status': 'active'}) result = self.client_post("/json/users/me/presence", {'status': 'active'}, HTTP_USER_AGENT="ZulipDesktop/1.0") result = self.api_post(email, "/api/v1/users/me/presence", {'status': 'idle'}, HTTP_USER_AGENT="ZulipAndroid/1.0") self.assert_json_success(result) # Check some error conditions result = self.client_get("/json/users/nonexistence@zulip.com/presence") self.assert_json_error(result, "No such user") result = self.client_get("/json/users/cordelia@zulip.com/presence") self.assert_json_error(result, "No presence data for cordelia@zulip.com") do_deactivate_user(self.example_user('cordelia')) result = self.client_get("/json/users/cordelia@zulip.com/presence") self.assert_json_error(result, "No such user") result = self.client_get("/json/users/new-user-bot@zulip.com/presence") self.assert_json_error(result, "Presence is not supported for bot users.") self.login(self.mit_email("sipbtest"), realm=get_realm("zephyr")) result = self.client_get("/json/users/othello@zulip.com/presence", subdomain="zephyr") self.assert_json_error(result, "No such user") # Then, we check everything works self.login(self.example_email("hamlet")) result = self.client_get("/json/users/othello@zulip.com/presence") result_dict = result.json() self.assertEqual( set(result_dict['presence'].keys()), {"ZulipAndroid", "website", "aggregated"}) self.assertEqual(set(result_dict['presence']['website'].keys()), {"status", "timestamp"}) def test_ping_only(self) -> None: self.login(self.example_email("othello")) req = dict( status='active', ping_only='true', ) result = self.client_post("/json/users/me/presence", req) self.assertEqual(result.json()['msg'], '') class UserPresenceAggregationTests(ZulipTestCase): def _send_presence_for_aggregated_tests(self, email: str, status: str, validate_time: datetime.datetime) -> Dict[str, Dict[str, Any]]: self.login(email) timezone_util = 'zerver.views.presence.timezone_now' with mock.patch(timezone_util, return_value=validate_time - datetime.timedelta(seconds=5)): self.client_post("/json/users/me/presence", {'status': status}) with mock.patch(timezone_util, return_value=validate_time - datetime.timedelta(seconds=2)): self.api_post(email, "/api/v1/users/me/presence", {'status': status}, HTTP_USER_AGENT="ZulipAndroid/1.0") with mock.patch(timezone_util, return_value=validate_time - datetime.timedelta(seconds=7)): latest_result = self.api_post(email, "/api/v1/users/me/presence", {'status': status}, HTTP_USER_AGENT="ZulipIOS/1.0") latest_result_dict = latest_result.json() self.assertDictEqual( latest_result_dict['presences'][email]['aggregated'], { 'status': status, 'timestamp': datetime_to_timestamp(validate_time - datetime.timedelta(seconds=2)), 'client': 'ZulipAndroid' } ) result = self.client_get("/json/users/%s/presence" % (email,)) return result.json() def test_aggregated_info(self) -> None: email = self.example_email("othello") validate_time = timezone_now() self._send_presence_for_aggregated_tests(str(self.example_email("othello")), 'active', validate_time) with mock.patch('zerver.views.presence.timezone_now', return_value=validate_time - datetime.timedelta(seconds=1)): result = self.api_post(email, "/api/v1/users/me/presence", {'status': 'active'}, HTTP_USER_AGENT="ZulipTestDev/1.0") result_dict = result.json() self.assertDictEqual( result_dict['presences'][email]['aggregated'], { 'status': 'active', 'timestamp': datetime_to_timestamp(validate_time - datetime.timedelta(seconds=1)), 'client': 'ZulipTestDev' } ) def test_aggregated_presense_active(self) -> None: validate_time = timezone_now() result_dict = self._send_presence_for_aggregated_tests(str(self.example_email("othello")), 'active', validate_time) self.assertDictEqual( result_dict['presence']['aggregated'], { "status": "active", "timestamp": datetime_to_timestamp(validate_time - datetime.timedelta(seconds=2)) } ) def test_aggregated_presense_idle(self) -> None: validate_time = timezone_now() result_dict = self._send_presence_for_aggregated_tests(str(self.example_email("othello")), 'idle', validate_time) self.assertDictEqual( result_dict['presence']['aggregated'], { "status": "idle", "timestamp": datetime_to_timestamp(validate_time - datetime.timedelta(seconds=2)) } ) def test_aggregated_presense_mixed(self) -> None: email = self.example_email("othello") self.login(email) validate_time = timezone_now() with mock.patch('zerver.views.presence.timezone_now', return_value=validate_time - datetime.timedelta(seconds=3)): self.api_post(email, "/api/v1/users/me/presence", {'status': 'active'}, HTTP_USER_AGENT="ZulipTestDev/1.0") result_dict = self._send_presence_for_aggregated_tests(str(email), 'idle', validate_time) self.assertDictEqual( result_dict['presence']['aggregated'], { "status": "idle", "timestamp": datetime_to_timestamp(validate_time - datetime.timedelta(seconds=2)) } ) def test_aggregated_presense_offline(self) -> None: email = self.example_email("othello") self.login(email) validate_time = timezone_now() with self.settings(OFFLINE_THRESHOLD_SECS=1): result_dict = self._send_presence_for_aggregated_tests(str(email), 'idle', validate_time) self.assertDictEqual( result_dict['presence']['aggregated'], { "status": "offline", "timestamp": datetime_to_timestamp(validate_time - datetime.timedelta(seconds=2)) } ) class GetRealmStatusesTest(ZulipTestCase): def test_get_statuses(self) -> None: # Setup the test by simulating users reporting their presence data. othello_email = self.example_email("othello") result = self.api_post(othello_email, "/api/v1/users/me/presence", {'status': 'active'}, HTTP_USER_AGENT="ZulipAndroid/1.0") hamlet_email = self.example_email("hamlet") result = self.api_post(hamlet_email, "/api/v1/users/me/presence", {'status': 'idle'}, HTTP_USER_AGENT="ZulipDesktop/1.0") self.assert_json_success(result) # Check that a bot can fetch the presence data for the realm. result = self.api_get(self.example_email("welcome_bot"), "/api/v1/realm/presence") self.assert_json_success(result) json = result.json() self.assertEqual(sorted(json['presences'].keys()), [hamlet_email, othello_email])
[ "mock.Mock", "int", "mock.Mock", "UserProfile", "str", "str", "datetime.datetime" ]
[ 889, 3405, 7779, 13654, 17193, 17206, 17270 ]
[ 898, 3408, 7788, 13665, 17196, 17209, 17287 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_push_notifications.py
from contextlib import contextmanager import itertools import requests import mock from mock import call import time from typing import Any, Dict, List, Optional, Union, SupportsInt import base64 import gcm import json import os import ujson import uuid from django.test import TestCase, override_settings from django.conf import settings from django.http import HttpResponse from django.utils.crypto import get_random_string from zerver.models import ( PushDeviceToken, UserProfile, Message, UserMessage, receives_offline_email_notifications, receives_offline_push_notifications, receives_online_notifications, receives_stream_notifications, get_client, get_realm, Recipient, Stream, Subscription, ) from zerver.lib.soft_deactivation import do_soft_deactivate_users from zerver.lib import push_notifications as apn from zerver.lib.push_notifications import get_mobile_push_content, \ DeviceToken, PushNotificationBouncerException, get_apns_client from zerver.lib.response import json_success from zerver.lib.test_classes import ( ZulipTestCase, ) from zilencer.models import RemoteZulipServer, RemotePushDeviceToken from django.utils.timezone import now ZERVER_DIR = os.path.dirname(os.path.dirname(__file__)) class BouncerTestCase(ZulipTestCase): def setUp(self) -> None: self.server_uuid = "1234-abcd" server = RemoteZulipServer(uuid=self.server_uuid, api_key="magic_secret_api_key", hostname="demo.example.com", last_updated=now()) server.save() super().setUp() def tearDown(self) -> None: RemoteZulipServer.objects.filter(uuid=self.server_uuid).delete() super().tearDown() def bounce_request(self, *args: Any, **kwargs: Any) -> HttpResponse: """This method is used to carry out the push notification bouncer requests using the Django test browser, rather than python-requests. """ # args[0] is method, args[1] is URL. local_url = args[1].replace(settings.PUSH_NOTIFICATION_BOUNCER_URL, "") if args[0] == "POST": result = self.api_post(self.server_uuid, local_url, kwargs['data'], subdomain="") else: raise AssertionError("Unsupported method for bounce_request") return result def get_generic_payload(self, method: str='register') -> Dict[str, Any]: user_id = 10 token = "111222" token_kind = PushDeviceToken.GCM return {'user_id': user_id, 'token': token, 'token_kind': token_kind} class PushBouncerNotificationTest(BouncerTestCase): DEFAULT_SUBDOMAIN = "" def test_unregister_remote_push_user_params(self) -> None: token = "111222" token_kind = PushDeviceToken.GCM endpoint = '/api/v1/remotes/push/unregister' result = self.api_post(self.server_uuid, endpoint, {'token_kind': token_kind}) self.assert_json_error(result, "Missing 'token' argument") result = self.api_post(self.server_uuid, endpoint, {'token': token}) self.assert_json_error(result, "Missing 'token_kind' argument") # We need the root ('') subdomain to be in use for this next # test, since the push bouncer API is only available there: realm = get_realm("zulip") realm.string_id = "" realm.save() result = self.api_post(self.example_email("hamlet"), endpoint, {'token': token, 'user_id': 15, 'token_kind': token_kind}, realm="") self.assert_json_error(result, "Must validate with valid Zulip server API key") def test_register_remote_push_user_paramas(self) -> None: token = "111222" user_id = 11 token_kind = PushDeviceToken.GCM endpoint = '/api/v1/remotes/push/register' result = self.api_post(self.server_uuid, endpoint, {'user_id': user_id, 'token_kind': token_kind}) self.assert_json_error(result, "Missing 'token' argument") result = self.api_post(self.server_uuid, endpoint, {'user_id': user_id, 'token': token}) self.assert_json_error(result, "Missing 'token_kind' argument") result = self.api_post(self.server_uuid, endpoint, {'token': token, 'token_kind': token_kind}) self.assert_json_error(result, "Missing 'user_id' argument") result = self.api_post(self.server_uuid, endpoint, {'user_id': user_id, 'token': token, 'token_kind': 17}) self.assert_json_error(result, "Invalid token type") result = self.api_post(self.example_email("hamlet"), endpoint, {'user_id': user_id, 'token_kind': token_kind, 'token': token}) self.assert_json_error(result, "Account is not associated with this subdomain", status_code=401) # We need the root ('') subdomain to be in use for this next # test, since the push bouncer API is only available there: realm = get_realm("zulip") realm.string_id = "" realm.save() result = self.api_post(self.example_email("hamlet"), endpoint, {'user_id': user_id, 'token_kind': token_kind, 'token': token}) self.assert_json_error(result, "Must validate with valid Zulip server API key") result = self.api_post(self.server_uuid, endpoint, {'user_id': user_id, 'token_kind': token_kind, 'token': token}, subdomain="zulip") self.assert_json_error(result, "Invalid subdomain for push notifications bouncer", status_code=401) # We do a bit of hackery here to the API_KEYS cache just to # make the code simple for sending an incorrect API key. from zerver.lib.test_classes import API_KEYS API_KEYS[self.server_uuid] = 'invalid' result = self.api_post(self.server_uuid, endpoint, {'user_id': user_id, 'token_kind': token_kind, 'token': token}) self.assert_json_error(result, "Zulip server auth failure: key does not match role 1234-abcd", status_code=401) del API_KEYS[self.server_uuid] credentials = "%s:%s" % ("5678-efgh", 'invalid') api_auth = 'Basic ' + base64.b64encode(credentials.encode('utf-8')).decode('utf-8') result = self.client_post(endpoint, {'user_id': user_id, 'token_kind': token_kind, 'token': token}, HTTP_AUTHORIZATION = api_auth) self.assert_json_error(result, "Zulip server auth failure: 5678-efgh is not registered", status_code=401) def test_remote_push_user_endpoints(self) -> None: endpoints = [ ('/api/v1/remotes/push/register', 'register'), ('/api/v1/remotes/push/unregister', 'unregister'), ] for endpoint, method in endpoints: payload = self.get_generic_payload(method) # Verify correct results are success result = self.api_post(self.server_uuid, endpoint, payload) self.assert_json_success(result) remote_tokens = RemotePushDeviceToken.objects.filter(token=payload['token']) token_count = 1 if method == 'register' else 0 self.assertEqual(len(remote_tokens), token_count) # Try adding/removing tokens that are too big... broken_token = "x" * 5000 # too big payload['token'] = broken_token result = self.api_post(self.server_uuid, endpoint, payload) self.assert_json_error(result, 'Empty or invalid length token') def test_invalid_apns_token(self) -> None: endpoints = [ ('/api/v1/remotes/push/register', 'apple-token'), ] for endpoint, method in endpoints: payload = { 'user_id': 10, 'token': 'xyz uses non-hex characters', 'token_kind': PushDeviceToken.APNS, } result = self.api_post(self.server_uuid, endpoint, payload) self.assert_json_error(result, 'Invalid APNS token') @override_settings(PUSH_NOTIFICATION_BOUNCER_URL='https://push.zulip.org.example.com') @mock.patch('zerver.lib.push_notifications.requests.request') def test_push_bouncer_api(self, mock: Any) -> None: """This is a variant of the below test_push_api, but using the full push notification bouncer flow """ mock.side_effect = self.bounce_request user = self.example_user('cordelia') email = user.email self.login(email) server = RemoteZulipServer.objects.get(uuid=self.server_uuid) endpoints = [ ('/json/users/me/apns_device_token', 'apple-tokenaz', RemotePushDeviceToken.APNS), ('/json/users/me/android_gcm_reg_id', 'android-token', RemotePushDeviceToken.GCM), ] # Test error handling for endpoint, _, kind in endpoints: # Try adding/removing tokens that are too big... broken_token = "a" * 5000 # too big result = self.client_post(endpoint, {'token': broken_token, 'token_kind': kind}, subdomain="zulip") self.assert_json_error(result, 'Empty or invalid length token') result = self.client_delete(endpoint, {'token': broken_token, 'token_kind': kind}, subdomain="zulip") self.assert_json_error(result, 'Empty or invalid length token') # Try to remove a non-existent token... result = self.client_delete(endpoint, {'token': 'abcd1234', 'token_kind': kind}, subdomain="zulip") self.assert_json_error(result, 'Token does not exist') # Add tokens for endpoint, token, kind in endpoints: # Test that we can push twice result = self.client_post(endpoint, {'token': token}, subdomain="zulip") self.assert_json_success(result) result = self.client_post(endpoint, {'token': token}, subdomain="zulip") self.assert_json_success(result) tokens = list(RemotePushDeviceToken.objects.filter(user_id=user.id, token=token, server=server)) self.assertEqual(len(tokens), 1) self.assertEqual(tokens[0].token, token) # User should have tokens for both devices now. tokens = list(RemotePushDeviceToken.objects.filter(user_id=user.id, server=server)) self.assertEqual(len(tokens), 2) # Remove tokens for endpoint, token, kind in endpoints: result = self.client_delete(endpoint, {'token': token, 'token_kind': kind}, subdomain="zulip") self.assert_json_success(result) tokens = list(RemotePushDeviceToken.objects.filter(user_id=user.id, token=token, server=server)) self.assertEqual(len(tokens), 0) class PushNotificationTest(BouncerTestCase): def setUp(self) -> None: super().setUp() self.user_profile = self.example_user('hamlet') self.tokens = [u'aaaa', u'bbbb'] for token in self.tokens: PushDeviceToken.objects.create( kind=PushDeviceToken.APNS, token=apn.hex_to_b64(token), user=self.user_profile, ios_app_id=settings.ZULIP_IOS_APP_ID) self.remote_tokens = [u'cccc'] for token in self.remote_tokens: RemotePushDeviceToken.objects.create( kind=RemotePushDeviceToken.APNS, token=apn.hex_to_b64(token), user_id=self.user_profile.id, server=RemoteZulipServer.objects.get(uuid=self.server_uuid), ) self.sending_client = get_client('test') self.sender = self.example_user('hamlet') def get_message(self, type: int, type_id: int=100) -> Message: recipient, _ = Recipient.objects.get_or_create( type_id=type_id, type=type, ) message = Message( sender=self.sender, recipient=recipient, content='This is test content', rendered_content='This is test content', pub_date=now(), sending_client=self.sending_client, ) message.set_topic_name('Test Topic') message.save() return message @contextmanager def mock_apns(self) -> mock.MagicMock: mock_apns = mock.Mock() with mock.patch('zerver.lib.push_notifications.get_apns_client') as mock_get: mock_get.return_value = mock_apns yield mock_apns class HandlePushNotificationTest(PushNotificationTest): DEFAULT_SUBDOMAIN = "" def bounce_request(self, *args: Any, **kwargs: Any) -> HttpResponse: """This method is used to carry out the push notification bouncer requests using the Django test browser, rather than python-requests. """ # args[0] is method, args[1] is URL. local_url = args[1].replace(settings.PUSH_NOTIFICATION_BOUNCER_URL, "") if args[0] == "POST": result = self.api_post(self.server_uuid, local_url, kwargs['data'], content_type="application/json") else: raise AssertionError("Unsupported method for bounce_request") return result def test_end_to_end(self) -> None: remote_gcm_tokens = [u'dddd'] for token in remote_gcm_tokens: RemotePushDeviceToken.objects.create( kind=RemotePushDeviceToken.GCM, token=apn.hex_to_b64(token), user_id=self.user_profile.id, server=RemoteZulipServer.objects.get(uuid=self.server_uuid), ) message = self.get_message(Recipient.PERSONAL, type_id=1) UserMessage.objects.create( user_profile=self.user_profile, message=message ) missed_message = { 'message_id': message.id, 'trigger': 'private_message', } with self.settings(PUSH_NOTIFICATION_BOUNCER_URL=''), \ mock.patch('zerver.lib.push_notifications.requests.request', side_effect=self.bounce_request), \ mock.patch('zerver.lib.push_notifications.gcm') as mock_gcm, \ self.mock_apns() as mock_apns, \ mock.patch('logging.info') as mock_info, \ mock.patch('logging.warning'): apns_devices = [ (apn.b64_to_hex(device.token), device.ios_app_id, device.token) for device in RemotePushDeviceToken.objects.filter( kind=PushDeviceToken.APNS) ] gcm_devices = [ (apn.b64_to_hex(device.token), device.ios_app_id, device.token) for device in RemotePushDeviceToken.objects.filter( kind=PushDeviceToken.GCM) ] mock_gcm.json_request.return_value = { 'success': {gcm_devices[0][2]: message.id}} mock_apns.get_notification_result.return_value = 'Success' apn.handle_push_notification(self.user_profile.id, missed_message) for _, _, token in apns_devices: mock_info.assert_any_call( "APNs: Success sending for user %d to device %s", self.user_profile.id, token) for _, _, token in gcm_devices: mock_info.assert_any_call( "GCM: Sent %s as %s" % (token, message.id)) # Now test the unregistered case mock_apns.get_notification_result.return_value = ('Unregistered', 1234567) apn.handle_push_notification(self.user_profile.id, missed_message) for _, _, token in apns_devices: mock_info.assert_any_call( "APNs: Removing invalid/expired token %s (%s)" % (token, "Unregistered")) self.assertEqual(RemotePushDeviceToken.objects.filter(kind=PushDeviceToken.APNS).count(), 0) def test_end_to_end_connection_error(self) -> None: remote_gcm_tokens = [u'dddd'] for token in remote_gcm_tokens: RemotePushDeviceToken.objects.create( kind=RemotePushDeviceToken.GCM, token=apn.hex_to_b64(token), user_id=self.user_profile.id, server=RemoteZulipServer.objects.get(uuid=self.server_uuid), ) message = self.get_message(Recipient.PERSONAL, type_id=1) UserMessage.objects.create( user_profile=self.user_profile, message=message ) def retry(queue_name: Any, event: Any, processor: Any) -> None: apn.handle_push_notification(event['user_profile_id'], event) missed_message = { 'user_profile_id': self.user_profile.id, 'message_id': message.id, 'trigger': 'private_message', } with self.settings(PUSH_NOTIFICATION_BOUNCER_URL=''), \ mock.patch('zerver.lib.push_notifications.requests.request', side_effect=self.bounce_request), \ mock.patch('zerver.lib.push_notifications.gcm') as mock_gcm, \ mock.patch('zerver.lib.push_notifications.send_notifications_to_bouncer', side_effect=requests.ConnectionError), \ mock.patch('zerver.lib.queue.queue_json_publish', side_effect=retry) as mock_retry, \ mock.patch('logging.warning') as mock_warn: gcm_devices = [ (apn.b64_to_hex(device.token), device.ios_app_id, device.token) for device in RemotePushDeviceToken.objects.filter( kind=PushDeviceToken.GCM) ] mock_gcm.json_request.return_value = { 'success': {gcm_devices[0][2]: message.id}} apn.handle_push_notification(self.user_profile.id, missed_message) self.assertEqual(mock_retry.call_count, 3) mock_warn.assert_called_with("Maximum retries exceeded for " "trigger:%s event:" "push_notification" % (self.user_profile.id,)) def test_disabled_notifications(self) -> None: user_profile = self.example_user('hamlet') user_profile.enable_online_email_notifications = False user_profile.enable_online_push_notifications = False user_profile.enable_offline_email_notifications = False user_profile.enable_offline_push_notifications = False user_profile.enable_stream_push_notifications = False user_profile.save() apn.handle_push_notification(user_profile.id, {}) def test_read_message(self) -> None: user_profile = self.example_user('hamlet') message = self.get_message(Recipient.PERSONAL, type_id=1) UserMessage.objects.create( user_profile=user_profile, flags=UserMessage.flags.read, message=message ) missed_message = { 'message_id': message.id, 'trigger': 'private_message', } apn.handle_push_notification(user_profile.id, missed_message) def test_send_notifications_to_bouncer(self) -> None: user_profile = self.example_user('hamlet') message = self.get_message(Recipient.PERSONAL, type_id=1) UserMessage.objects.create( user_profile=user_profile, message=message ) missed_message = { 'message_id': message.id, 'trigger': 'private_message', } with self.settings(PUSH_NOTIFICATION_BOUNCER_URL=True), \ mock.patch('zerver.lib.push_notifications.get_apns_payload', return_value={'apns': True}), \ mock.patch('zerver.lib.push_notifications.get_gcm_payload', return_value={'gcm': True}), \ mock.patch('zerver.lib.push_notifications' '.send_notifications_to_bouncer') as mock_send: apn.handle_push_notification(user_profile.id, missed_message) mock_send.assert_called_with(user_profile.id, {'apns': True}, {'gcm': True}, ) def test_non_bouncer_push(self) -> None: message = self.get_message(Recipient.PERSONAL, type_id=1) UserMessage.objects.create( user_profile=self.user_profile, message=message ) for token in [u'dddd']: PushDeviceToken.objects.create( kind=PushDeviceToken.GCM, token=apn.hex_to_b64(token), user=self.user_profile) android_devices = list( PushDeviceToken.objects.filter(user=self.user_profile, kind=PushDeviceToken.GCM)) apple_devices = list( PushDeviceToken.objects.filter(user=self.user_profile, kind=PushDeviceToken.APNS)) missed_message = { 'message_id': message.id, 'trigger': 'private_message', } with mock.patch('zerver.lib.push_notifications.get_apns_payload', return_value={'apns': True}), \ mock.patch('zerver.lib.push_notifications.get_gcm_payload', return_value={'gcm': True}), \ mock.patch('zerver.lib.push_notifications' '.send_apple_push_notification') as mock_send_apple, \ mock.patch('zerver.lib.push_notifications' '.send_android_push_notification') as mock_send_android: apn.handle_push_notification(self.user_profile.id, missed_message) mock_send_apple.assert_called_with(self.user_profile.id, apple_devices, {'apns': True}) mock_send_android.assert_called_with(android_devices, {'gcm': True}) @override_settings(SEND_REMOVE_PUSH_NOTIFICATIONS=True) def test_send_remove_notifications_to_bouncer(self) -> None: user_profile = self.example_user('hamlet') message = self.get_message(Recipient.PERSONAL, type_id=1) UserMessage.objects.create( user_profile=user_profile, message=message ) with self.settings(PUSH_NOTIFICATION_BOUNCER_URL=True), \ mock.patch('zerver.lib.push_notifications' '.send_notifications_to_bouncer') as mock_send_android, \ mock.patch('zerver.lib.push_notifications.get_common_payload', return_value={'gcm': True}): apn.handle_remove_push_notification(user_profile.id, message.id) mock_send_android.assert_called_with(user_profile.id, {}, {'gcm': True, 'event': 'remove', 'zulip_message_id': message.id}) @override_settings(SEND_REMOVE_PUSH_NOTIFICATIONS=True) def test_non_bouncer_push_remove(self) -> None: message = self.get_message(Recipient.PERSONAL, type_id=1) UserMessage.objects.create( user_profile=self.user_profile, message=message ) for token in [u'dddd']: PushDeviceToken.objects.create( kind=PushDeviceToken.GCM, token=apn.hex_to_b64(token), user=self.user_profile) android_devices = list( PushDeviceToken.objects.filter(user=self.user_profile, kind=PushDeviceToken.GCM)) with mock.patch('zerver.lib.push_notifications' '.send_android_push_notification') as mock_send_android, \ mock.patch('zerver.lib.push_notifications.get_common_payload', return_value={'gcm': True}): apn.handle_remove_push_notification(self.user_profile.id, message.id) mock_send_android.assert_called_with(android_devices, {'gcm': True, 'event': 'remove', 'zulip_message_id': message.id}) def test_user_message_does_not_exist(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""" self.make_stream('public_stream') message_id = self.send_stream_message("iago@zulip.com", "public_stream", "test") missed_message = {'message_id': message_id} with mock.patch('logging.error') as mock_logger: apn.handle_push_notification(self.user_profile.id, missed_message) mock_logger.assert_called_with("Could not find UserMessage with " "message_id %s and user_id %s" % (message_id, self.user_profile.id,)) 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""" self.make_stream('public_stream') self.subscribe(self.user_profile, 'public_stream') do_soft_deactivate_users([self.user_profile]) message_id = self.send_stream_message("iago@zulip.com", "public_stream", "test") missed_message = { 'message_id': message_id, 'trigger': 'stream_push_notify', } for token in [u'dddd']: PushDeviceToken.objects.create( kind=PushDeviceToken.GCM, token=apn.hex_to_b64(token), user=self.user_profile) android_devices = list( PushDeviceToken.objects.filter(user=self.user_profile, kind=PushDeviceToken.GCM)) apple_devices = list( PushDeviceToken.objects.filter(user=self.user_profile, kind=PushDeviceToken.APNS)) with mock.patch('zerver.lib.push_notifications.get_apns_payload', return_value={'apns': True}), \ mock.patch('zerver.lib.push_notifications.get_gcm_payload', return_value={'gcm': True}), \ mock.patch('zerver.lib.push_notifications' '.send_apple_push_notification') as mock_send_apple, \ mock.patch('zerver.lib.push_notifications' '.send_android_push_notification') as mock_send_android, \ mock.patch('logging.error') as mock_logger: apn.handle_push_notification(self.user_profile.id, missed_message) mock_logger.assert_not_called() mock_send_apple.assert_called_with(self.user_profile.id, apple_devices, {'apns': True}) mock_send_android.assert_called_with(android_devices, {'gcm': True}) class TestAPNs(PushNotificationTest): def devices(self) -> List[DeviceToken]: return list(PushDeviceToken.objects.filter( user=self.user_profile, kind=PushDeviceToken.APNS)) def send(self, devices: Optional[List[PushDeviceToken]]=None, payload_data: Dict[str, Any]={}) -> None: if devices is None: devices = self.devices() apn.send_apple_push_notification( self.user_profile.id, devices, payload_data) def test_get_apns_client(self) -> None: import zerver.lib.push_notifications zerver.lib.push_notifications._apns_client_initialized = False with self.settings(APNS_CERT_FILE='/foo.pem'), \ mock.patch('apns2.client.APNsClient') as mock_client: client = get_apns_client() self.assertEqual(mock_client.return_value, client) def test_not_configured(self) -> None: with mock.patch('zerver.lib.push_notifications.get_apns_client') as mock_get, \ mock.patch('zerver.lib.push_notifications.logging') as mock_logging: mock_get.return_value = None self.send() mock_logging.warning.assert_called_once_with( "APNs: Dropping a notification because nothing configured. " "Set PUSH_NOTIFICATION_BOUNCER_URL (or APNS_CERT_FILE).") mock_logging.info.assert_not_called() def test_success(self) -> None: with self.mock_apns() as mock_apns, \ mock.patch('zerver.lib.push_notifications.logging') as mock_logging: mock_apns.get_notification_result.return_value = 'Success' self.send() mock_logging.warning.assert_not_called() for device in self.devices(): mock_logging.info.assert_any_call( "APNs: Success sending for user %d to device %s", self.user_profile.id, device.token) def test_http_retry(self) -> None: import hyper with self.mock_apns() as mock_apns, \ mock.patch('zerver.lib.push_notifications.logging') as mock_logging: mock_apns.get_notification_result.side_effect = itertools.chain( [hyper.http20.exceptions.StreamResetError()], itertools.repeat('Success')) self.send() mock_logging.warning.assert_called_once_with( "APNs: HTTP error sending for user %d to device %s: %s", self.user_profile.id, self.devices()[0].token, "StreamResetError") for device in self.devices(): mock_logging.info.assert_any_call( "APNs: Success sending for user %d to device %s", self.user_profile.id, device.token) def test_http_retry_eventually_fails(self) -> None: import hyper with self.mock_apns() as mock_apns, \ mock.patch('zerver.lib.push_notifications.logging') as mock_logging: mock_apns.get_notification_result.side_effect = itertools.chain( [hyper.http20.exceptions.StreamResetError()], [hyper.http20.exceptions.StreamResetError()], [hyper.http20.exceptions.StreamResetError()], [hyper.http20.exceptions.StreamResetError()], [hyper.http20.exceptions.StreamResetError()], ) self.send(devices=self.devices()[0:1]) self.assertEqual(mock_logging.warning.call_count, 5) mock_logging.warning.assert_called_with( 'APNs: Failed to send for user %d to device %s: %s', self.user_profile.id, self.devices()[0].token, 'HTTP error, retries exhausted') self.assertEqual(mock_logging.info.call_count, 1) def test_modernize_apns_payload(self) -> None: payload = {'alert': 'Message from Hamlet', 'badge': 0, 'custom': {'zulip': {'message_ids': [3]}}} self.assertEqual( apn.modernize_apns_payload( {'alert': 'Message from Hamlet', 'message_ids': [3]}), payload) self.assertEqual( apn.modernize_apns_payload(payload), payload) class TestGetAPNsPayload(PushNotificationTest): def test_get_apns_payload_personal_message(self) -> None: user_profile = self.example_user("othello") message_id = self.send_personal_message( self.example_email('hamlet'), self.example_email('othello'), 'Content of personal message', ) message = Message.objects.get(id=message_id) message.trigger = 'private_message' payload = apn.get_apns_payload(user_profile, message) expected = { 'alert': { 'title': 'King Hamlet', 'subtitle': '', 'body': message.content, }, 'badge': 0, 'sound': 'default', 'custom': { 'zulip': { 'message_ids': [message.id], 'recipient_type': 'private', 'sender_email': 'hamlet@zulip.com', 'sender_id': 4, 'server': settings.EXTERNAL_HOST, 'realm_id': message.sender.realm.id, 'realm_uri': message.sender.realm.uri, } } } self.assertDictEqual(payload, expected) def test_get_apns_payload_huddle_message(self) -> None: user_profile = self.example_user("othello") message_id = self.send_huddle_message( self.sender.email, [self.example_email('othello'), self.example_email('cordelia')]) message = Message.objects.get(id=message_id) message.trigger = 'private_message' payload = apn.get_apns_payload(user_profile, message) expected = { 'alert': { 'title': 'Cordelia Lear, King Hamlet, Othello, the Moor of Venice', 'subtitle': 'King Hamlet:', 'body': message.content, }, 'sound': 'default', 'badge': 0, 'custom': { 'zulip': { 'message_ids': [message.id], 'recipient_type': 'private', 'pm_users': ','.join( str(s.user_profile_id) for s in Subscription.objects.filter( recipient=message.recipient)), 'sender_email': 'hamlet@zulip.com', 'sender_id': 4, 'server': settings.EXTERNAL_HOST, 'realm_id': message.sender.realm.id, 'realm_uri': message.sender.realm.uri, } } } self.assertDictEqual(payload, expected) def test_get_apns_payload_stream_message(self): # type: () -> None user_profile = self.example_user("hamlet") stream = Stream.objects.filter(name='Verona').get() message = self.get_message(Recipient.STREAM, stream.id) message.trigger = 'push_stream_notify' message.stream_name = 'Verona' payload = apn.get_apns_payload(user_profile, message) expected = { 'alert': { 'title': '#Verona > Test Topic', 'subtitle': 'King Hamlet:', 'body': message.content, }, 'sound': 'default', 'badge': 0, 'custom': { 'zulip': { 'message_ids': [message.id], 'recipient_type': 'stream', 'sender_email': 'hamlet@zulip.com', 'sender_id': 4, "stream": apn.get_display_recipient(message.recipient), "topic": message.topic_name(), 'server': settings.EXTERNAL_HOST, 'realm_id': message.sender.realm.id, 'realm_uri': message.sender.realm.uri, } } } self.assertDictEqual(payload, expected) def test_get_apns_payload_stream_mention(self): # type: () -> None user_profile = self.example_user("othello") stream = Stream.objects.filter(name='Verona').get() message = self.get_message(Recipient.STREAM, stream.id) message.trigger = 'mentioned' message.stream_name = 'Verona' payload = apn.get_apns_payload(user_profile, message) expected = { 'alert': { 'title': '#Verona > Test Topic', 'subtitle': 'King Hamlet mentioned you:', 'body': message.content, }, 'sound': 'default', 'badge': 0, 'custom': { 'zulip': { 'message_ids': [message.id], 'recipient_type': 'stream', 'sender_email': 'hamlet@zulip.com', 'sender_id': 4, "stream": apn.get_display_recipient(message.recipient), "topic": message.topic_name(), 'server': settings.EXTERNAL_HOST, 'realm_id': message.sender.realm.id, 'realm_uri': message.sender.realm.uri, } } } self.assertDictEqual(payload, expected) @override_settings(PUSH_NOTIFICATION_REDACT_CONTENT = True) def test_get_apns_payload_redacted_content(self) -> None: user_profile = self.example_user("othello") message_id = self.send_huddle_message( self.sender.email, [self.example_email('othello'), self.example_email('cordelia')]) message = Message.objects.get(id=message_id) message.trigger = 'private_message' payload = apn.get_apns_payload(user_profile, message) expected = { 'alert': { 'title': 'Cordelia Lear, King Hamlet, Othello, the Moor of Venice', 'subtitle': "King Hamlet:", 'body': "***REDACTED***", }, 'sound': 'default', 'badge': 0, 'custom': { 'zulip': { 'message_ids': [message.id], 'recipient_type': 'private', 'pm_users': ','.join( str(s.user_profile_id) for s in Subscription.objects.filter( recipient=message.recipient)), 'sender_email': self.example_email("hamlet"), 'sender_id': 4, 'server': settings.EXTERNAL_HOST, 'realm_id': message.sender.realm.id, 'realm_uri': message.sender.realm.uri, } } } self.assertDictEqual(payload, expected) class TestGetGCMPayload(PushNotificationTest): def test_get_gcm_payload(self) -> None: stream = Stream.objects.filter(name='Verona').get() message = self.get_message(Recipient.STREAM, stream.id) message.content = 'a' * 210 message.rendered_content = 'a' * 210 message.save() message.trigger = 'mentioned' user_profile = self.example_user('hamlet') payload = apn.get_gcm_payload(user_profile, message) expected = { "user": user_profile.email, "event": "message", "alert": "New mention from King Hamlet", "zulip_message_id": message.id, "time": apn.datetime_to_timestamp(message.pub_date), "content": 'a' * 200 + '…', "content_truncated": True, "server": settings.EXTERNAL_HOST, "realm_id": self.example_user("hamlet").realm.id, "realm_uri": self.example_user("hamlet").realm.uri, "sender_id": self.example_user("hamlet").id, "sender_email": self.example_email("hamlet"), "sender_full_name": "King Hamlet", "sender_avatar_url": apn.absolute_avatar_url(message.sender), "recipient_type": "stream", "stream": apn.get_display_recipient(message.recipient), "topic": message.topic_name(), } self.assertDictEqual(payload, expected) def test_get_gcm_payload_personal(self) -> None: message = self.get_message(Recipient.PERSONAL, 1) message.trigger = 'private_message' user_profile = self.example_user('hamlet') payload = apn.get_gcm_payload(user_profile, message) expected = { "user": user_profile.email, "event": "message", "alert": "New private message from King Hamlet", "zulip_message_id": message.id, "time": apn.datetime_to_timestamp(message.pub_date), "content": message.content, "content_truncated": False, "server": settings.EXTERNAL_HOST, "realm_id": self.example_user("hamlet").realm.id, "realm_uri": self.example_user("hamlet").realm.uri, "sender_id": self.example_user("hamlet").id, "sender_email": self.example_email("hamlet"), "sender_full_name": "King Hamlet", "sender_avatar_url": apn.absolute_avatar_url(message.sender), "recipient_type": "private", } self.assertDictEqual(payload, expected) def test_get_gcm_payload_stream_notifications(self) -> None: message = self.get_message(Recipient.STREAM, 1) message.trigger = 'stream_push_notify' message.stream_name = 'Denmark' user_profile = self.example_user('hamlet') payload = apn.get_gcm_payload(user_profile, message) expected = { "user": user_profile.email, "event": "message", "alert": "New stream message from King Hamlet in Denmark", "zulip_message_id": message.id, "time": apn.datetime_to_timestamp(message.pub_date), "content": message.content, "content_truncated": False, "server": settings.EXTERNAL_HOST, "realm_id": self.example_user("hamlet").realm.id, "realm_uri": self.example_user("hamlet").realm.uri, "sender_id": self.example_user("hamlet").id, "sender_email": self.example_email("hamlet"), "sender_full_name": "King Hamlet", "sender_avatar_url": apn.absolute_avatar_url(message.sender), "recipient_type": "stream", "topic": "Test Topic", "stream": "Denmark" } self.assertDictEqual(payload, expected) @override_settings(PUSH_NOTIFICATION_REDACT_CONTENT = True) def test_get_gcm_payload_redacted_content(self) -> None: message = self.get_message(Recipient.STREAM, 1) message.trigger = 'stream_push_notify' message.stream_name = 'Denmark' user_profile = self.example_user('hamlet') payload = apn.get_gcm_payload(user_profile, message) expected = { "user": user_profile.email, "event": "message", "alert": "New stream message from King Hamlet in Denmark", "zulip_message_id": message.id, "time": apn.datetime_to_timestamp(message.pub_date), "content": "***REDACTED***", "content_truncated": False, "server": settings.EXTERNAL_HOST, "realm_id": self.example_user("hamlet").realm.id, "realm_uri": self.example_user("hamlet").realm.uri, "sender_id": self.example_user("hamlet").id, "sender_email": self.example_email("hamlet"), "sender_full_name": "King Hamlet", "sender_avatar_url": apn.absolute_avatar_url(message.sender), "recipient_type": "stream", "topic": "Test Topic", "stream": "Denmark" } self.assertDictEqual(payload, expected) class TestSendNotificationsToBouncer(ZulipTestCase): @mock.patch('zerver.lib.push_notifications.send_to_push_bouncer') def test_send_notifications_to_bouncer(self, mock_send: mock.MagicMock) -> None: apn.send_notifications_to_bouncer(1, {'apns': True}, {'gcm': True}) post_data = { 'user_id': 1, 'apns_payload': {'apns': True}, 'gcm_payload': {'gcm': True}, } mock_send.assert_called_with('POST', 'notify', ujson.dumps(post_data), extra_headers={'Content-type': 'application/json'}) class Result: def __init__(self, status: int=200, content: str=ujson.dumps({'msg': 'error'})) -> None: self.status_code = status self.content = content class TestSendToPushBouncer(PushNotificationTest): @mock.patch('requests.request', return_value=Result(status=500)) def test_500_error(self, mock_request: mock.MagicMock) -> None: with self.assertRaises(PushNotificationBouncerException) as exc: apn.send_to_push_bouncer('register', 'register', {'data': True}) self.assertEqual(str(exc.exception), 'Received 500 from push notification bouncer') @mock.patch('requests.request', return_value=Result(status=400)) def test_400_error(self, mock_request: mock.MagicMock) -> None: with self.assertRaises(apn.JsonableError) as exc: apn.send_to_push_bouncer('register', 'register', {'msg': True}) self.assertEqual(exc.exception.msg, 'error') def test_400_error_invalid_server_key(self) -> None: from zerver.decorator import InvalidZulipServerError # This is the exception our decorator uses for an invalid Zulip server error_obj = InvalidZulipServerError("testRole") with mock.patch('requests.request', return_value=Result(status=400, content=ujson.dumps(error_obj.to_json()))): with self.assertRaises(PushNotificationBouncerException) as exc: apn.send_to_push_bouncer('register', 'register', {'msg': True}) self.assertEqual(str(exc.exception), 'Push notifications bouncer error: ' 'Zulip server auth failure: testRole is not registered') @mock.patch('requests.request', return_value=Result(status=400, content='/')) def test_400_error_when_content_is_not_serializable(self, mock_request: mock.MagicMock) -> None: with self.assertRaises(ValueError) as exc: apn.send_to_push_bouncer('register', 'register', {'msg': True}) self.assertEqual(str(exc.exception), 'Expected object or value') @mock.patch('requests.request', return_value=Result(status=300, content='/')) def test_300_error(self, mock_request: mock.MagicMock) -> None: with self.assertRaises(PushNotificationBouncerException) as exc: apn.send_to_push_bouncer('register', 'register', {'msg': True}) self.assertEqual(str(exc.exception), 'Push notification bouncer returned unexpected status code 300') class TestNumPushDevicesForUser(PushNotificationTest): def test_when_kind_is_none(self) -> None: self.assertEqual(apn.num_push_devices_for_user(self.user_profile), 2) def test_when_kind_is_not_none(self) -> None: count = apn.num_push_devices_for_user(self.user_profile, kind=PushDeviceToken.APNS) self.assertEqual(count, 2) class TestPushApi(ZulipTestCase): def test_push_api(self) -> None: user = self.example_user('cordelia') email = user.email self.login(email) endpoints = [ ('/json/users/me/apns_device_token', 'apple-tokenaz'), ('/json/users/me/android_gcm_reg_id', 'android-token'), ] # Test error handling for endpoint, label in endpoints: # Try adding/removing tokens that are too big... broken_token = "a" * 5000 # too big result = self.client_post(endpoint, {'token': broken_token}) self.assert_json_error(result, 'Empty or invalid length token') if label == 'apple-tokenaz': result = self.client_post(endpoint, {'token': 'xyz has non-hex characters'}) self.assert_json_error(result, 'Invalid APNS token') result = self.client_delete(endpoint, {'token': broken_token}) self.assert_json_error(result, 'Empty or invalid length token') # Try to remove a non-existent token... result = self.client_delete(endpoint, {'token': 'abcd1234'}) self.assert_json_error(result, 'Token does not exist') # Add tokens for endpoint, token in endpoints: # Test that we can push twice result = self.client_post(endpoint, {'token': token}) self.assert_json_success(result) result = self.client_post(endpoint, {'token': token}) self.assert_json_success(result) tokens = list(PushDeviceToken.objects.filter(user=user, token=token)) self.assertEqual(len(tokens), 1) self.assertEqual(tokens[0].token, token) # User should have tokens for both devices now. tokens = list(PushDeviceToken.objects.filter(user=user)) self.assertEqual(len(tokens), 2) # Remove tokens for endpoint, token in endpoints: result = self.client_delete(endpoint, {'token': token}) self.assert_json_success(result) tokens = list(PushDeviceToken.objects.filter(user=user, token=token)) self.assertEqual(len(tokens), 0) class GCMTest(PushNotificationTest): def setUp(self) -> None: super().setUp() apn.gcm = gcm.GCM('fake key') self.gcm_tokens = [u'1111', u'2222'] for token in self.gcm_tokens: PushDeviceToken.objects.create( kind=PushDeviceToken.GCM, token=apn.hex_to_b64(token), user=self.user_profile, ios_app_id=None) def get_gcm_data(self, **kwargs: Any) -> Dict[str, Any]: data = { 'key 1': 'Data 1', 'key 2': 'Data 2', } data.update(kwargs) return data class GCMNotSetTest(GCMTest): @mock.patch('logging.warning') def test_gcm_is_none(self, mock_warning: mock.MagicMock) -> None: apn.gcm = None apn.send_android_push_notification_to_user(self.user_profile, {}) mock_warning.assert_called_with( "Skipping sending a GCM push notification since PUSH_NOTIFICATION_BOUNCER_URL " "and ANDROID_GCM_API_KEY are both unset") class GCMIOErrorTest(GCMTest): @mock.patch('zerver.lib.push_notifications.gcm.json_request') @mock.patch('logging.warning') def test_json_request_raises_ioerror(self, mock_warn: mock.MagicMock, mock_json_request: mock.MagicMock) -> None: mock_json_request.side_effect = IOError('error') apn.send_android_push_notification_to_user(self.user_profile, {}) mock_warn.assert_called_with('error') class GCMSuccessTest(GCMTest): @mock.patch('logging.warning') @mock.patch('logging.info') @mock.patch('gcm.GCM.json_request') def test_success(self, mock_send: mock.MagicMock, mock_info: mock.MagicMock, mock_warning: mock.MagicMock) -> None: res = {} res['success'] = {token: ind for ind, token in enumerate(self.gcm_tokens)} mock_send.return_value = res data = self.get_gcm_data() apn.send_android_push_notification_to_user(self.user_profile, data) self.assertEqual(mock_info.call_count, 2) c1 = call("GCM: Sent 1111 as 0") c2 = call("GCM: Sent 2222 as 1") mock_info.assert_has_calls([c1, c2], any_order=True) mock_warning.assert_not_called() class GCMCanonicalTest(GCMTest): @mock.patch('logging.warning') @mock.patch('gcm.GCM.json_request') def test_equal(self, mock_send: mock.MagicMock, mock_warning: mock.MagicMock) -> None: res = {} res['canonical'] = {1: 1} mock_send.return_value = res data = self.get_gcm_data() apn.send_android_push_notification_to_user(self.user_profile, data) mock_warning.assert_called_once_with("GCM: Got canonical ref but it " "already matches our ID 1!") @mock.patch('logging.warning') @mock.patch('gcm.GCM.json_request') def test_pushdevice_not_present(self, mock_send: mock.MagicMock, mock_warning: mock.MagicMock) -> None: res = {} t1 = apn.hex_to_b64(u'1111') t2 = apn.hex_to_b64(u'3333') res['canonical'] = {t1: t2} mock_send.return_value = res def get_count(hex_token: str) -> int: token = apn.hex_to_b64(hex_token) return PushDeviceToken.objects.filter( token=token, kind=PushDeviceToken.GCM).count() self.assertEqual(get_count(u'1111'), 1) self.assertEqual(get_count(u'3333'), 0) data = self.get_gcm_data() apn.send_android_push_notification_to_user(self.user_profile, data) msg = ("GCM: Got canonical ref %s " "replacing %s but new ID not " "registered! Updating.") mock_warning.assert_called_once_with(msg % (t2, t1)) self.assertEqual(get_count(u'1111'), 0) self.assertEqual(get_count(u'3333'), 1) @mock.patch('logging.info') @mock.patch('gcm.GCM.json_request') def test_pushdevice_different(self, mock_send: mock.MagicMock, mock_info: mock.MagicMock) -> None: res = {} old_token = apn.hex_to_b64(u'1111') new_token = apn.hex_to_b64(u'2222') res['canonical'] = {old_token: new_token} mock_send.return_value = res def get_count(hex_token: str) -> int: token = apn.hex_to_b64(hex_token) return PushDeviceToken.objects.filter( token=token, kind=PushDeviceToken.GCM).count() self.assertEqual(get_count(u'1111'), 1) self.assertEqual(get_count(u'2222'), 1) data = self.get_gcm_data() apn.send_android_push_notification_to_user(self.user_profile, data) mock_info.assert_called_once_with( "GCM: Got canonical ref %s, dropping %s" % (new_token, old_token)) self.assertEqual(get_count(u'1111'), 0) self.assertEqual(get_count(u'2222'), 1) class GCMNotRegisteredTest(GCMTest): @mock.patch('logging.info') @mock.patch('gcm.GCM.json_request') def test_not_registered(self, mock_send: mock.MagicMock, mock_info: mock.MagicMock) -> None: res = {} token = apn.hex_to_b64(u'1111') res['errors'] = {'NotRegistered': [token]} mock_send.return_value = res def get_count(hex_token: str) -> int: token = apn.hex_to_b64(hex_token) return PushDeviceToken.objects.filter( token=token, kind=PushDeviceToken.GCM).count() self.assertEqual(get_count(u'1111'), 1) data = self.get_gcm_data() apn.send_android_push_notification_to_user(self.user_profile, data) mock_info.assert_called_once_with("GCM: Removing %s" % (token,)) self.assertEqual(get_count(u'1111'), 0) class GCMFailureTest(GCMTest): @mock.patch('logging.warning') @mock.patch('gcm.GCM.json_request') def test_failure(self, mock_send: mock.MagicMock, mock_warn: mock.MagicMock) -> None: res = {} token = apn.hex_to_b64(u'1111') res['errors'] = {'Failed': [token]} mock_send.return_value = res data = self.get_gcm_data() apn.send_android_push_notification_to_user(self.user_profile, data) c1 = call("GCM: Delivery to %s failed: Failed" % (token,)) mock_warn.assert_has_calls([c1], any_order=True) class TestReceivesNotificationsFunctions(ZulipTestCase): def setUp(self) -> None: self.user = self.example_user('cordelia') def test_receivers_online_notifications_when_user_is_a_bot(self) -> None: self.user.is_bot = True self.user.enable_online_push_notifications = True self.assertFalse(receives_online_notifications(self.user)) self.user.enable_online_push_notifications = False self.assertFalse(receives_online_notifications(self.user)) def test_receivers_online_notifications_when_user_is_not_a_bot(self) -> None: self.user.is_bot = False self.user.enable_online_push_notifications = True self.assertTrue(receives_online_notifications(self.user)) self.user.enable_online_push_notifications = False self.assertFalse(receives_online_notifications(self.user)) def test_receivers_offline_notifications_when_user_is_a_bot(self) -> None: self.user.is_bot = True self.user.enable_offline_email_notifications = True self.user.enable_offline_push_notifications = True self.assertFalse(receives_offline_push_notifications(self.user)) self.assertFalse(receives_offline_email_notifications(self.user)) self.user.enable_offline_email_notifications = False self.user.enable_offline_push_notifications = False self.assertFalse(receives_offline_push_notifications(self.user)) self.assertFalse(receives_offline_email_notifications(self.user)) self.user.enable_offline_email_notifications = True self.user.enable_offline_push_notifications = False self.assertFalse(receives_offline_push_notifications(self.user)) self.assertFalse(receives_offline_email_notifications(self.user)) self.user.enable_offline_email_notifications = False self.user.enable_offline_push_notifications = True self.assertFalse(receives_offline_push_notifications(self.user)) self.assertFalse(receives_offline_email_notifications(self.user)) def test_receivers_offline_notifications_when_user_is_not_a_bot(self) -> None: self.user.is_bot = False self.user.enable_offline_email_notifications = True self.user.enable_offline_push_notifications = True self.assertTrue(receives_offline_push_notifications(self.user)) self.assertTrue(receives_offline_email_notifications(self.user)) self.user.enable_offline_email_notifications = False self.user.enable_offline_push_notifications = False self.assertFalse(receives_offline_push_notifications(self.user)) self.assertFalse(receives_offline_email_notifications(self.user)) self.user.enable_offline_email_notifications = True self.user.enable_offline_push_notifications = False self.assertFalse(receives_offline_push_notifications(self.user)) self.assertTrue(receives_offline_email_notifications(self.user)) self.user.enable_offline_email_notifications = False self.user.enable_offline_push_notifications = True self.assertTrue(receives_offline_push_notifications(self.user)) self.assertFalse(receives_offline_email_notifications(self.user)) def test_receivers_stream_notifications_when_user_is_a_bot(self) -> None: self.user.is_bot = True self.user.enable_stream_push_notifications = True self.assertFalse(receives_stream_notifications(self.user)) self.user.enable_stream_push_notifications = False self.assertFalse(receives_stream_notifications(self.user)) def test_receivers_stream_notifications_when_user_is_not_a_bot(self) -> None: self.user.is_bot = False self.user.enable_stream_push_notifications = True self.assertTrue(receives_stream_notifications(self.user)) self.user.enable_stream_push_notifications = False self.assertFalse(receives_stream_notifications(self.user)) class TestPushNotificationsContent(ZulipTestCase): def test_fixtures(self) -> None: fixtures = ujson.loads(self.fixture_data("markdown_test_cases.json")) tests = fixtures["regular_tests"] for test in tests: if "text_content" in test: output = get_mobile_push_content(test["expected_output"]) self.assertEqual(output, test["text_content"]) def test_backend_only_fixtures(self) -> None: fixtures = [ { 'name': 'realm_emoji', 'rendered_content': '<p>Testing <img alt=":green_tick:" class="emoji" src="/user_avatars/1/emoji/green_tick.png" title="green tick"> realm emoji.</p>', 'expected_output': 'Testing :green_tick: realm emoji.', }, { 'name': 'mentions', 'rendered_content': '<p>Mentioning <span class="user-mention" data-user-id="3">@Cordelia Lear</span>.</p>', 'expected_output': 'Mentioning @Cordelia Lear.', }, { 'name': 'stream_names', 'rendered_content': '<p>Testing stream names <a class="stream" data-stream-id="5" href="/#narrow/stream/Verona">#Verona</a>.</p>', 'expected_output': 'Testing stream names #Verona.', }, ] for test in fixtures: actual_output = get_mobile_push_content(test["rendered_content"]) self.assertEqual(actual_output, test["expected_output"]) class PushBouncerSignupTest(ZulipTestCase): def test_push_signup_invalid_host(self) -> None: zulip_org_id = str(uuid.uuid4()) zulip_org_key = get_random_string(64) request = dict( zulip_org_id=zulip_org_id, zulip_org_key=zulip_org_key, hostname="invalid-host", contact_email="server-admin@example.com", ) result = self.client_post("/api/v1/remotes/server/register", request) self.assert_json_error(result, "invalid-host is not a valid hostname") def test_push_signup_invalid_email(self) -> None: zulip_org_id = str(uuid.uuid4()) zulip_org_key = get_random_string(64) request = dict( zulip_org_id=zulip_org_id, zulip_org_key=zulip_org_key, hostname="example.com", contact_email="server-admin", ) result = self.client_post("/api/v1/remotes/server/register", request) self.assert_json_error(result, "Enter a valid email address.") def test_push_signup_success(self) -> None: zulip_org_id = str(uuid.uuid4()) zulip_org_key = get_random_string(64) request = dict( zulip_org_id=zulip_org_id, zulip_org_key=zulip_org_key, hostname="example.com", contact_email="server-admin@example.com", ) result = self.client_post("/api/v1/remotes/server/register", request) self.assert_json_success(result) server = RemoteZulipServer.objects.get(uuid=zulip_org_id) self.assertEqual(server.hostname, "example.com") self.assertEqual(server.contact_email, "server-admin@example.com") # Update our hostname request = dict( zulip_org_id=zulip_org_id, zulip_org_key=zulip_org_key, hostname="zulip.example.com", contact_email="server-admin@example.com", ) result = self.client_post("/api/v1/remotes/server/register", request) self.assert_json_success(result) server = RemoteZulipServer.objects.get(uuid=zulip_org_id) self.assertEqual(server.hostname, "zulip.example.com") self.assertEqual(server.contact_email, "server-admin@example.com") # Now test rotating our key request = dict( zulip_org_id=zulip_org_id, zulip_org_key=zulip_org_key, hostname="example.com", contact_email="server-admin@example.com", new_org_key=get_random_string(64), ) result = self.client_post("/api/v1/remotes/server/register", request) self.assert_json_success(result) server = RemoteZulipServer.objects.get(uuid=zulip_org_id) self.assertEqual(server.hostname, "example.com") self.assertEqual(server.contact_email, "server-admin@example.com") zulip_org_key = request["new_org_key"] self.assertEqual(server.api_key, zulip_org_key) # Update our hostname request = dict( zulip_org_id=zulip_org_id, zulip_org_key=zulip_org_key, hostname="zulip.example.com", contact_email="new-server-admin@example.com", ) result = self.client_post("/api/v1/remotes/server/register", request) self.assert_json_success(result) server = RemoteZulipServer.objects.get(uuid=zulip_org_id) self.assertEqual(server.hostname, "zulip.example.com") self.assertEqual(server.contact_email, "new-server-admin@example.com") # Now test trying to double-create with a new random key fails request = dict( zulip_org_id=zulip_org_id, zulip_org_key=get_random_string(64), hostname="example.com", contact_email="server-admin@example.com", ) result = self.client_post("/api/v1/remotes/server/register", request) self.assert_json_error(result, "Zulip server auth failure: key does not match role %s" % (zulip_org_id,))
[ "Any", "Any", "Any", "int", "Any", "Any", "Any", "Any", "Any", "mock.MagicMock", "mock.MagicMock", "mock.MagicMock", "mock.MagicMock", "mock.MagicMock", "Any", "mock.MagicMock", "mock.MagicMock", "mock.MagicMock", "mock.MagicMock", "mock.MagicMock", "mock.MagicMock", "mock.MagicMock", "mock.MagicMock", "mock.MagicMock", "mock.MagicMock", "str", "mock.MagicMock", "mock.MagicMock", "str", "mock.MagicMock", "mock.MagicMock", "str", "mock.MagicMock", "mock.MagicMock" ]
[ 1844, 1859, 9228, 13325, 14223, 14238, 18288, 18300, 18316, 45641, 46517, 46922, 48081, 48457, 51823, 52095, 52595, 52671, 53050, 53077, 53128, 53781, 53811, 54317, 54383, 54606, 55400, 55461, 55712, 56468, 56495, 56699, 57299, 57326 ]
[ 1847, 1862, 9231, 13328, 14226, 14241, 18291, 18303, 18319, 45655, 46531, 46936, 48095, 48471, 51826, 52109, 52609, 52685, 53064, 53091, 53142, 53795, 53825, 54331, 54397, 54609, 55414, 55475, 55715, 56482, 56509, 56702, 57313, 57340 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_queue.py
import mock import os from typing import Any, Dict import ujson from django.test import override_settings from pika.exceptions import ConnectionClosed, AMQPConnectionError from zerver.lib.queue import TornadoQueueClient, queue_json_publish, \ get_queue_client, SimpleQueueClient from zerver.lib.test_classes import ZulipTestCase class TestTornadoQueueClient(ZulipTestCase): @mock.patch('zerver.lib.queue.logging.getLogger', autospec=True) @mock.patch('zerver.lib.queue.ExceptionFreeTornadoConnection', autospec=True) def test_on_open_closed(self, mock_cxn: mock.MagicMock, mock_get_logger: mock.MagicMock) -> None: connection = TornadoQueueClient() connection.connection.channel.side_effect = ConnectionClosed connection._on_open(mock.MagicMock()) class TestQueueImplementation(ZulipTestCase): @override_settings(USING_RABBITMQ=True) def test_queue_basics(self) -> None: queue_client = get_queue_client() queue_client.publish("test_suite", 'test_event') result = queue_client.drain_queue("test_suite") self.assertEqual(len(result), 1) self.assertEqual(result[0], b'test_event') @override_settings(USING_RABBITMQ=True) def test_queue_basics_json(self) -> None: queue_json_publish("test_suite", {"event": "my_event"}) queue_client = get_queue_client() result = queue_client.drain_queue("test_suite", json=True) self.assertEqual(len(result), 1) self.assertEqual(result[0]['event'], 'my_event') @override_settings(USING_RABBITMQ=True) def test_register_consumer(self) -> None: output = [] queue_client = get_queue_client() def collect(event: Dict[str, Any]) -> None: output.append(event) queue_client.stop_consuming() queue_client.register_json_consumer("test_suite", collect) queue_json_publish("test_suite", {"event": "my_event"}) queue_client.start_consuming() self.assertEqual(len(output), 1) self.assertEqual(output[0]['event'], 'my_event') @override_settings(USING_RABBITMQ=True) def test_register_consumer_nack(self) -> None: output = [] count = 0 queue_client = get_queue_client() def collect(event: Dict[str, Any]) -> None: queue_client.stop_consuming() nonlocal count count += 1 if count == 1: raise Exception("Make me nack!") output.append(event) queue_client.register_json_consumer("test_suite", collect) queue_json_publish("test_suite", {"event": "my_event"}) try: queue_client.start_consuming() except Exception: queue_client.register_json_consumer("test_suite", collect) queue_client.start_consuming() # Confirm that we processed the event fully once self.assertEqual(count, 2) self.assertEqual(len(output), 1) self.assertEqual(output[0]['event'], 'my_event') @override_settings(USING_RABBITMQ=True) def test_queue_error_json(self) -> None: queue_client = get_queue_client() actual_publish = queue_client.publish self.counter = 0 def throw_connection_error_once(self_obj: Any, *args: Any, **kwargs: Any) -> None: self.counter += 1 if self.counter <= 1: raise AMQPConnectionError("test") actual_publish(*args, **kwargs) with mock.patch("zerver.lib.queue.SimpleQueueClient.publish", throw_connection_error_once): queue_json_publish("test_suite", {"event": "my_event"}) result = queue_client.drain_queue("test_suite", json=True) self.assertEqual(len(result), 1) self.assertEqual(result[0]['event'], 'my_event') @override_settings(USING_RABBITMQ=True) def tearDown(self) -> None: queue_client = get_queue_client() queue_client.drain_queue("test_suite")
[ "mock.MagicMock", "mock.MagicMock", "Dict[str, Any]", "Dict[str, Any]", "Any", "Any", "Any" ]
[ 576, 637, 1745, 2321, 3322, 3334, 3389 ]
[ 590, 651, 1759, 2335, 3325, 3337, 3392 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_queue_worker.py
import os import time import ujson import smtplib from django.conf import settings from django.http import HttpResponse from django.test import TestCase, override_settings from mock import patch, MagicMock from typing import Any, Callable, Dict, List, Mapping, Tuple from zerver.lib.send_email import FromAddress from zerver.lib.test_helpers import simulated_queue_client from zerver.lib.test_classes import ZulipTestCase from zerver.models import get_client, UserActivity, PreregistrationUser, \ get_system_bot from zerver.worker import queue_processors from zerver.worker.queue_processors import ( get_active_worker_queues, QueueProcessingWorker, EmailSendingWorker, LoopQueueProcessingWorker, MissedMessageWorker, SlowQueryWorker, ) Event = Dict[str, Any] # This is used for testing LoopQueueProcessingWorker, which # would run forever if we don't mock time.sleep to abort the # loop. class AbortLoop(Exception): pass class WorkerTest(ZulipTestCase): class FakeClient: def __init__(self) -> None: self.consumers = {} # type: Dict[str, Callable[[Dict[str, Any]], None]] self.queue = [] # type: List[Tuple[str, Any]] def register_json_consumer(self, queue_name: str, callback: Callable[[Dict[str, Any]], None]) -> None: self.consumers[queue_name] = callback def start_consuming(self) -> None: for queue_name, data in self.queue: callback = self.consumers[queue_name] callback(data) self.queue = [] def drain_queue(self, queue_name: str, json: bool) -> List[Event]: assert json events = [ dct for (queue_name, dct) in self.queue ] # IMPORTANT! # This next line prevents us from double draining # queues, which was a bug at one point. self.queue = [] return events @override_settings(SLOW_QUERY_LOGS_STREAM="errors") def test_slow_queries_worker(self) -> None: error_bot = get_system_bot(settings.ERROR_BOT) fake_client = self.FakeClient() events = [ 'test query (data)', 'second test query (data)', ] for event in events: fake_client.queue.append(('slow_queries', event)) worker = SlowQueryWorker() time_mock = patch( 'zerver.worker.queue_processors.time.sleep', side_effect=AbortLoop, ) send_mock = patch( 'zerver.worker.queue_processors.internal_send_message' ) with send_mock as sm, time_mock as tm: with simulated_queue_client(lambda: fake_client): try: worker.setup() worker.start() except AbortLoop: pass self.assertEqual(tm.call_args[0][0], 60) # should sleep 60 seconds sm.assert_called_once() args = [c[0] for c in sm.call_args_list][0] self.assertEqual(args[0], error_bot.realm) self.assertEqual(args[1], error_bot.email) self.assertEqual(args[2], "stream") self.assertEqual(args[3], "errors") self.assertEqual(args[4], "testserver: slow queries") self.assertEqual(args[5], " test query (data)\n second test query (data)\n") def test_missed_message_worker(self) -> None: cordelia = self.example_user('cordelia') hamlet = self.example_user('hamlet') othello = self.example_user('othello') hamlet1_msg_id = self.send_personal_message( from_email=cordelia.email, to_email=hamlet.email, content='hi hamlet', ) hamlet2_msg_id = self.send_personal_message( from_email=cordelia.email, to_email=hamlet.email, content='goodbye hamlet', ) hamlet3_msg_id = self.send_personal_message( from_email=cordelia.email, to_email=hamlet.email, content='hello again hamlet', ) othello_msg_id = self.send_personal_message( from_email=cordelia.email, to_email=othello.email, content='where art thou, othello?', ) events = [ dict(user_profile_id=hamlet.id, message_id=hamlet1_msg_id), dict(user_profile_id=hamlet.id, message_id=hamlet2_msg_id), dict(user_profile_id=othello.id, message_id=othello_msg_id), ] fake_client = self.FakeClient() for event in events: fake_client.queue.append(('missedmessage_emails', event)) mmw = MissedMessageWorker() class MockTimer(): is_running = False def is_alive(self) -> bool: return self.is_running def start(self) -> None: self.is_running = True def cancel(self) -> None: self.is_running = False timer = MockTimer() time_mock = patch( 'zerver.worker.queue_processors.Timer', return_value=timer, ) send_mock = patch( 'zerver.lib.notifications.do_send_missedmessage_events_reply_in_zulip' ) mmw.BATCH_DURATION = 0 bonus_event = dict(user_profile_id=hamlet.id, message_id=hamlet3_msg_id) with send_mock as sm, time_mock as tm: with simulated_queue_client(lambda: fake_client): self.assertFalse(timer.is_alive()) mmw.setup() mmw.start() self.assertTrue(timer.is_alive()) fake_client.queue.append(('missedmessage_emails', bonus_event)) # Double-calling start is our way to get it to run again self.assertTrue(timer.is_alive()) mmw.start() # Now, we actually send the emails. mmw.maybe_send_batched_emails() self.assertFalse(timer.is_alive()) self.assertEqual(tm.call_args[0][0], 5) # should sleep 5 seconds args = [c[0] for c in sm.call_args_list] arg_dict = { arg[0].id: dict( missed_messages=arg[1], count=arg[2], ) for arg in args } hamlet_info = arg_dict[hamlet.id] self.assertEqual(hamlet_info['count'], 3) self.assertEqual( {m['message'].content for m in hamlet_info['missed_messages']}, {'hi hamlet', 'goodbye hamlet', 'hello again hamlet'}, ) othello_info = arg_dict[othello.id] self.assertEqual(othello_info['count'], 1) self.assertEqual( {m['message'].content for m in othello_info['missed_messages']}, {'where art thou, othello?'} ) def test_mirror_worker(self) -> None: fake_client = self.FakeClient() data = [ dict( message=u'\xf3test', time=time.time(), rcpt_to=self.example_email('hamlet'), ), dict( message='\xf3test', time=time.time(), rcpt_to=self.example_email('hamlet'), ), dict( message='test', time=time.time(), rcpt_to=self.example_email('hamlet'), ), ] for element in data: fake_client.queue.append(('email_mirror', element)) with patch('zerver.worker.queue_processors.mirror_email'): with simulated_queue_client(lambda: fake_client): worker = queue_processors.MirrorWorker() worker.setup() worker.start() def test_email_sending_worker_retries(self) -> None: """Tests the retry_send_email_failures decorator to make sure it retries sending the email 3 times and then gives up.""" fake_client = self.FakeClient() data = { 'template_prefix': 'zerver/emails/confirm_new_email', 'to_email': self.example_email("hamlet"), 'from_name': 'Zulip Account Security', 'from_address': FromAddress.NOREPLY, 'context': {} } fake_client.queue.append(('email_senders', data)) def fake_publish(queue_name: str, event: Dict[str, Any], processor: Callable[[Any], None]) -> None: fake_client.queue.append((queue_name, event)) with simulated_queue_client(lambda: fake_client): worker = queue_processors.EmailSendingWorker() worker.setup() with patch('zerver.lib.send_email.build_email', side_effect=smtplib.SMTPServerDisconnected), \ patch('zerver.lib.queue.queue_json_publish', side_effect=fake_publish), \ patch('logging.exception'): worker.start() self.assertEqual(data['failed_tries'], 4) def test_signups_worker_retries(self) -> None: """Tests the retry logic of signups queue.""" fake_client = self.FakeClient() user_id = self.example_user('hamlet').id data = {'user_id': user_id, 'id': 'test_missed'} fake_client.queue.append(('signups', data)) def fake_publish(queue_name: str, event: Dict[str, Any], processor: Callable[[Any], None]) -> None: fake_client.queue.append((queue_name, event)) fake_response = MagicMock() fake_response.status_code = 400 fake_response.text = ujson.dumps({'title': ''}) with simulated_queue_client(lambda: fake_client): worker = queue_processors.SignupWorker() worker.setup() with patch('zerver.worker.queue_processors.requests.post', return_value=fake_response), \ patch('zerver.lib.queue.queue_json_publish', side_effect=fake_publish), \ patch('logging.info'), \ self.settings(MAILCHIMP_API_KEY='one-two', PRODUCTION=True, ZULIP_FRIENDS_LIST_ID='id'): worker.start() self.assertEqual(data['failed_tries'], 4) def test_signups_worker_existing_member(self) -> None: fake_client = self.FakeClient() user_id = self.example_user('hamlet').id data = {'user_id': user_id, 'id': 'test_missed', 'email_address': 'foo@bar.baz'} fake_client.queue.append(('signups', data)) fake_response = MagicMock() fake_response.status_code = 400 fake_response.text = ujson.dumps({'title': 'Member Exists'}) with simulated_queue_client(lambda: fake_client): worker = queue_processors.SignupWorker() worker.setup() with patch('zerver.worker.queue_processors.requests.post', return_value=fake_response), \ self.settings(MAILCHIMP_API_KEY='one-two', PRODUCTION=True, ZULIP_FRIENDS_LIST_ID='id'): with patch('logging.warning') as logging_warning_mock: worker.start() logging_warning_mock.assert_called_once_with( "Attempted to sign up already existing email to list: foo@bar.baz") def test_signups_bad_request(self) -> None: fake_client = self.FakeClient() user_id = self.example_user('hamlet').id data = {'user_id': user_id, 'id': 'test_missed'} fake_client.queue.append(('signups', data)) fake_response = MagicMock() fake_response.status_code = 444 # Any non-400 bad request code. fake_response.text = ujson.dumps({'title': 'Member Exists'}) with simulated_queue_client(lambda: fake_client): worker = queue_processors.SignupWorker() worker.setup() with patch('zerver.worker.queue_processors.requests.post', return_value=fake_response), \ self.settings(MAILCHIMP_API_KEY='one-two', PRODUCTION=True, ZULIP_FRIENDS_LIST_ID='id'): worker.start() fake_response.raise_for_status.assert_called_once() def test_invites_worker(self) -> None: fake_client = self.FakeClient() invitor = self.example_user('iago') prereg_alice = PreregistrationUser.objects.create( email=self.nonreg_email('alice'), referred_by=invitor, realm=invitor.realm) PreregistrationUser.objects.create( email=self.nonreg_email('bob'), referred_by=invitor, realm=invitor.realm) data = [ dict(prereg_id=prereg_alice.id, referrer_id=invitor.id, email_body=None), # Nonexistent prereg_id, as if the invitation was deleted dict(prereg_id=-1, referrer_id=invitor.id, email_body=None), # Form with `email` is from versions up to Zulip 1.7.1 dict(email=self.nonreg_email('bob'), referrer_id=invitor.id, email_body=None), ] for element in data: fake_client.queue.append(('invites', element)) with simulated_queue_client(lambda: fake_client): worker = queue_processors.ConfirmationEmailWorker() worker.setup() with patch('zerver.worker.queue_processors.do_send_confirmation_email'), \ patch('zerver.worker.queue_processors.create_confirmation_link'), \ patch('zerver.worker.queue_processors.send_future_email') \ as send_mock, \ patch('logging.info'): worker.start() self.assertEqual(send_mock.call_count, 2) def test_UserActivityWorker(self) -> None: fake_client = self.FakeClient() user = self.example_user('hamlet') UserActivity.objects.filter( user_profile = user.id, client = get_client('ios') ).delete() data = dict( user_profile_id = user.id, client = 'ios', time = time.time(), query = 'send_message' ) fake_client.queue.append(('user_activity', data)) with simulated_queue_client(lambda: fake_client): worker = queue_processors.UserActivityWorker() worker.setup() worker.start() activity_records = UserActivity.objects.filter( user_profile = user.id, client = get_client('ios') ) self.assertTrue(len(activity_records), 1) self.assertTrue(activity_records[0].count, 1) def test_error_handling(self) -> None: processed = [] @queue_processors.assign_queue('unreliable_worker') class UnreliableWorker(queue_processors.QueueProcessingWorker): def consume(self, data: Mapping[str, Any]) -> None: if data["type"] == 'unexpected behaviour': raise Exception('Worker task not performing as expected!') processed.append(data["type"]) fake_client = self.FakeClient() for msg in ['good', 'fine', 'unexpected behaviour', 'back to normal']: fake_client.queue.append(('unreliable_worker', {'type': msg})) fn = os.path.join(settings.QUEUE_ERROR_DIR, 'unreliable_worker.errors') try: os.remove(fn) except OSError: # nocoverage # error handling for the directory not existing pass with simulated_queue_client(lambda: fake_client): worker = UnreliableWorker() worker.setup() with patch('logging.exception') as logging_exception_mock: worker.start() logging_exception_mock.assert_called_once_with( "Problem handling data on queue unreliable_worker") self.assertEqual(processed, ['good', 'fine', 'back to normal']) line = open(fn).readline().strip() event = ujson.loads(line.split('\t')[1]) self.assertEqual(event["type"], 'unexpected behaviour') def test_worker_noname(self) -> None: class TestWorker(queue_processors.QueueProcessingWorker): def __init__(self) -> None: super().__init__() def consume(self, data: Mapping[str, Any]) -> None: pass # nocoverage # this is intentionally not called with self.assertRaises(queue_processors.WorkerDeclarationException): TestWorker() def test_worker_noconsume(self) -> None: @queue_processors.assign_queue('test_worker') class TestWorker(queue_processors.QueueProcessingWorker): def __init__(self) -> None: super().__init__() with self.assertRaises(queue_processors.WorkerDeclarationException): worker = TestWorker() worker.consume({}) def test_get_active_worker_queues(self) -> None: worker_queue_count = (len(QueueProcessingWorker.__subclasses__()) + len(EmailSendingWorker.__subclasses__()) + len(LoopQueueProcessingWorker.__subclasses__()) - 1) self.assertEqual(worker_queue_count, len(get_active_worker_queues())) self.assertEqual(1, len(get_active_worker_queues(queue_type='test')))
[ "str", "Callable[[Dict[str, Any]], None]", "str", "bool", "str", "Dict[str, Any]", "Callable[[Any], None]", "str", "Dict[str, Any]", "Callable[[Any], None]", "Mapping[str, Any]", "Mapping[str, Any]" ]
[ 1283, 1333, 1674, 1685, 8484, 8521, 8573, 9531, 9543, 9570, 15271, 16716 ]
[ 1286, 1365, 1677, 1689, 8487, 8535, 8594, 9534, 9557, 9591, 15288, 16733 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_reactions.py
# -*- coding: utf-8 -*- import ujson from django.http import HttpResponse from typing import Any, Dict, List, Mapping from unittest import mock from zerver.lib.emoji import emoji_name_to_emoji_code from zerver.lib.request import JsonableError from zerver.lib.test_helpers import tornado_redirected_to_list, get_display_recipient, \ get_test_image_file from zerver.lib.test_classes import ZulipTestCase from zerver.models import get_realm, Message, Reaction, RealmEmoji, Recipient, UserMessage class ReactionEmojiTest(ZulipTestCase): def test_missing_emoji(self) -> None: """ Sending reaction without emoji fails """ sender = self.example_email("hamlet") result = self.api_put(sender, '/api/v1/messages/1/emoji_reactions/') self.assertEqual(result.status_code, 400) def test_add_invalid_emoji(self) -> None: """ Sending invalid emoji fails """ sender = self.example_email("hamlet") result = self.api_put(sender, '/api/v1/messages/1/emoji_reactions/foo') self.assert_json_error(result, "Emoji 'foo' does not exist") def test_add_deactivated_realm_emoji(self) -> None: """ Sending deactivated realm emoji fails. """ emoji = RealmEmoji.objects.get(name="green_tick") emoji.deactivated = True emoji.save(update_fields=['deactivated']) sender = self.example_email("hamlet") result = self.api_put(sender, '/api/v1/messages/1/emoji_reactions/green_tick') self.assert_json_error(result, "Emoji 'green_tick' does not exist") def test_valid_emoji(self) -> None: """ Reacting with valid emoji succeeds """ sender = self.example_email("hamlet") result = self.api_put(sender, '/api/v1/messages/1/emoji_reactions/smile') self.assert_json_success(result) self.assertEqual(200, result.status_code) def test_zulip_emoji(self) -> None: """ Reacting with zulip emoji succeeds """ sender = self.example_email("hamlet") result = self.api_put(sender, '/api/v1/messages/1/emoji_reactions/zulip') self.assert_json_success(result) self.assertEqual(200, result.status_code) def test_valid_emoji_react_historical(self) -> None: """ Reacting with valid emoji on a historical message succeeds """ stream_name = "Saxony" self.subscribe(self.example_user("cordelia"), stream_name) message_id = self.send_stream_message(self.example_email("cordelia"), stream_name) user_profile = self.example_user('hamlet') sender = user_profile.email # Verify that hamlet did not receive the message. self.assertFalse(UserMessage.objects.filter(user_profile=user_profile, message_id=message_id).exists()) # Have hamlet react to the message result = self.api_put(sender, '/api/v1/messages/%s/emoji_reactions/smile' % (message_id,)) self.assert_json_success(result) # Fetch the now-created UserMessage object to confirm it exists and is historical user_message = UserMessage.objects.get(user_profile=user_profile, message_id=message_id) self.assertTrue(user_message.flags.historical) self.assertTrue(user_message.flags.read) self.assertFalse(user_message.flags.starred) def test_valid_realm_emoji(self) -> None: """ Reacting with valid realm emoji succeeds """ sender = self.example_email("hamlet") emoji_name = 'green_tick' result = self.api_put(sender, '/api/v1/messages/1/emoji_reactions/%s' % (emoji_name,)) self.assert_json_success(result) def test_emoji_name_to_emoji_code(self) -> None: """ An emoji name is mapped canonically to emoji code. """ realm = get_realm('zulip') realm_emoji = RealmEmoji.objects.get(name="green_tick") # Test active realm emoji. emoji_code, reaction_type = emoji_name_to_emoji_code(realm, 'green_tick') self.assertEqual(emoji_code, str(realm_emoji.id)) self.assertEqual(reaction_type, 'realm_emoji') # Test deactivated realm emoji. realm_emoji.deactivated = True realm_emoji.save(update_fields=['deactivated']) with self.assertRaises(JsonableError) as exc: emoji_name_to_emoji_code(realm, 'green_tick') self.assertEqual(str(exc.exception), "Emoji 'green_tick' does not exist") # Test ':zulip:' emoji. emoji_code, reaction_type = emoji_name_to_emoji_code(realm, 'zulip') self.assertEqual(emoji_code, 'zulip') self.assertEqual(reaction_type, 'zulip_extra_emoji') # Test unicode emoji. emoji_code, reaction_type = emoji_name_to_emoji_code(realm, 'astonished') self.assertEqual(emoji_code, '1f632') self.assertEqual(reaction_type, 'unicode_emoji') # Test override unicode emoji. overriding_emoji = RealmEmoji.objects.create( name='astonished', realm=realm, file_name='astonished') emoji_code, reaction_type = emoji_name_to_emoji_code(realm, 'astonished') self.assertEqual(emoji_code, str(overriding_emoji.id)) self.assertEqual(reaction_type, 'realm_emoji') # Test deactivate over-ridding realm emoji. overriding_emoji.deactivated = True overriding_emoji.save(update_fields=['deactivated']) emoji_code, reaction_type = emoji_name_to_emoji_code(realm, 'astonished') self.assertEqual(emoji_code, '1f632') self.assertEqual(reaction_type, 'unicode_emoji') # Test override `:zulip:` emoji. overriding_emoji = RealmEmoji.objects.create( name='zulip', realm=realm, file_name='zulip') emoji_code, reaction_type = emoji_name_to_emoji_code(realm, 'zulip') self.assertEqual(emoji_code, str(overriding_emoji.id)) self.assertEqual(reaction_type, 'realm_emoji') # Test non-existent emoji. with self.assertRaises(JsonableError) as exc: emoji_name_to_emoji_code(realm, 'invalid_emoji') self.assertEqual(str(exc.exception), "Emoji 'invalid_emoji' does not exist") class ReactionMessageIDTest(ZulipTestCase): def test_missing_message_id(self) -> None: """ Reacting without a message_id fails """ sender = self.example_email("hamlet") result = self.api_put(sender, '/api/v1/messages//emoji_reactions/smile') self.assertEqual(result.status_code, 404) def test_invalid_message_id(self) -> None: """ Reacting to an invalid message id fails """ sender = self.example_email("hamlet") result = self.api_put(sender, '/api/v1/messages/-1/emoji_reactions/smile') self.assertEqual(result.status_code, 404) def test_inaccessible_message_id(self) -> None: """ Reacting to a inaccessible (for instance, private) message fails """ pm_sender = self.example_email("hamlet") pm_recipient = self.example_email("othello") reaction_sender = self.example_email("iago") result = self.api_post(pm_sender, "/api/v1/messages", {"type": "private", "content": "Test message", "to": pm_recipient}) self.assert_json_success(result) pm_id = result.json()['id'] result = self.api_put(reaction_sender, '/api/v1/messages/%s/emoji_reactions/smile' % (pm_id,)) self.assert_json_error(result, "Invalid message(s)") class ReactionTest(ZulipTestCase): def test_add_existing_reaction(self) -> None: """ Creating the same reaction twice fails """ pm_sender = self.example_email("hamlet") pm_recipient = self.example_email("othello") reaction_sender = pm_recipient pm = self.api_post(pm_sender, "/api/v1/messages", {"type": "private", "content": "Test message", "to": pm_recipient}) self.assert_json_success(pm) content = ujson.loads(pm.content) pm_id = content['id'] first = self.api_put(reaction_sender, '/api/v1/messages/%s/emoji_reactions/smile' % (pm_id,)) self.assert_json_success(first) second = self.api_put(reaction_sender, '/api/v1/messages/%s/emoji_reactions/smile' % (pm_id,)) self.assert_json_error(second, "Reaction already exists") def test_remove_nonexisting_reaction(self) -> None: """ Removing a reaction twice fails """ pm_sender = self.example_email("hamlet") pm_recipient = self.example_email("othello") reaction_sender = pm_recipient pm = self.api_post(pm_sender, "/api/v1/messages", {"type": "private", "content": "Test message", "to": pm_recipient}) self.assert_json_success(pm) content = ujson.loads(pm.content) pm_id = content['id'] add = self.api_put(reaction_sender, '/api/v1/messages/%s/emoji_reactions/smile' % (pm_id,)) self.assert_json_success(add) first = self.api_delete(reaction_sender, '/api/v1/messages/%s/emoji_reactions/smile' % (pm_id,)) self.assert_json_success(first) second = self.api_delete(reaction_sender, '/api/v1/messages/%s/emoji_reactions/smile' % (pm_id,)) self.assert_json_error(second, "Reaction does not exist") def test_remove_existing_reaction_with_renamed_emoji(self) -> None: """ Removes an old existing reaction but the name of emoji got changed during various emoji infra changes. """ sender = self.example_email("hamlet") result = self.api_put(sender, '/api/v1/messages/1/emoji_reactions/smile') self.assert_json_success(result) with mock.patch('zerver.lib.emoji.name_to_codepoint', name_to_codepoint={}): result = self.api_delete(sender, '/api/v1/messages/1/emoji_reactions/smile') self.assert_json_success(result) def test_remove_existing_reaction_with_deactivated_realm_emoji(self) -> None: """ Removes an old existing reaction but the realm emoji used there has been deactivated. """ sender = self.example_email("hamlet") result = self.api_put(sender, '/api/v1/messages/1/emoji_reactions/green_tick') self.assert_json_success(result) # Deactivate realm emoji. emoji = RealmEmoji.objects.get(name="green_tick") emoji.deactivated = True emoji.save(update_fields=['deactivated']) result = self.api_delete(sender, '/api/v1/messages/1/emoji_reactions/green_tick') self.assert_json_success(result) class ReactionEventTest(ZulipTestCase): def test_add_event(self) -> None: """ Recipients of the message receive the reaction event and event contains relevant data """ pm_sender = self.example_user('hamlet') pm_recipient = self.example_user('othello') reaction_sender = pm_recipient result = self.api_post(pm_sender.email, "/api/v1/messages", {"type": "private", "content": "Test message", "to": pm_recipient.email}) self.assert_json_success(result) pm_id = result.json()['id'] expected_recipient_ids = set([pm_sender.id, pm_recipient.id]) events = [] # type: List[Mapping[str, Any]] with tornado_redirected_to_list(events): result = self.api_put(reaction_sender.email, '/api/v1/messages/%s/emoji_reactions/smile' % (pm_id,)) self.assert_json_success(result) self.assertEqual(len(events), 1) event = events[0]['event'] event_user_ids = set(events[0]['users']) self.assertEqual(expected_recipient_ids, event_user_ids) self.assertEqual(event['user']['email'], reaction_sender.email) self.assertEqual(event['type'], 'reaction') self.assertEqual(event['op'], 'add') self.assertEqual(event['emoji_name'], 'smile') self.assertEqual(event['message_id'], pm_id) def test_remove_event(self) -> None: """ Recipients of the message receive the reaction event and event contains relevant data """ pm_sender = self.example_user('hamlet') pm_recipient = self.example_user('othello') reaction_sender = pm_recipient result = self.api_post(pm_sender.email, "/api/v1/messages", {"type": "private", "content": "Test message", "to": pm_recipient.email}) self.assert_json_success(result) content = result.json() pm_id = content['id'] expected_recipient_ids = set([pm_sender.id, pm_recipient.id]) add = self.api_put(reaction_sender.email, '/api/v1/messages/%s/emoji_reactions/smile' % (pm_id,)) self.assert_json_success(add) events = [] # type: List[Mapping[str, Any]] with tornado_redirected_to_list(events): result = self.api_delete(reaction_sender.email, '/api/v1/messages/%s/emoji_reactions/smile' % (pm_id,)) self.assert_json_success(result) self.assertEqual(len(events), 1) event = events[0]['event'] event_user_ids = set(events[0]['users']) self.assertEqual(expected_recipient_ids, event_user_ids) self.assertEqual(event['user']['email'], reaction_sender.email) self.assertEqual(event['type'], 'reaction') self.assertEqual(event['op'], 'remove') self.assertEqual(event['emoji_name'], 'smile') self.assertEqual(event['message_id'], pm_id) class EmojiReactionBase(ZulipTestCase): def __init__(self, *args: Any, **kwargs: Any) -> None: self.reaction_type = 'realm_emoji' super().__init__(*args, **kwargs) def post_reaction(self, reaction_info: Dict[str, str], message_id: int=1, sender: str='hamlet') -> HttpResponse: if 'reaction_type' not in reaction_info: reaction_info['reaction_type'] = self.reaction_type sender = self.example_email(sender) result = self.api_post(sender, '/api/v1/messages/%s/reactions' % (message_id,), reaction_info) return result def post_zulip_reaction(self, message_id: int=1, sender: str='hamlet') -> HttpResponse: reaction_info = { 'emoji_name': 'zulip', 'emoji_code': 'zulip', 'reaction_type': 'zulip_extra_emoji', } result = self.post_reaction(reaction_info, message_id, sender) return result def delete_reaction(self, reaction_info: Dict[str, str], message_id: int=1, sender: str='hamlet') -> HttpResponse: if 'reaction_type' not in reaction_info: reaction_info['reaction_type'] = self.reaction_type sender = self.example_email(sender) result = self.api_delete(sender, '/api/v1/messages/%s/reactions' % (message_id,), reaction_info) return result def delete_zulip_reaction(self, message_id: int=1, sender: str='hamlet') -> HttpResponse: reaction_info = { 'emoji_name': 'zulip', 'emoji_code': 'zulip', 'reaction_type': 'zulip_extra_emoji', } result = self.delete_reaction(reaction_info, message_id, sender) return result def get_message_reactions(self, message_id: int, emoji_code: str, reaction_type: str) -> List[Reaction]: message = Message.objects.get(id=message_id) reactions = Reaction.objects.filter(message=message, emoji_code=emoji_code, reaction_type=reaction_type) return list(reactions) class DefaultEmojiReactionTests(EmojiReactionBase): def setUp(self) -> None: self.reaction_type = 'unicode_emoji' reaction_info = { 'emoji_name': 'hamburger', 'emoji_code': '1f354', } result = self.post_reaction(reaction_info) self.assert_json_success(result) def test_add_default_emoji_reaction(self) -> None: reaction_info = { 'emoji_name': 'thumbs_up', 'emoji_code': '1f44d', } result = self.post_reaction(reaction_info) self.assert_json_success(result) def test_add_default_emoji_invalid_code(self) -> None: reaction_info = { 'emoji_name': 'hamburger', 'emoji_code': 'TBD', } result = self.post_reaction(reaction_info) self.assert_json_error(result, 'Invalid emoji code.') def test_add_default_emoji_invalid_name(self) -> None: reaction_info = { 'emoji_name': 'non-existent', 'emoji_code': '1f44d', } result = self.post_reaction(reaction_info) self.assert_json_error(result, 'Invalid emoji name.') def test_add_to_existing_renamed_default_emoji_reaction(self) -> None: hamlet = self.example_user('hamlet') message = Message.objects.get(id=1) reaction = Reaction.objects.create(user_profile=hamlet, message=message, emoji_name='old_name', emoji_code='1f603', reaction_type='unicode_emoji', ) reaction_info = { 'emoji_name': 'smiley', 'emoji_code': '1f603', } result = self.post_reaction(reaction_info, sender='AARON') self.assert_json_success(result) reactions = self.get_message_reactions(1, '1f603', 'unicode_emoji') for reaction in reactions: self.assertEqual(reaction.emoji_name, 'old_name') def test_add_duplicate_reaction(self) -> None: reaction_info = { 'emoji_name': 'non-existent', 'emoji_code': '1f354', } result = self.post_reaction(reaction_info) self.assert_json_error(result, 'Reaction already exists.') def test_add_reaction_by_name(self) -> None: reaction_info = { 'emoji_name': '+1' } result = self.post_reaction(reaction_info) self.assert_json_success(result) hamlet = self.example_user('hamlet') message = Message.objects.get(id=1) self.assertTrue( Reaction.objects.filter(user_profile=hamlet, message=message, emoji_name=reaction_info['emoji_name'], emoji_code='1f44d', reaction_type='unicode_emoji').exists() ) def test_preserve_non_canonical_name(self) -> None: reaction_info = { 'emoji_name': '+1', 'emoji_code': '1f44d', } result = self.post_reaction(reaction_info) self.assert_json_success(result) reactions = self.get_message_reactions(1, '1f44d', 'unicode_emoji') for reaction in reactions: self.assertEqual(reaction.emoji_name, '+1') def test_reaction_name_collapse(self) -> None: reaction_info = { 'emoji_name': '+1', 'emoji_code': '1f44d', } result = self.post_reaction(reaction_info) self.assert_json_success(result) reaction_info['emoji_name'] = 'thumbs_up' result = self.post_reaction(reaction_info, sender='AARON') self.assert_json_success(result) reactions = self.get_message_reactions(1, '1f44d', 'unicode_emoji') for reaction in reactions: self.assertEqual(reaction.emoji_name, '+1') def test_delete_default_emoji_reaction(self) -> None: reaction_info = { 'emoji_name': 'hamburger', 'emoji_code': '1f354', } result = self.delete_reaction(reaction_info) self.assert_json_success(result) def test_delete_insufficient_arguments_reaction(self) -> None: result = self.delete_reaction({}) self.assert_json_error(result, 'At least one of the following ' 'arguments must be present: emoji_name, ' 'emoji_code') def test_delete_non_existing_emoji_reaction(self) -> None: reaction_info = { 'emoji_name': 'thumbs_up', 'emoji_code': '1f44d', } result = self.delete_reaction(reaction_info) self.assert_json_error(result, "Reaction doesn't exist.") def test_delete_renamed_default_emoji(self) -> None: hamlet = self.example_user('hamlet') message = Message.objects.get(id=1) Reaction.objects.create(user_profile=hamlet, message=message, emoji_name='old_name', emoji_code='1f44f', reaction_type='unicode_emoji', ) reaction_info = { 'emoji_name': 'new_name', 'emoji_code': '1f44f', } result = self.delete_reaction(reaction_info) self.assert_json_success(result) def test_delete_reaction_by_name(self) -> None: hamlet = self.example_user('hamlet') message = Message.objects.get(id=1) Reaction.objects.create(user_profile=hamlet, message=message, emoji_name='+1', emoji_code='1f44d', reaction_type='unicode_emoji', ) reaction_info = { 'emoji_name': '+1' } result = self.delete_reaction(reaction_info) self.assert_json_success(result) self.assertFalse( Reaction.objects.filter(user_profile=hamlet, message=message, emoji_name=reaction_info['emoji_name'], emoji_code='1f44d', reaction_type='unicode_emoji').exists() ) def test_react_historical(self) -> None: """ Reacting with valid emoji on a historical message succeeds. """ stream_name = "Saxony" self.subscribe(self.example_user("cordelia"), stream_name) message_id = self.send_stream_message(self.example_email("cordelia"), stream_name) user_profile = self.example_user('hamlet') # Verify that hamlet did not receive the message. self.assertFalse(UserMessage.objects.filter(user_profile=user_profile, message_id=message_id).exists()) # Have hamlet react to the message reaction_info = { 'emoji_name': 'hamburger', 'emoji_code': '1f354', } result = self.post_reaction(reaction_info, message_id=message_id) self.assert_json_success(result) # Fetch the now-created UserMessage object to confirm it exists and is historical user_message = UserMessage.objects.get(user_profile=user_profile, message_id=message_id) self.assertTrue(user_message.flags.historical) self.assertTrue(user_message.flags.read) self.assertFalse(user_message.flags.starred) class ZulipExtraEmojiReactionTest(EmojiReactionBase): def test_add_zulip_emoji_reaction(self) -> None: result = self.post_zulip_reaction() self.assert_json_success(result) def test_add_duplicate_zulip_reaction(self) -> None: result = self.post_zulip_reaction() self.assert_json_success(result) result = self.post_zulip_reaction() self.assert_json_error(result, 'Reaction already exists.') def test_add_invalid_extra_emoji(self) -> None: reaction_info = { 'emoji_name': 'extra_emoji', 'emoji_code': 'extra_emoji', 'reaction_type': 'zulip_extra_emoji', } result = self.post_reaction(reaction_info) self.assert_json_error(result, 'Invalid emoji code.') def test_add_invalid_emoji_name(self) -> None: reaction_info = { 'emoji_name': 'zulip_invalid', 'emoji_code': 'zulip', 'reaction_type': 'zulip_extra_emoji', } result = self.post_reaction(reaction_info) self.assert_json_error(result, 'Invalid emoji name.') def test_delete_zulip_emoji(self) -> None: result = self.post_zulip_reaction() self.assert_json_success(result) result = self.delete_zulip_reaction() self.assert_json_success(result) def test_delete_non_existent_zulip_reaction(self) -> None: result = self.delete_zulip_reaction() self.assert_json_error(result, "Reaction doesn't exist.") class RealmEmojiReactionTests(EmojiReactionBase): def setUp(self) -> None: green_tick_emoji = RealmEmoji.objects.get(name="green_tick") self.default_reaction_info = { 'emoji_name': 'green_tick', 'emoji_code': str(green_tick_emoji.id), } def test_add_realm_emoji(self) -> None: result = self.post_reaction(self.default_reaction_info) self.assert_json_success(result) def test_add_realm_emoji_invalid_code(self) -> None: reaction_info = { 'emoji_name': 'green_tick', 'emoji_code': '9999', } result = self.post_reaction(reaction_info) self.assert_json_error(result, 'Invalid custom emoji.') def test_add_realm_emoji_invalid_name(self) -> None: green_tick_emoji = RealmEmoji.objects.get(name="green_tick") reaction_info = { 'emoji_name': 'bogus_name', 'emoji_code': str(green_tick_emoji.id), } result = self.post_reaction(reaction_info) self.assert_json_error(result, 'Invalid custom emoji name.') def test_add_deactivated_realm_emoji(self) -> None: emoji = RealmEmoji.objects.get(name="green_tick") emoji.deactivated = True emoji.save(update_fields=['deactivated']) result = self.post_reaction(self.default_reaction_info) self.assert_json_error(result, 'This custom emoji has been deactivated.') def test_add_to_existing_deactivated_realm_emoji_reaction(self) -> None: result = self.post_reaction(self.default_reaction_info) self.assert_json_success(result) emoji = RealmEmoji.objects.get(name="green_tick") emoji.deactivated = True emoji.save(update_fields=['deactivated']) result = self.post_reaction(self.default_reaction_info, sender='AARON') self.assert_json_success(result) reactions = self.get_message_reactions(1, self.default_reaction_info['emoji_code'], 'realm_emoji') self.assertEqual(len(reactions), 2) def test_remove_realm_emoji_reaction(self) -> None: result = self.post_reaction(self.default_reaction_info) self.assert_json_success(result) result = self.delete_reaction(self.default_reaction_info) self.assert_json_success(result) def test_remove_deactivated_realm_emoji_reaction(self) -> None: result = self.post_reaction(self.default_reaction_info) self.assert_json_success(result) emoji = RealmEmoji.objects.get(name="green_tick") emoji.deactivated = True emoji.save(update_fields=['deactivated']) result = self.delete_reaction(self.default_reaction_info) self.assert_json_success(result) def test_remove_non_existent_realm_emoji_reaction(self) -> None: reaction_info = { 'emoji_name': 'non_existent', 'emoji_code': 'TBD', } result = self.delete_reaction(reaction_info) self.assert_json_error(result, "Reaction doesn't exist.") def test_invalid_reaction_type(self) -> None: reaction_info = { 'emoji_name': 'zulip', 'emoji_code': 'zulip', 'reaction_type': 'nonexistent_emoji_type', } sender = self.example_email("hamlet") message_id = 1 result = self.api_post(sender, '/api/v1/messages/%s/reactions' % (message_id,), reaction_info) self.assert_json_error(result, "Invalid emoji type.") class ReactionAPIEventTest(EmojiReactionBase): def test_add_event(self) -> None: """ Recipients of the message receive the reaction event and event contains relevant data """ pm_sender = self.example_user('hamlet') pm_recipient = self.example_user('othello') reaction_sender = pm_recipient pm_id = self.send_personal_message(pm_sender.email, pm_recipient.email) expected_recipient_ids = set([pm_sender.id, pm_recipient.id]) reaction_info = { 'emoji_name': 'hamburger', 'emoji_code': '1f354', 'reaction_type': 'unicode_emoji', } events = [] # type: List[Mapping[str, Any]] with tornado_redirected_to_list(events): result = self.post_reaction(reaction_info, message_id=pm_id, sender=reaction_sender.short_name) self.assert_json_success(result) self.assertEqual(len(events), 1) event = events[0]['event'] event_user_ids = set(events[0]['users']) self.assertEqual(expected_recipient_ids, event_user_ids) self.assertEqual(event['user']['user_id'], reaction_sender.id) self.assertEqual(event['user']['email'], reaction_sender.email) self.assertEqual(event['user']['full_name'], reaction_sender.full_name) self.assertEqual(event['type'], 'reaction') self.assertEqual(event['op'], 'add') self.assertEqual(event['message_id'], pm_id) self.assertEqual(event['emoji_name'], reaction_info['emoji_name']) self.assertEqual(event['emoji_code'], reaction_info['emoji_code']) self.assertEqual(event['reaction_type'], reaction_info['reaction_type']) def test_remove_event(self) -> None: """ Recipients of the message receive the reaction event and event contains relevant data """ pm_sender = self.example_user('hamlet') pm_recipient = self.example_user('othello') reaction_sender = pm_recipient pm_id = self.send_personal_message(pm_sender.email, pm_recipient.email) expected_recipient_ids = set([pm_sender.id, pm_recipient.id]) reaction_info = { 'emoji_name': 'hamburger', 'emoji_code': '1f354', 'reaction_type': 'unicode_emoji', } add = self.post_reaction(reaction_info, message_id=pm_id, sender=reaction_sender.short_name) self.assert_json_success(add) events = [] # type: List[Mapping[str, Any]] with tornado_redirected_to_list(events): result = self.delete_reaction(reaction_info, message_id=pm_id, sender=reaction_sender.short_name) self.assert_json_success(result) self.assertEqual(len(events), 1) event = events[0]['event'] event_user_ids = set(events[0]['users']) self.assertEqual(expected_recipient_ids, event_user_ids) self.assertEqual(event['user']['user_id'], reaction_sender.id) self.assertEqual(event['user']['email'], reaction_sender.email) self.assertEqual(event['user']['full_name'], reaction_sender.full_name) self.assertEqual(event['type'], 'reaction') self.assertEqual(event['op'], 'remove') self.assertEqual(event['message_id'], pm_id) self.assertEqual(event['emoji_name'], reaction_info['emoji_name']) self.assertEqual(event['emoji_code'], reaction_info['emoji_code']) self.assertEqual(event['reaction_type'], reaction_info['reaction_type'])
[ "Any", "Any", "Dict[str, str]", "Dict[str, str]", "int", "str", "str" ]
[ 14279, 14294, 14437, 15235, 16045, 16062, 16112 ]
[ 14282, 14297, 14451, 15249, 16048, 16065, 16115 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_realm.py
import datetime import ujson import re import mock from django.conf import settings from django.http import HttpResponse from django.conf import settings from mock import patch from typing import Any, Dict, List, Union, Mapping from zerver.lib.actions import ( do_change_is_admin, do_change_realm_subdomain, do_set_realm_property, do_deactivate_realm, do_deactivate_stream, do_create_realm, do_scrub_realm, create_stream_if_needed, do_change_plan_type, ) from zerver.lib.send_email import send_future_email from zerver.lib.test_classes import ZulipTestCase from zerver.lib.test_helpers import tornado_redirected_to_list from zerver.lib.test_runner import slow from zerver.models import get_realm, Realm, UserProfile, ScheduledEmail, get_stream, \ CustomProfileField, Message, UserMessage, Attachment, get_user_profile_by_email class RealmTest(ZulipTestCase): def assert_user_profile_cache_gets_new_name(self, user_profile: UserProfile, new_realm_name: str) -> None: self.assertEqual(user_profile.realm.name, new_realm_name) def test_do_set_realm_name_caching(self) -> None: """The main complicated thing about setting realm names is fighting the cache, and we start by populating the cache for Hamlet, and we end by checking the cache to ensure that the new value is there.""" self.example_user('hamlet') realm = get_realm('zulip') new_name = u'Zed You Elle Eye Pea' do_set_realm_property(realm, 'name', new_name) self.assertEqual(get_realm(realm.string_id).name, new_name) self.assert_user_profile_cache_gets_new_name(self.example_user('hamlet'), new_name) def test_update_realm_name_events(self) -> None: realm = get_realm('zulip') new_name = u'Puliz' events = [] # type: List[Mapping[str, Any]] with tornado_redirected_to_list(events): do_set_realm_property(realm, 'name', new_name) event = events[0]['event'] self.assertEqual(event, dict( type='realm', op='update', property='name', value=new_name, )) def test_update_realm_description_events(self) -> None: realm = get_realm('zulip') new_description = u'zulip dev group' events = [] # type: List[Mapping[str, Any]] with tornado_redirected_to_list(events): do_set_realm_property(realm, 'description', new_description) event = events[0]['event'] self.assertEqual(event, dict( type='realm', op='update', property='description', value=new_description, )) def test_update_realm_description(self) -> None: email = self.example_email("iago") self.login(email) realm = get_realm('zulip') new_description = u'zulip dev group' data = dict(description=ujson.dumps(new_description)) events = [] # type: List[Mapping[str, Any]] with tornado_redirected_to_list(events): result = self.client_patch('/json/realm', data) self.assert_json_success(result) realm = get_realm('zulip') self.assertEqual(realm.description, new_description) event = events[0]['event'] self.assertEqual(event, dict( type='realm', op='update', property='description', value=new_description, )) def test_realm_description_length(self) -> None: new_description = u'A' * 1001 data = dict(description=ujson.dumps(new_description)) # create an admin user email = self.example_email("iago") self.login(email) result = self.client_patch('/json/realm', data) self.assert_json_error(result, 'Organization description is too long.') realm = get_realm('zulip') self.assertNotEqual(realm.description, new_description) def test_realm_name_length(self) -> None: new_name = u'A' * (Realm.MAX_REALM_NAME_LENGTH + 1) data = dict(name=ujson.dumps(new_name)) # create an admin user email = self.example_email("iago") self.login(email) result = self.client_patch('/json/realm', data) self.assert_json_error(result, 'Organization name is too long.') realm = get_realm('zulip') self.assertNotEqual(realm.name, new_name) def test_admin_restrictions_for_changing_realm_name(self) -> None: new_name = 'Mice will play while the cat is away' user_profile = self.example_user('othello') email = user_profile.email self.login(email) do_change_is_admin(user_profile, False) req = dict(name=ujson.dumps(new_name)) result = self.client_patch('/json/realm', req) self.assert_json_error(result, 'Must be an organization administrator') def test_unauthorized_name_change(self) -> None: data = {'full_name': 'Sir Hamlet'} user_profile = self.example_user('hamlet') email = user_profile.email self.login(email) do_set_realm_property(user_profile.realm, 'name_changes_disabled', True) url = '/json/settings' result = self.client_patch(url, data) self.assertEqual(result.status_code, 200) # Since the setting fails silently, no message is returned self.assert_in_response("", result) # Realm admins can change their name even setting is disabled. data = {'full_name': 'New Iago'} self.login(self.example_email("iago")) url = '/json/settings' result = self.client_patch(url, data) self.assert_in_success_response(['"full_name":"New Iago"'], result) def test_do_deactivate_realm_clears_user_realm_cache(self) -> None: """The main complicated thing about deactivating realm names is updating the cache, and we start by populating the cache for Hamlet, and we end by checking the cache to ensure that his realm appears to be deactivated. You can make this test fail by disabling cache.flush_realm().""" self.example_user('hamlet') realm = get_realm('zulip') do_deactivate_realm(realm) user = self.example_user('hamlet') self.assertTrue(user.realm.deactivated) def test_do_change_realm_subdomain_clears_user_realm_cache(self) -> None: """The main complicated thing about changing realm subdomains is updating the cache, and we start by populating the cache for Hamlet, and we end by checking the cache to ensure that his realm appears to be deactivated. You can make this test fail by disabling cache.flush_realm().""" user = get_user_profile_by_email('hamlet@zulip.com') realm = get_realm('zulip') do_change_realm_subdomain(realm, "newzulip") user = get_user_profile_by_email('hamlet@zulip.com') self.assertEqual(user.realm.string_id, "newzulip") # This doesn't use a cache right now, but may later. self.assertIsNone(get_realm("zulip")) def test_do_deactivate_realm_clears_scheduled_jobs(self) -> None: user = self.example_user('hamlet') send_future_email('zerver/emails/followup_day1', user.realm, to_user_id=user.id, delay=datetime.timedelta(hours=1)) self.assertEqual(ScheduledEmail.objects.count(), 1) do_deactivate_realm(user.realm) self.assertEqual(ScheduledEmail.objects.count(), 0) def test_do_deactivate_realm_on_deactived_realm(self) -> None: """Ensure early exit is working in realm deactivation""" realm = get_realm('zulip') self.assertFalse(realm.deactivated) do_deactivate_realm(realm) self.assertTrue(realm.deactivated) do_deactivate_realm(realm) self.assertTrue(realm.deactivated) def test_change_notifications_stream(self) -> None: # We need an admin user. email = 'iago@zulip.com' self.login(email) disabled_notif_stream_id = -1 req = dict(notifications_stream_id = ujson.dumps(disabled_notif_stream_id)) result = self.client_patch('/json/realm', req) self.assert_json_success(result) realm = get_realm('zulip') self.assertEqual(realm.notifications_stream, None) new_notif_stream_id = 4 req = dict(notifications_stream_id = ujson.dumps(new_notif_stream_id)) result = self.client_patch('/json/realm', req) self.assert_json_success(result) realm = get_realm('zulip') self.assertEqual(realm.notifications_stream.id, new_notif_stream_id) invalid_notif_stream_id = 1234 req = dict(notifications_stream_id = ujson.dumps(invalid_notif_stream_id)) result = self.client_patch('/json/realm', req) self.assert_json_error(result, 'Invalid stream id') realm = get_realm('zulip') self.assertNotEqual(realm.notifications_stream.id, invalid_notif_stream_id) def test_get_default_notifications_stream(self) -> None: realm = get_realm("zulip") verona = get_stream("verona", realm) realm.notifications_stream_id = verona.id realm.save(update_fields=["notifications_stream"]) notifications_stream = realm.get_notifications_stream() self.assertEqual(notifications_stream.id, verona.id) do_deactivate_stream(notifications_stream) self.assertIsNone(realm.get_notifications_stream()) def test_change_signup_notifications_stream(self) -> None: # We need an admin user. email = 'iago@zulip.com' self.login(email) disabled_signup_notifications_stream_id = -1 req = dict(signup_notifications_stream_id = ujson.dumps(disabled_signup_notifications_stream_id)) result = self.client_patch('/json/realm', req) self.assert_json_success(result) realm = get_realm('zulip') self.assertEqual(realm.signup_notifications_stream, None) new_signup_notifications_stream_id = 4 req = dict(signup_notifications_stream_id = ujson.dumps(new_signup_notifications_stream_id)) result = self.client_patch('/json/realm', req) self.assert_json_success(result) realm = get_realm('zulip') self.assertEqual(realm.signup_notifications_stream.id, new_signup_notifications_stream_id) invalid_signup_notifications_stream_id = 1234 req = dict(signup_notifications_stream_id = ujson.dumps(invalid_signup_notifications_stream_id)) result = self.client_patch('/json/realm', req) self.assert_json_error(result, 'Invalid stream id') realm = get_realm('zulip') self.assertNotEqual(realm.signup_notifications_stream.id, invalid_signup_notifications_stream_id) def test_get_default_signup_notifications_stream(self) -> None: realm = get_realm("zulip") verona = get_stream("verona", realm) realm.signup_notifications_stream = verona realm.save(update_fields=["signup_notifications_stream"]) signup_notifications_stream = realm.get_signup_notifications_stream() self.assertEqual(signup_notifications_stream, verona) do_deactivate_stream(signup_notifications_stream) self.assertIsNone(realm.get_signup_notifications_stream()) def test_change_realm_default_language(self) -> None: new_lang = "de" realm = get_realm('zulip') self.assertNotEqual(realm.default_language, new_lang) # we need an admin user. email = self.example_email("iago") self.login(email) req = dict(default_language=ujson.dumps(new_lang)) result = self.client_patch('/json/realm', req) self.assert_json_success(result) realm = get_realm('zulip') self.assertEqual(realm.default_language, new_lang) # Test to make sure that when invalid languages are passed # as the default realm language, correct validation error is # raised and the invalid language is not saved in db invalid_lang = "invalid_lang" req = dict(default_language=ujson.dumps(invalid_lang)) result = self.client_patch('/json/realm', req) self.assert_json_error(result, "Invalid language '%s'" % (invalid_lang,)) realm = get_realm('zulip') self.assertNotEqual(realm.default_language, invalid_lang) def test_deactivate_realm_by_admin(self) -> None: email = self.example_email('iago') self.login(email) realm = get_realm('zulip') self.assertFalse(realm.deactivated) result = self.client_post('/json/realm/deactivate') self.assert_json_success(result) realm = get_realm('zulip') self.assertTrue(realm.deactivated) def test_deactivate_realm_by_non_admin(self) -> None: email = self.example_email('hamlet') self.login(email) realm = get_realm('zulip') self.assertFalse(realm.deactivated) result = self.client_post('/json/realm/deactivate') self.assert_json_error(result, "Must be an organization administrator") realm = get_realm('zulip') self.assertFalse(realm.deactivated) def test_change_bot_creation_policy(self) -> None: # We need an admin user. email = 'iago@zulip.com' self.login(email) req = dict(bot_creation_policy = ujson.dumps(Realm.BOT_CREATION_LIMIT_GENERIC_BOTS)) result = self.client_patch('/json/realm', req) self.assert_json_success(result) invalid_add_bot_permission = 4 req = dict(bot_creation_policy = ujson.dumps(invalid_add_bot_permission)) result = self.client_patch('/json/realm', req) self.assert_json_error(result, 'Invalid bot creation policy') def test_change_video_chat_provider(self) -> None: self.assertEqual(get_realm('zulip').video_chat_provider, "Jitsi") email = self.example_email("iago") self.login(email) req = {"video_chat_provider": ujson.dumps("Google Hangouts")} result = self.client_patch('/json/realm', req) self.assert_json_error(result, "Invalid domain: Domain can't be empty.") req = { "video_chat_provider": ujson.dumps("Google Hangouts"), "google_hangouts_domain": ujson.dumps("invaliddomain"), } result = self.client_patch('/json/realm', req) self.assert_json_error(result, "Invalid domain: Domain must have at least one dot (.)") req = { "video_chat_provider": ujson.dumps("Google Hangouts"), "google_hangouts_domain": ujson.dumps("zulip.com"), } result = self.client_patch('/json/realm', req) self.assert_json_success(result) self.assertEqual(get_realm('zulip').video_chat_provider, "Google Hangouts") req = {"video_chat_provider": ujson.dumps("Jitsi")} result = self.client_patch('/json/realm', req) self.assert_json_success(result) self.assertEqual(get_realm('zulip').video_chat_provider, "Jitsi") def test_initial_plan_type(self) -> None: with self.settings(BILLING_ENABLED=True): self.assertEqual(do_create_realm('hosted', 'hosted').plan_type, Realm.LIMITED) self.assertEqual(get_realm("hosted").max_invites, settings.INVITES_DEFAULT_REALM_DAILY_MAX) self.assertEqual(get_realm("hosted").message_visibility_limit, Realm.MESSAGE_VISIBILITY_LIMITED) with self.settings(BILLING_ENABLED=False): self.assertEqual(do_create_realm('onpremise', 'onpremise').plan_type, Realm.SELF_HOSTED) self.assertEqual(get_realm('onpremise').max_invites, settings.INVITES_DEFAULT_REALM_DAILY_MAX) self.assertEqual(get_realm('onpremise').message_visibility_limit, None) def test_change_plan_type(self) -> None: user = self.example_user('iago') realm = get_realm('zulip') self.assertEqual(realm.plan_type, Realm.SELF_HOSTED) self.assertEqual(realm.max_invites, settings.INVITES_DEFAULT_REALM_DAILY_MAX) self.assertEqual(realm.message_visibility_limit, None) do_change_plan_type(user, Realm.STANDARD) realm = get_realm('zulip') self.assertEqual(realm.max_invites, Realm.INVITES_STANDARD_REALM_DAILY_MAX) self.assertEqual(realm.message_visibility_limit, None) do_change_plan_type(user, Realm.LIMITED) realm = get_realm('zulip') self.assertEqual(realm.max_invites, settings.INVITES_DEFAULT_REALM_DAILY_MAX) self.assertEqual(realm.message_visibility_limit, Realm.MESSAGE_VISIBILITY_LIMITED) do_change_plan_type(user, Realm.STANDARD_FREE) realm = get_realm('zulip') self.assertEqual(realm.max_invites, Realm.INVITES_STANDARD_REALM_DAILY_MAX) self.assertEqual(realm.message_visibility_limit, None) class RealmAPITest(ZulipTestCase): def setUp(self) -> None: user_profile = self.example_user('cordelia') email = user_profile.email self.login(email) do_change_is_admin(user_profile, True) def set_up_db(self, attr: str, value: Any) -> None: realm = get_realm('zulip') setattr(realm, attr, value) realm.save(update_fields=[attr]) def update_with_api(self, name: str, value: int) -> Realm: result = self.client_patch('/json/realm', {name: ujson.dumps(value)}) self.assert_json_success(result) return get_realm('zulip') # refresh data def do_test_realm_update_api(self, name: str) -> None: """Test updating realm properties. If new realm properties have been added to the Realm model but the test_values dict below has not been updated, this will raise an assertion error. """ bool_tests = [False, True] # type: List[bool] test_values = dict( default_language=[u'de', u'en'], description=[u'Realm description', u'New description'], message_retention_days=[10, 20], name=[u'Zulip', u'New Name'], waiting_period_threshold=[10, 20], bot_creation_policy=[1, 2], video_chat_provider=[u'Jitsi', u'Hangouts'], google_hangouts_domain=[u'zulip.com', u'zulip.org'], ) # type: Dict[str, Any] vals = test_values.get(name) if Realm.property_types[name] is bool: vals = bool_tests if vals is None: raise AssertionError('No test created for %s' % (name)) self.set_up_db(name, vals[0]) realm = self.update_with_api(name, vals[1]) self.assertEqual(getattr(realm, name), vals[1]) realm = self.update_with_api(name, vals[0]) self.assertEqual(getattr(realm, name), vals[0]) @slow("Tests a dozen properties in a loop") def test_update_realm_properties(self) -> None: for prop in Realm.property_types: self.do_test_realm_update_api(prop) def test_update_realm_allow_message_editing(self) -> None: """Tests updating the realm property 'allow_message_editing'.""" self.set_up_db('allow_message_editing', False) self.set_up_db('message_content_edit_limit_seconds', 0) self.set_up_db('allow_community_topic_editing', False) realm = self.update_with_api('allow_message_editing', True) realm = self.update_with_api('message_content_edit_limit_seconds', 100) realm = self.update_with_api('allow_community_topic_editing', True) self.assertEqual(realm.allow_message_editing, True) self.assertEqual(realm.message_content_edit_limit_seconds, 100) self.assertEqual(realm.allow_community_topic_editing, True) realm = self.update_with_api('allow_message_editing', False) self.assertEqual(realm.allow_message_editing, False) self.assertEqual(realm.message_content_edit_limit_seconds, 100) self.assertEqual(realm.allow_community_topic_editing, True) realm = self.update_with_api('message_content_edit_limit_seconds', 200) self.assertEqual(realm.allow_message_editing, False) self.assertEqual(realm.message_content_edit_limit_seconds, 200) self.assertEqual(realm.allow_community_topic_editing, True) realm = self.update_with_api('allow_community_topic_editing', False) self.assertEqual(realm.allow_message_editing, False) self.assertEqual(realm.message_content_edit_limit_seconds, 200) self.assertEqual(realm.allow_community_topic_editing, False) def test_update_realm_allow_message_deleting(self) -> None: """Tests updating the realm property 'allow_message_deleting'.""" self.set_up_db('allow_message_deleting', True) self.set_up_db('message_content_delete_limit_seconds', 0) realm = self.update_with_api('allow_message_deleting', False) self.assertEqual(realm.allow_message_deleting, False) self.assertEqual(realm.message_content_delete_limit_seconds, 0) realm = self.update_with_api('allow_message_deleting', True) realm = self.update_with_api('message_content_delete_limit_seconds', 100) self.assertEqual(realm.allow_message_deleting, True) self.assertEqual(realm.message_content_delete_limit_seconds, 100) realm = self.update_with_api('message_content_delete_limit_seconds', 600) self.assertEqual(realm.allow_message_deleting, True) self.assertEqual(realm.message_content_delete_limit_seconds, 600) class ScrubRealmTest(ZulipTestCase): def test_scrub_realm(self) -> None: zulip = get_realm("zulip") lear = get_realm("lear") iago = self.example_user("iago") othello = self.example_user("othello") cordelia = self.lear_user("cordelia") king = self.lear_user("king") create_stream_if_needed(lear, "Shakespeare") self.subscribe(cordelia, "Shakespeare") self.subscribe(king, "Shakespeare") Message.objects.all().delete() UserMessage.objects.all().delete() for i in range(5): self.send_stream_message(iago.email, "Scotland") self.send_stream_message(othello.email, "Scotland") self.send_stream_message(cordelia.email, "Shakespeare", sender_realm="lear") self.send_stream_message(king.email, "Shakespeare", sender_realm="lear") Attachment.objects.filter(realm=zulip).delete() Attachment.objects.create(realm=zulip, owner=iago, path_id="a/b/temp1.txt") Attachment.objects.create(realm=zulip, owner=othello, path_id="a/b/temp2.txt") Attachment.objects.filter(realm=lear).delete() Attachment.objects.create(realm=lear, owner=cordelia, path_id="c/d/temp1.txt") Attachment.objects.create(realm=lear, owner=king, path_id="c/d/temp2.txt") CustomProfileField.objects.create(realm=lear) self.assertEqual(Message.objects.filter(sender__in=[iago, othello]).count(), 10) self.assertEqual(Message.objects.filter(sender__in=[cordelia, king]).count(), 10) self.assertEqual(UserMessage.objects.filter(user_profile__in=[iago, othello]).count(), 20) self.assertEqual(UserMessage.objects.filter(user_profile__in=[cordelia, king]).count(), 20) self.assertNotEqual(CustomProfileField.objects.filter(realm=zulip).count(), 0) with mock.patch('logging.warning'): do_scrub_realm(zulip) self.assertEqual(Message.objects.filter(sender__in=[iago, othello]).count(), 0) self.assertEqual(Message.objects.filter(sender__in=[cordelia, king]).count(), 10) self.assertEqual(UserMessage.objects.filter(user_profile__in=[iago, othello]).count(), 0) self.assertEqual(UserMessage.objects.filter(user_profile__in=[cordelia, king]).count(), 20) self.assertEqual(Attachment.objects.filter(realm=zulip).count(), 0) self.assertEqual(Attachment.objects.filter(realm=lear).count(), 2) self.assertEqual(CustomProfileField.objects.filter(realm=zulip).count(), 0) self.assertNotEqual(CustomProfileField.objects.filter(realm=lear).count(), 0) zulip_users = UserProfile.objects.filter(realm=zulip) for user in zulip_users: self.assertTrue(re.search("Scrubbed [a-z0-9]{15}", user.full_name)) self.assertTrue(re.search("scrubbed-[a-z0-9]{15}@" + zulip.host, user.email)) self.assertTrue(re.search("scrubbed-[a-z0-9]{15}@" + zulip.host, user.delivery_email)) lear_users = UserProfile.objects.filter(realm=lear) for user in lear_users: self.assertIsNone(re.search("Scrubbed [a-z0-9]{15}", user.full_name)) self.assertIsNone(re.search("scrubbed-[a-z0-9]{15}@" + zulip.host, user.email)) self.assertIsNone(re.search("scrubbed-[a-z0-9]{15}@" + zulip.host, user.delivery_email))
[ "UserProfile", "str", "str", "Any", "str", "int", "str" ]
[ 972, 1049, 17249, 17261, 17424, 17436, 17666 ]
[ 983, 1052, 17252, 17264, 17427, 17439, 17669 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_realm_domains.py
# -*- coding: utf-8 -*- from django.core.exceptions import ValidationError from django.db.utils import IntegrityError from typing import Optional from zerver.lib.actions import do_change_is_admin, \ do_change_realm_domain, do_create_realm, \ do_remove_realm_domain from zerver.lib.domains import validate_domain from zerver.lib.test_classes import ZulipTestCase from zerver.models import email_allowed_for_realm, get_realm, \ RealmDomain, DomainNotAllowedForRealmError import ujson class RealmDomainTest(ZulipTestCase): def test_list_realm_domains(self) -> None: self.login(self.example_email("iago")) realm = get_realm('zulip') RealmDomain.objects.create(realm=realm, domain='acme.com', allow_subdomains=True) result = self.client_get("/json/realm/domains") self.assert_json_success(result) received = ujson.dumps(result.json()['domains'], sort_keys=True) expected = ujson.dumps([{'domain': 'zulip.com', 'allow_subdomains': False}, {'domain': 'acme.com', 'allow_subdomains': True}], sort_keys=True) self.assertEqual(received, expected) def test_not_realm_admin(self) -> None: self.login(self.example_email("hamlet")) result = self.client_post("/json/realm/domains") self.assert_json_error(result, 'Must be an organization administrator') result = self.client_patch("/json/realm/domains/15") self.assert_json_error(result, 'Must be an organization administrator') result = self.client_delete("/json/realm/domains/15") self.assert_json_error(result, 'Must be an organization administrator') def test_create_realm_domain(self) -> None: self.login(self.example_email("iago")) data = {'domain': ujson.dumps(''), 'allow_subdomains': ujson.dumps(True)} result = self.client_post("/json/realm/domains", info=data) self.assert_json_error(result, 'Invalid domain: Domain can\'t be empty.') data['domain'] = ujson.dumps('acme.com') result = self.client_post("/json/realm/domains", info=data) self.assert_json_success(result) realm = get_realm('zulip') self.assertTrue(RealmDomain.objects.filter(realm=realm, domain='acme.com', allow_subdomains=True).exists()) result = self.client_post("/json/realm/domains", info=data) self.assert_json_error(result, 'The domain acme.com is already a part of your organization.') mit_user_profile = self.mit_user("sipbtest") self.login(mit_user_profile.email, realm=get_realm("zephyr")) do_change_is_admin(mit_user_profile, True) result = self.client_post("/json/realm/domains", info=data, HTTP_HOST=mit_user_profile.realm.host) self.assert_json_success(result) def test_patch_realm_domain(self) -> None: self.login(self.example_email("iago")) realm = get_realm('zulip') RealmDomain.objects.create(realm=realm, domain='acme.com', allow_subdomains=False) data = { 'allow_subdomains': ujson.dumps(True), } url = "/json/realm/domains/acme.com" result = self.client_patch(url, data) self.assert_json_success(result) self.assertTrue(RealmDomain.objects.filter(realm=realm, domain='acme.com', allow_subdomains=True).exists()) url = "/json/realm/domains/non-existent.com" result = self.client_patch(url, data) self.assertEqual(result.status_code, 400) self.assert_json_error(result, 'No entry found for domain non-existent.com.') def test_delete_realm_domain(self) -> None: self.login(self.example_email("iago")) realm = get_realm('zulip') RealmDomain.objects.create(realm=realm, domain='acme.com') result = self.client_delete("/json/realm/domains/non-existent.com") self.assertEqual(result.status_code, 400) self.assert_json_error(result, 'No entry found for domain non-existent.com.') result = self.client_delete("/json/realm/domains/acme.com") self.assert_json_success(result) self.assertFalse(RealmDomain.objects.filter(domain='acme.com').exists()) self.assertTrue(realm.emails_restricted_to_domains) def test_delete_all_realm_domains(self) -> None: self.login(self.example_email("iago")) realm = get_realm('zulip') query = RealmDomain.objects.filter(realm=realm) self.assertTrue(realm.emails_restricted_to_domains) for realm_domain in query.all(): do_remove_realm_domain(realm_domain) self.assertEqual(query.count(), 0) # Deleting last realm_domain should set `emails_restricted_to_domains` to False. # This should be tested on a fresh instance, since the cached objects # would not be updated. self.assertFalse(get_realm('zulip').emails_restricted_to_domains) def test_email_allowed_for_realm(self) -> None: realm1 = do_create_realm('testrealm1', 'Test Realm 1', emails_restricted_to_domains=True) realm2 = do_create_realm('testrealm2', 'Test Realm 2', emails_restricted_to_domains=True) realm_domain = RealmDomain.objects.create(realm=realm1, domain='test1.com', allow_subdomains=False) RealmDomain.objects.create(realm=realm2, domain='test2.test1.com', allow_subdomains=True) email_allowed_for_realm('user@test1.com', realm1) with self.assertRaises(DomainNotAllowedForRealmError): email_allowed_for_realm('user@test2.test1.com', realm1) email_allowed_for_realm('user@test2.test1.com', realm2) email_allowed_for_realm('user@test3.test2.test1.com', realm2) with self.assertRaises(DomainNotAllowedForRealmError): email_allowed_for_realm('user@test3.test1.com', realm2) do_change_realm_domain(realm_domain, True) email_allowed_for_realm('user@test1.com', realm1) email_allowed_for_realm('user@test2.test1.com', realm1) with self.assertRaises(DomainNotAllowedForRealmError): email_allowed_for_realm('user@test2.com', realm1) def test_realm_realm_domains_uniqueness(self) -> None: realm = get_realm('zulip') with self.assertRaises(IntegrityError): RealmDomain.objects.create(realm=realm, domain='zulip.com', allow_subdomains=True) def test_validate_domain(self) -> None: invalid_domains = ['', 'test', 't.', 'test.', '.com', '-test', 'test...com', 'test-', 'test_domain.com', 'test.-domain.com', 'a' * 255 + ".com"] for domain in invalid_domains: with self.assertRaises(ValidationError): validate_domain(domain) valid_domains = ['acme.com', 'x-x.y.3.z'] for domain in valid_domains: validate_domain(domain)
[]
[]
[]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_realm_emoji.py
# -*- coding: utf-8 -*- import mock from zerver.lib.actions import do_create_realm, do_create_user, \ do_remove_realm_emoji, get_realm, check_add_realm_emoji from zerver.lib.test_classes import ZulipTestCase from zerver.lib.test_helpers import get_test_image_file, get_user from zerver.models import Realm, RealmEmoji, UserProfile class RealmEmojiTest(ZulipTestCase): def create_test_emoji(self, name: str, author: UserProfile) -> RealmEmoji: with get_test_image_file('img.png') as img_file: realm_emoji = check_add_realm_emoji(realm=author.realm, name=name, author=author, image_file=img_file) if realm_emoji is None: raise Exception("Error creating test emoji.") # nocoverage return realm_emoji def create_test_emoji_with_no_author(self, name: str, realm: Realm) -> RealmEmoji: realm_emoji = RealmEmoji.objects.create(realm=realm, name=name) return realm_emoji def test_list(self) -> None: emoji_author = self.example_user('iago') self.login(emoji_author.email) self.create_test_emoji('my_emoji', emoji_author) result = self.client_get("/json/realm/emoji") self.assert_json_success(result) self.assertEqual(200, result.status_code) self.assertEqual(len(result.json()["emoji"]), 2) def test_list_no_author(self) -> None: email = self.example_email('iago') self.login(email) realm = get_realm('zulip') realm_emoji = self.create_test_emoji_with_no_author('my_emoji', realm) result = self.client_get("/json/realm/emoji") self.assert_json_success(result) content = result.json() self.assertEqual(len(content["emoji"]), 2) test_emoji = content["emoji"][str(realm_emoji.id)] self.assertIsNone(test_emoji['author']) def test_list_admins_only(self) -> None: # Test that realm emoji list is public and realm emojis # having no author are also there in the list. email = self.example_email('othello') self.login(email) realm = get_realm('zulip') realm.add_emoji_by_admins_only = True realm.save() realm_emoji = self.create_test_emoji_with_no_author('my_emoji', realm) result = self.client_get("/json/realm/emoji") self.assert_json_success(result) content = result.json() self.assertEqual(len(content["emoji"]), 2) test_emoji = content["emoji"][str(realm_emoji.id)] self.assertIsNone(test_emoji['author']) def test_upload(self) -> None: email = self.example_email('iago') self.login(email) with get_test_image_file('img.png') as fp1: emoji_data = {'f1': fp1} result = self.client_post('/json/realm/emoji/my_emoji', info=emoji_data) self.assert_json_success(result) self.assertEqual(200, result.status_code) realm_emoji = RealmEmoji.objects.get(name="my_emoji") self.assertEqual(realm_emoji.author.email, email) result = self.client_get("/json/realm/emoji") content = result.json() self.assert_json_success(result) self.assertEqual(len(content["emoji"]), 2) test_emoji = content["emoji"][str(realm_emoji.id)] self.assertIn('author', test_emoji) self.assertEqual(test_emoji['author']['email'], email) def test_realm_emoji_repr(self) -> None: realm_emoji = RealmEmoji.objects.get(name='green_tick') file_name = str(realm_emoji.id) + '.png' self.assertEqual( str(realm_emoji), '<RealmEmoji(zulip): %s green_tick False %s>' % (realm_emoji.id, file_name) ) def test_upload_exception(self) -> None: email = self.example_email('iago') self.login(email) with get_test_image_file('img.png') as fp1: emoji_data = {'f1': fp1} result = self.client_post('/json/realm/emoji/my_em*oji', info=emoji_data) self.assert_json_error(result, 'Invalid characters in emoji name') def test_upload_uppercase_exception(self) -> None: email = self.example_email('iago') self.login(email) with get_test_image_file('img.png') as fp1: emoji_data = {'f1': fp1} result = self.client_post('/json/realm/emoji/my_EMoji', info=emoji_data) self.assert_json_error(result, 'Invalid characters in emoji name') def test_upload_admins_only(self) -> None: email = self.example_email('othello') self.login(email) realm = get_realm('zulip') realm.add_emoji_by_admins_only = True realm.save() with get_test_image_file('img.png') as fp1: emoji_data = {'f1': fp1} result = self.client_post('/json/realm/emoji/my_emoji', info=emoji_data) self.assert_json_error(result, 'Must be an organization administrator') def test_upload_anyone(self) -> None: email = self.example_email('othello') self.login(email) realm = get_realm('zulip') realm.add_emoji_by_admins_only = False realm.save() with get_test_image_file('img.png') as fp1: emoji_data = {'f1': fp1} result = self.client_post('/json/realm/emoji/my_emoji', info=emoji_data) self.assert_json_success(result) def test_emoji_upload_by_guest_user(self) -> None: email = self.example_email('polonius') self.login(email) with get_test_image_file('img.png') as fp1: emoji_data = {'f1': fp1} result = self.client_post('/json/realm/emoji/my_emoji', info=emoji_data) self.assert_json_error(result, 'Not allowed for guest users') def test_delete(self) -> None: emoji_author = self.example_user('iago') self.login(emoji_author.email) realm_emoji = self.create_test_emoji('my_emoji', emoji_author) result = self.client_delete('/json/realm/emoji/my_emoji') self.assert_json_success(result) result = self.client_get("/json/realm/emoji") emojis = result.json()["emoji"] self.assert_json_success(result) # We only mark an emoji as deactivated instead of # removing it from the database. self.assertEqual(len(emojis), 2) test_emoji = emojis[str(realm_emoji.id)] self.assertEqual(test_emoji["deactivated"], True) def test_delete_no_author(self) -> None: email = self.example_email('iago') self.login(email) realm = get_realm('zulip') self.create_test_emoji_with_no_author('my_emoji', realm) result = self.client_delete('/json/realm/emoji/my_emoji') self.assert_json_success(result) def test_delete_admins_only(self) -> None: emoji_author = self.example_user('othello') self.login(emoji_author.email) realm = get_realm('zulip') realm.add_emoji_by_admins_only = True realm.save() self.create_test_emoji_with_no_author("my_emoji", realm) result = self.client_delete("/json/realm/emoji/my_emoji") self.assert_json_error(result, 'Must be an organization administrator') def test_delete_admin_or_author(self) -> None: # If any user in a realm can upload the emoji then the user who # uploaded it as well as the admin should be able to delete it. emoji_author = self.example_user('othello') realm = get_realm('zulip') realm.add_emoji_by_admins_only = False realm.save() self.create_test_emoji('my_emoji_1', emoji_author) self.login(emoji_author.email) result = self.client_delete("/json/realm/emoji/my_emoji_1") self.assert_json_success(result) self.logout() self.create_test_emoji('my_emoji_2', emoji_author) self.login(self.example_email('iago')) result = self.client_delete("/json/realm/emoji/my_emoji_2") self.assert_json_success(result) self.logout() self.create_test_emoji('my_emoji_3', emoji_author) self.login(self.example_email('cordelia')) result = self.client_delete("/json/realm/emoji/my_emoji_3") self.assert_json_error(result, 'Must be an organization administrator or emoji author') def test_delete_exception(self) -> None: email = self.example_email('iago') self.login(email) result = self.client_delete("/json/realm/emoji/invalid_emoji") self.assert_json_error(result, "Emoji 'invalid_emoji' does not exist") def test_multiple_upload(self) -> None: email = self.example_email('iago') self.login(email) with get_test_image_file('img.png') as fp1, get_test_image_file('img.png') as fp2: result = self.client_post('/json/realm/emoji/my_emoji', {'f1': fp1, 'f2': fp2}) self.assert_json_error(result, 'You must upload exactly one file.') def test_emoji_upload_file_size_error(self) -> None: email = self.example_email('iago') self.login(email) with get_test_image_file('img.png') as fp: with self.settings(MAX_EMOJI_FILE_SIZE=0): result = self.client_post('/json/realm/emoji/my_emoji', {'file': fp}) self.assert_json_error(result, 'Uploaded file is larger than the allowed limit of 0 MB') def test_upload_already_existed_emoji(self) -> None: email = self.example_email('iago') self.login(email) with get_test_image_file('img.png') as fp1: emoji_data = {'f1': fp1} result = self.client_post('/json/realm/emoji/green_tick', info=emoji_data) self.assert_json_error(result, 'A custom emoji with this name already exists.') def test_reupload(self) -> None: # An user should be able to reupload an emoji with same name. email = self.example_email('iago') self.login(email) with get_test_image_file('img.png') as fp1: emoji_data = {'f1': fp1} result = self.client_post('/json/realm/emoji/my_emoji', info=emoji_data) self.assert_json_success(result) result = self.client_delete("/json/realm/emoji/my_emoji") self.assert_json_success(result) with get_test_image_file('img.png') as fp1: emoji_data = {'f1': fp1} result = self.client_post('/json/realm/emoji/my_emoji', info=emoji_data) self.assert_json_success(result) result = self.client_get("/json/realm/emoji") emojis = result.json()["emoji"] self.assert_json_success(result) self.assertEqual(len(emojis), 3) def test_failed_file_upload(self) -> None: email = self.example_email('iago') self.login(email) with mock.patch('zerver.lib.upload.write_local_file', side_effect=Exception()): with get_test_image_file('img.png') as fp1: emoji_data = {'f1': fp1} result = self.client_post('/json/realm/emoji/my_emoji', info=emoji_data) self.assert_json_error(result, "Image file upload failed.") def test_check_admin_realm_emoji(self) -> None: # Test that an user A is able to remove a realm emoji uploaded by him # and having same name as a deactivated realm emoji uploaded by some # other user B. emoji_author_1 = self.example_user('cordelia') self.create_test_emoji('test_emoji', emoji_author_1) self.login(emoji_author_1.email) result = self.client_delete('/json/realm/emoji/test_emoji') self.assert_json_success(result) emoji_author_2 = self.example_user('othello') self.create_test_emoji('test_emoji', emoji_author_2) self.login(emoji_author_2.email) result = self.client_delete('/json/realm/emoji/test_emoji') self.assert_json_success(result) def test_check_admin_different_realm_emoji(self) -> None: # Test that two different realm emojis in two different realms but # having same name can be administered independently. realm_1 = do_create_realm('test_realm', 'test_realm') emoji_author_1 = do_create_user('abc@example.com', password='abc', realm=realm_1, full_name='abc', short_name='abc') self.create_test_emoji('test_emoji', emoji_author_1) emoji_author_2 = self.example_user('othello') self.create_test_emoji('test_emoji', emoji_author_2) self.login(emoji_author_2.email) result = self.client_delete('/json/realm/emoji/test_emoji') self.assert_json_success(result)
[ "str", "UserProfile", "str", "Realm" ]
[ 414, 427, 965, 977 ]
[ 417, 438, 968, 982 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_realm_filters.py
# -*- coding: utf-8 -*- from zerver.lib.actions import get_realm, do_add_realm_filter from zerver.lib.test_classes import ZulipTestCase from zerver.models import RealmFilter class RealmFilterTest(ZulipTestCase): def test_list(self) -> None: email = self.example_email('iago') self.login(email) realm = get_realm('zulip') do_add_realm_filter( realm, "#(?P<id>[123])", "https://realm.com/my_realm_filter/%(id)s") result = self.client_get("/json/realm/filters") self.assert_json_success(result) self.assertEqual(200, result.status_code) self.assertEqual(len(result.json()["filters"]), 1) def test_create(self) -> None: email = self.example_email('iago') self.login(email) data = {"pattern": "", "url_format_string": "https://realm.com/my_realm_filter/%(id)s"} result = self.client_post("/json/realm/filters", info=data) self.assert_json_error(result, 'This field cannot be blank.') data['pattern'] = '$a' result = self.client_post("/json/realm/filters", info=data) self.assert_json_error(result, 'Invalid filter pattern, you must use the following format OPTIONAL_PREFIX(?P<id>.+)') data['pattern'] = r'ZUL-(?P<id>\d++)' result = self.client_post("/json/realm/filters", info=data) self.assert_json_error(result, 'Invalid filter pattern, you must use the following format OPTIONAL_PREFIX(?P<id>.+)') data['pattern'] = r'ZUL-(?P<id>\d+)' data['url_format_string'] = '$fgfg' result = self.client_post("/json/realm/filters", info=data) self.assert_json_error(result, 'Enter a valid URL.') data['pattern'] = r'ZUL-(?P<id>\d+)' data['url_format_string'] = 'https://realm.com/my_realm_filter/' result = self.client_post("/json/realm/filters", info=data) self.assert_json_error(result, 'URL format string must be in the following format: `https://example.com/%(\\w+)s`') data['url_format_string'] = 'https://realm.com/my_realm_filter/#hashtag/%(id)s' result = self.client_post("/json/realm/filters", info=data) self.assert_json_success(result) data['pattern'] = r'ZUL2-(?P<id>\d+)' data['url_format_string'] = 'https://realm.com/my_realm_filter/?value=%(id)s' result = self.client_post("/json/realm/filters", info=data) self.assert_json_success(result) # This is something we'd like to support, but don't currently; # this test is a reminder of something we should allow in the # future. data['pattern'] = r'(?P<org>[a-z]+)/(?P<repo>[a-z]+)#(?P<id>[0-9]+)' data['url_format_string'] = 'https://github.com/%(org)/%(repo)/issue/%(id)' result = self.client_post("/json/realm/filters", info=data) self.assert_json_error(result, 'URL format string must be in the following format: `https://example.com/%(\\w+)s`') def test_not_realm_admin(self) -> None: email = self.example_email('hamlet') self.login(email) result = self.client_post("/json/realm/filters") self.assert_json_error(result, 'Must be an organization administrator') result = self.client_delete("/json/realm/filters/15") self.assert_json_error(result, 'Must be an organization administrator') def test_delete(self) -> None: email = self.example_email('iago') self.login(email) realm = get_realm('zulip') filter_id = do_add_realm_filter( realm, "#(?P<id>[123])", "https://realm.com/my_realm_filter/%(id)s") filters_count = RealmFilter.objects.count() result = self.client_delete("/json/realm/filters/{0}".format(filter_id + 1)) self.assert_json_error(result, 'Filter not found') result = self.client_delete("/json/realm/filters/{0}".format(filter_id)) self.assert_json_success(result) self.assertEqual(RealmFilter.objects.count(), filters_count - 1)
[]
[]
[]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_report.py
# -*- coding: utf-8 -*- from typing import Any, Callable, Dict, Iterable, List, Tuple from django.test import override_settings from zerver.lib.test_classes import ( ZulipTestCase, ) from zerver.lib.utils import statsd import mock import ujson import os def fix_params(raw_params: Dict[str, Any]) -> Dict[str, str]: # A few of our few legacy endpoints need their # individual parameters serialized as JSON. return {k: ujson.dumps(v) for k, v in raw_params.items()} class StatsMock: def __init__(self, settings: Callable[..., Any]) -> None: self.settings = settings self.real_impl = statsd self.func_calls = [] # type: List[Tuple[str, Iterable[Any]]] def __getattr__(self, name: str) -> Callable[..., Any]: def f(*args: Any) -> None: with self.settings(STATSD_HOST=''): getattr(self.real_impl, name)(*args) self.func_calls.append((name, args)) return f class TestReport(ZulipTestCase): def test_send_time(self) -> None: email = self.example_email('hamlet') self.login(email) params = dict( time=5, received=6, displayed=7, locally_echoed='true', rendered_content_disparity='true', ) stats_mock = StatsMock(self.settings) with mock.patch('zerver.views.report.statsd', wraps=stats_mock): result = self.client_post("/json/report/send_times", params) self.assert_json_success(result) expected_calls = [ ('timing', ('endtoend.send_time.zulip', 5)), ('timing', ('endtoend.receive_time.zulip', 6)), ('timing', ('endtoend.displayed_time.zulip', 7)), ('incr', ('locally_echoed',)), ('incr', ('render_disparity',)), ] self.assertEqual(stats_mock.func_calls, expected_calls) def test_narrow_time(self) -> None: email = self.example_email('hamlet') self.login(email) params = dict( initial_core=5, initial_free=6, network=7, ) stats_mock = StatsMock(self.settings) with mock.patch('zerver.views.report.statsd', wraps=stats_mock): result = self.client_post("/json/report/narrow_times", params) self.assert_json_success(result) expected_calls = [ ('timing', ('narrow.initial_core.zulip', 5)), ('timing', ('narrow.initial_free.zulip', 6)), ('timing', ('narrow.network.zulip', 7)), ] self.assertEqual(stats_mock.func_calls, expected_calls) def test_unnarrow_time(self) -> None: email = self.example_email('hamlet') self.login(email) params = dict( initial_core=5, initial_free=6, ) stats_mock = StatsMock(self.settings) with mock.patch('zerver.views.report.statsd', wraps=stats_mock): result = self.client_post("/json/report/unnarrow_times", params) self.assert_json_success(result) expected_calls = [ ('timing', ('unnarrow.initial_core.zulip', 5)), ('timing', ('unnarrow.initial_free.zulip', 6)), ] self.assertEqual(stats_mock.func_calls, expected_calls) @override_settings(BROWSER_ERROR_REPORTING=True) def test_report_error(self) -> None: email = self.example_email('hamlet') self.login(email) params = fix_params(dict( message='hello', stacktrace='trace', ui_message=True, user_agent='agent', href='href', log='log', more_info=dict(foo='bar', draft_content="**draft**"), )) publish_mock = mock.patch('zerver.views.report.queue_json_publish') subprocess_mock = mock.patch( 'zerver.views.report.subprocess.check_output', side_effect=KeyError('foo') ) with publish_mock as m, subprocess_mock: result = self.client_post("/json/report/error", params) self.assert_json_success(result) report = m.call_args[0][1]['report'] for k in set(params) - set(['ui_message', 'more_info']): self.assertEqual(report[k], params[k]) self.assertEqual(report['more_info'], dict(foo='bar', draft_content="'**xxxxx**'")) self.assertEqual(report['user_email'], email) # Teset with no more_info del params['more_info'] with publish_mock as m, subprocess_mock: result = self.client_post("/json/report/error", params) self.assert_json_success(result) with self.settings(BROWSER_ERROR_REPORTING=False): result = self.client_post("/json/report/error", params) self.assert_json_success(result) # If js_source_map is present, then the stack trace should be annotated. # DEVELOPMENT=False and TEST_SUITE=False are necessary to ensure that # js_source_map actually gets instantiated. with \ self.settings(DEVELOPMENT=False, TEST_SUITE=False), \ mock.patch('zerver.lib.unminify.SourceMap.annotate_stacktrace') as annotate: result = self.client_post("/json/report/error", params) self.assert_json_success(result) # fix_params (see above) adds quotes when JSON encoding. annotate.assert_called_once_with('"trace"') def test_report_csp_violations(self) -> None: fixture_data = self.fixture_data('csp_report.json') result = self.client_post("/report/csp_violations", fixture_data, content_type="application/json") self.assert_json_success(result)
[ "Dict[str, Any]", "Callable[..., Any]", "str", "Any" ]
[ 289, 536, 733, 782 ]
[ 303, 554, 736, 785 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_retention.py
# -*- coding: utf-8 -*- import types from datetime import datetime, timedelta from django.utils.timezone import now as timezone_now from zerver.lib.test_classes import ZulipTestCase from zerver.lib.upload import create_attachment from zerver.models import Message, Realm, Recipient, UserProfile, UserMessage, ArchivedUserMessage, \ ArchivedMessage, Attachment, ArchivedAttachment from zerver.lib.retention import get_expired_messages, move_messages_to_archive from typing import Any, List, Tuple class TestRetentionLib(ZulipTestCase): """ Test receiving expired messages retention tool. """ def setUp(self) -> None: super().setUp() self.zulip_realm = self._set_realm_message_retention_value('zulip', 30) self.mit_realm = self._set_realm_message_retention_value('zephyr', 100) Message.objects.all().update(pub_date=timezone_now()) @staticmethod def _set_realm_message_retention_value(realm_str: str, retention_period: int) -> Realm: realm = Realm.objects.get(string_id=realm_str) realm.message_retention_days = retention_period realm.save() return realm @staticmethod def _change_messages_pub_date(msgs_ids: List[int], pub_date: datetime) -> Any: messages = Message.objects.filter(id__in=msgs_ids).order_by('id') messages.update(pub_date=pub_date) return messages def _make_mit_messages(self, message_quantity: int, pub_date: datetime) -> Any: # send messages from mit.edu realm and change messages pub date sender = self.mit_user('espuser') recipient = self.mit_user('starnine') msgs_ids = [self.send_personal_message(sender.email, recipient.email, sender_realm='zephyr') for i in range(message_quantity)] mit_messages = self._change_messages_pub_date(msgs_ids, pub_date) return mit_messages def test_expired_messages_result_type(self) -> None: # Check return type of get_expired_message method. result = get_expired_messages() self.assertIsInstance(result, types.GeneratorType) def test_no_expired_messages(self) -> None: result = list(get_expired_messages()) self.assertFalse(result) def test_expired_messages_in_each_realm(self) -> None: # Check result realm messages order and result content # when all realm has expired messages. expired_mit_messages = self._make_mit_messages(3, timezone_now() - timedelta(days=101)) self._make_mit_messages(4, timezone_now() - timedelta(days=50)) zulip_messages_ids = Message.objects.order_by('id').filter( sender__realm=self.zulip_realm).values_list('id', flat=True)[3:10] expired_zulip_messages = self._change_messages_pub_date(zulip_messages_ids, timezone_now() - timedelta(days=31)) # Iterate by result expired_messages_result = [messages_list for messages_list in get_expired_messages()] self.assertEqual(len(expired_messages_result), 2) # Check mit.edu realm expired messages. self.assertEqual(len(expired_messages_result[0]['expired_messages']), 3) self.assertEqual(expired_messages_result[0]['realm_id'], self.mit_realm.id) # Check zulip.com realm expired messages. self.assertEqual(len(expired_messages_result[1]['expired_messages']), 7) self.assertEqual(expired_messages_result[1]['realm_id'], self.zulip_realm.id) # Compare expected messages ids with result messages ids. self.assertEqual( sorted([message.id for message in expired_mit_messages]), [message.id for message in expired_messages_result[0]['expired_messages']] ) self.assertEqual( sorted([message.id for message in expired_zulip_messages]), [message.id for message in expired_messages_result[1]['expired_messages']] ) def test_expired_messages_in_one_realm(self) -> None: # Check realm with expired messages and messages # with one day to expiration data. expired_mit_messages = self._make_mit_messages(5, timezone_now() - timedelta(days=101)) actual_mit_messages = self._make_mit_messages(3, timezone_now() - timedelta(days=99)) expired_messages_result = list(get_expired_messages()) expired_mit_messages_ids = [message.id for message in expired_mit_messages] expired_mit_messages_result_ids = [message.id for message in expired_messages_result[0]['expired_messages']] actual_mit_messages_ids = [message.id for message in actual_mit_messages] self.assertEqual(len(expired_messages_result), 1) self.assertEqual(len(expired_messages_result[0]['expired_messages']), 5) self.assertEqual(expired_messages_result[0]['realm_id'], self.mit_realm.id) # Compare expected messages ids with result messages ids. self.assertEqual( sorted(expired_mit_messages_ids), expired_mit_messages_result_ids ) # Check actual mit.edu messages are not contained in expired messages list self.assertEqual( set(actual_mit_messages_ids) - set(expired_mit_messages_ids), set(actual_mit_messages_ids) ) class TestMoveMessageToArchive(ZulipTestCase): def setUp(self) -> None: super().setUp() self.sender = 'hamlet@zulip.com' self.recipient = 'cordelia@zulip.com' def _create_attachments(self) -> None: sample_size = 10 dummy_files = [ ('zulip.txt', '1/31/4CBjtTLYZhk66pZrF8hnYGwc/zulip.txt', sample_size), ('temp_file.py', '1/31/4CBjtTLYZhk66pZrF8hnYGwc/temp_file.py', sample_size), ('abc.py', '1/31/4CBjtTLYZhk66pZrF8hnYGwc/abc.py', sample_size), ('hello.txt', '1/31/4CBjtTLYZhk66pZrF8hnYGwc/hello.txt', sample_size), ('new.py', '1/31/4CBjtTLYZhk66pZrF8hnYGwc/new.py', sample_size) ] user_profile = self.example_user('hamlet') for file_name, path_id, size in dummy_files: create_attachment(file_name, path_id, user_profile, size) def _check_messages_before_archiving(self, msg_ids: List[int]) -> Tuple[List[int], List[int]]: user_msgs_ids_before = list(UserMessage.objects.filter( message_id__in=msg_ids).order_by('id').values_list('id', flat=True)) all_msgs_ids_before = list(Message.objects.filter().order_by('id').values_list('id', flat=True)) self.assertEqual(ArchivedUserMessage.objects.count(), 0) self.assertEqual(ArchivedMessage.objects.count(), 0) return (user_msgs_ids_before, all_msgs_ids_before) def _check_messages_after_archiving(self, msg_ids: List[int], user_msgs_ids_before: List[int], all_msgs_ids_before: List[int]) -> None: self.assertEqual(ArchivedMessage.objects.all().count(), len(msg_ids)) self.assertEqual(Message.objects.filter().count(), len(all_msgs_ids_before) - len(msg_ids)) self.assertEqual(UserMessage.objects.filter(message_id__in=msg_ids).count(), 0) arc_user_messages_ids_after = list(ArchivedUserMessage.objects.filter().order_by('id').values_list('id', flat=True)) self.assertEqual(arc_user_messages_ids_after, user_msgs_ids_before) def test_personal_messages_archiving(self) -> None: msg_ids = [] for i in range(0, 3): msg_ids.append(self.send_personal_message(self.sender, self.recipient)) (user_msgs_ids_before, all_msgs_ids_before) = self._check_messages_before_archiving(msg_ids) move_messages_to_archive(message_ids=msg_ids) self._check_messages_after_archiving(msg_ids, user_msgs_ids_before, all_msgs_ids_before) def test_stream_messages_archiving(self) -> None: msg_ids = [] for i in range(0, 3): msg_ids.append(self.send_stream_message(self.sender, "Verona")) (user_msgs_ids_before, all_msgs_ids_before) = self._check_messages_before_archiving(msg_ids) move_messages_to_archive(message_ids=msg_ids) self._check_messages_after_archiving(msg_ids, user_msgs_ids_before, all_msgs_ids_before) def test_archiving_messages_second_time(self) -> None: msg_ids = [] for i in range(0, 3): msg_ids.append(self.send_stream_message(self.sender, "Verona")) (user_msgs_ids_before, all_msgs_ids_before) = self._check_messages_before_archiving(msg_ids) move_messages_to_archive(message_ids=msg_ids) self._check_messages_after_archiving(msg_ids, user_msgs_ids_before, all_msgs_ids_before) with self.assertRaises(Message.DoesNotExist): move_messages_to_archive(message_ids=msg_ids) def test_archiving_messages_with_attachment(self) -> None: self._create_attachments() body1 = """Some files here ...[zulip.txt]( http://localhost:9991/user_uploads/1/31/4CBjtTLYZhk66pZrF8hnYGwc/zulip.txt) http://localhost:9991/user_uploads/1/31/4CBjtTLYZhk66pZrF8hnYGwc/temp_file.py .... Some more.... http://localhost:9991/user_uploads/1/31/4CBjtTLYZhk66pZrF8hnYGwc/abc.py """ body2 = """Some files here http://localhost:9991/user_uploads/1/31/4CBjtTLYZhk66pZrF8hnYGwc/zulip.txt ... http://localhost:9991/user_uploads/1/31/4CBjtTLYZhk66pZrF8hnYGwc/hello.txt .... http://localhost:9991/user_uploads/1/31/4CBjtTLYZhk66pZrF8hnYGwc/new.py .... """ msg_ids = [] msg_ids.append(self.send_personal_message(self.sender, self.recipient, body1)) msg_ids.append(self.send_personal_message(self.sender, self.recipient, body2)) attachment_id_to_message_ids = {} attachments = Attachment.objects.filter(messages__id__in=msg_ids) for attachment in attachments: attachment_id_to_message_ids[attachment.id] = {message.id for message in attachment.messages.all()} (user_msgs_ids_before, all_msgs_ids_before) = self._check_messages_before_archiving(msg_ids) attachments_ids_before = list(attachments.order_by("id").values_list("id", flat=True)) self.assertEqual(ArchivedAttachment.objects.count(), 0) move_messages_to_archive(message_ids=msg_ids) self._check_messages_after_archiving(msg_ids, user_msgs_ids_before, all_msgs_ids_before) self.assertEqual(Attachment.objects.count(), 0) archived_attachments = ArchivedAttachment.objects.filter(messages__id__in=msg_ids) arc_attachments_ids_after = list(archived_attachments.order_by("id").values_list("id", flat=True)) self.assertEqual(attachments_ids_before, arc_attachments_ids_after) for attachment in archived_attachments: self.assertEqual(attachment_id_to_message_ids[attachment.id], {message.id for message in attachment.messages.all()}) def test_archiving_message_with_shared_attachment(self) -> None: # Check do not removing attachments which is used in other messages. self._create_attachments() body = """Some files here ...[zulip.txt]( http://localhost:9991/user_uploads/1/31/4CBjtTLYZhk66pZrF8hnYGwc/zulip.txt) http://localhost:9991/user_uploads/1/31/4CBjtTLYZhk66pZrF8hnYGwc/temp_file.py .... Some more.... http://localhost:9991/user_uploads/1/31/4CBjtTLYZhk66pZrF8hnYGwc/abc.py ... http://localhost:9991/user_uploads/1/31/4CBjtTLYZhk66pZrF8hnYGwc/new.py .... http://localhost:9991/user_uploads/1/31/4CBjtTLYZhk66pZrF8hnYGwc/hello.txt .... """ msg_id = self.send_personal_message(self.sender, self.recipient, body) # Simulate a reply with the same contents. msg_id_shared_attachments = self.send_personal_message( from_email=self.recipient, to_email=self.sender, content=body, ) (user_msgs_ids_before, all_msgs_ids_before) = self._check_messages_before_archiving([msg_id]) attachments_ids_before = list(Attachment.objects.filter( messages__id=msg_id).order_by("id").values_list("id", flat=True)) self.assertEqual(ArchivedAttachment.objects.count(), 0) move_messages_to_archive(message_ids=[msg_id]) self._check_messages_after_archiving([msg_id], user_msgs_ids_before, all_msgs_ids_before) self.assertEqual(Attachment.objects.count(), 5) arc_attachments_ids_after = list(ArchivedAttachment.objects.filter( messages__id=msg_id).order_by("id").values_list("id", flat=True)) self.assertEqual(attachments_ids_before, arc_attachments_ids_after) move_messages_to_archive(message_ids=[msg_id_shared_attachments]) self.assertEqual(Attachment.objects.count(), 0)
[ "str", "int", "List[int]", "datetime", "int", "datetime", "List[int]", "List[int]", "List[int]", "List[int]" ]
[ 964, 987, 1218, 1239, 1450, 1465, 6344, 6880, 6913, 6985 ]
[ 967, 990, 1227, 1247, 1453, 1473, 6353, 6889, 6922, 6994 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_service_bot_system.py
# -*- coding: utf-8 -*- import json import mock from typing import Any, Union, Mapping, Callable from django.conf import settings from django.test import override_settings from zerver.lib.actions import ( do_create_user, get_service_bot_events, ) from zerver.lib.bot_lib import StateHandler, EmbeddedBotHandler from zerver.lib.bot_storage import StateError from zerver.lib.bot_config import set_bot_config, ConfigError, load_bot_config_template from zerver.lib.test_classes import ZulipTestCase from zerver.models import ( get_realm, BotStorageData, UserProfile, Recipient, ) import ujson BOT_TYPE_TO_QUEUE_NAME = { UserProfile.OUTGOING_WEBHOOK_BOT: 'outgoing_webhooks', UserProfile.EMBEDDED_BOT: 'embedded_bots', } class TestServiceBotBasics(ZulipTestCase): def _get_outgoing_bot(self) -> UserProfile: outgoing_bot = do_create_user( email="bar-bot@zulip.com", password="test", realm=get_realm("zulip"), full_name="BarBot", short_name='bb', bot_type=UserProfile.OUTGOING_WEBHOOK_BOT, bot_owner=self.example_user('cordelia'), ) return outgoing_bot def test_service_events_for_pms(self) -> None: sender = self.example_user('hamlet') assert(not sender.is_bot) outgoing_bot = self._get_outgoing_bot() event_dict = get_service_bot_events( sender=sender, service_bot_tuples=[ (outgoing_bot.id, outgoing_bot.bot_type), ], active_user_ids={outgoing_bot.id}, mentioned_user_ids=set(), recipient_type=Recipient.PERSONAL, ) expected = dict( outgoing_webhooks=[ dict(trigger='private_message', user_profile_id=outgoing_bot.id), ], ) self.assertEqual(event_dict, expected) def test_spurious_mentions(self) -> None: sender = self.example_user('hamlet') assert(not sender.is_bot) outgoing_bot = self._get_outgoing_bot() # If outgoing_bot is not in mentioned_user_ids, # we will skip over it. This tests an anomaly # of the code that our query for bots can include # bots that may not actually be mentioned, and it's # easiest to just filter them in get_service_bot_events. event_dict = get_service_bot_events( sender=sender, service_bot_tuples=[ (outgoing_bot.id, outgoing_bot.bot_type), ], active_user_ids={outgoing_bot.id}, mentioned_user_ids=set(), recipient_type=Recipient.STREAM, ) self.assertEqual(len(event_dict), 0) def test_service_events_for_stream_mentions(self) -> None: sender = self.example_user('hamlet') assert(not sender.is_bot) outgoing_bot = self._get_outgoing_bot() cordelia = self.example_user('cordelia') red_herring_bot = self.create_test_bot( short_name='whatever', user_profile=cordelia, ) event_dict = get_service_bot_events( sender=sender, service_bot_tuples=[ (outgoing_bot.id, outgoing_bot.bot_type), (red_herring_bot.id, UserProfile.OUTGOING_WEBHOOK_BOT), ], active_user_ids=set(), mentioned_user_ids={outgoing_bot.id}, recipient_type=Recipient.STREAM, ) expected = dict( outgoing_webhooks=[ dict(trigger='mention', user_profile_id=outgoing_bot.id), ], ) self.assertEqual(event_dict, expected) def test_service_events_for_private_mentions(self) -> None: """Service bots should not get access to mentions if they aren't a direct recipient.""" sender = self.example_user('hamlet') assert(not sender.is_bot) outgoing_bot = self._get_outgoing_bot() event_dict = get_service_bot_events( sender=sender, service_bot_tuples=[ (outgoing_bot.id, outgoing_bot.bot_type), ], active_user_ids=set(), mentioned_user_ids={outgoing_bot.id}, recipient_type=Recipient.PERSONAL, ) self.assertEqual(len(event_dict), 0) def test_service_events_with_unexpected_bot_type(self) -> None: hamlet = self.example_user('hamlet') cordelia = self.example_user('cordelia') bot = self.create_test_bot( short_name='whatever', user_profile=cordelia, ) wrong_bot_type = UserProfile.INCOMING_WEBHOOK_BOT bot.bot_type = wrong_bot_type bot.save() with mock.patch('logging.error') as log_mock: event_dict = get_service_bot_events( sender=hamlet, service_bot_tuples=[ (bot.id, wrong_bot_type), ], active_user_ids=set(), mentioned_user_ids={bot.id}, recipient_type=Recipient.PERSONAL, ) self.assertEqual(len(event_dict), 0) arg = log_mock.call_args_list[0][0][0] self.assertIn('Unexpected bot_type', arg) class TestServiceBotStateHandler(ZulipTestCase): def setUp(self) -> None: self.user_profile = self.example_user("othello") self.bot_profile = do_create_user(email="embedded-bot-1@zulip.com", password="test", realm=get_realm("zulip"), full_name="EmbeddedBo1", short_name="embedded-bot-1", bot_type=UserProfile.EMBEDDED_BOT, bot_owner=self.user_profile) self.second_bot_profile = do_create_user(email="embedded-bot-2@zulip.com", password="test", realm=get_realm("zulip"), full_name="EmbeddedBot2", short_name="embedded-bot-2", bot_type=UserProfile.EMBEDDED_BOT, bot_owner=self.user_profile) def test_basic_storage_and_retrieval(self) -> None: storage = StateHandler(self.bot_profile) storage.put('some key', 'some value') storage.put('some other key', 'some other value') self.assertEqual(storage.get('some key'), 'some value') self.assertEqual(storage.get('some other key'), 'some other value') self.assertTrue(storage.contains('some key')) self.assertFalse(storage.contains('nonexistent key')) self.assertRaisesMessage(StateError, "Key does not exist.", lambda: storage.get('nonexistent key')) storage.put('some key', 'a new value') self.assertEqual(storage.get('some key'), 'a new value') second_storage = StateHandler(self.second_bot_profile) self.assertRaises(StateError, lambda: second_storage.get('some key')) second_storage.put('some key', 'yet another value') self.assertEqual(storage.get('some key'), 'a new value') self.assertEqual(second_storage.get('some key'), 'yet another value') def test_marshaling(self) -> None: storage = StateHandler(self.bot_profile) serializable_obj = {'foo': 'bar', 'baz': [42, 'cux']} storage.put('some key', serializable_obj) # type: ignore # Ignore for testing. self.assertEqual(storage.get('some key'), serializable_obj) def test_invalid_calls(self) -> None: storage = StateHandler(self.bot_profile) storage.marshal = lambda obj: obj storage.demarshal = lambda obj: obj serializable_obj = {'foo': 'bar', 'baz': [42, 'cux']} with self.assertRaisesMessage(StateError, "Value type is <class 'dict'>, but should be str."): storage.put('some key', serializable_obj) # type: ignore # We intend to test an invalid type. with self.assertRaisesMessage(StateError, "Key type is <class 'dict'>, but should be str."): storage.put(serializable_obj, 'some value') # type: ignore # We intend to test an invalid type. # Reduce maximal storage size for faster test string construction. @override_settings(USER_STATE_SIZE_LIMIT=100) def test_storage_limit(self) -> None: storage = StateHandler(self.bot_profile) # Disable marshaling for storing a string whose size is # equivalent to the size of the stored object. storage.marshal = lambda obj: obj storage.demarshal = lambda obj: obj key = 'capacity-filling entry' storage.put(key, 'x' * (settings.USER_STATE_SIZE_LIMIT - len(key))) with self.assertRaisesMessage(StateError, "Request exceeds storage limit by 32 characters. " "The limit is 100 characters."): storage.put('too much data', 'a few bits too long') second_storage = StateHandler(self.second_bot_profile) second_storage.put('another big entry', 'x' * (settings.USER_STATE_SIZE_LIMIT - 40)) second_storage.put('normal entry', 'abcd') def test_entry_removal(self) -> None: storage = StateHandler(self.bot_profile) storage.put('some key', 'some value') storage.put('another key', 'some value') self.assertTrue(storage.contains('some key')) self.assertTrue(storage.contains('another key')) storage.remove('some key') self.assertFalse(storage.contains('some key')) self.assertTrue(storage.contains('another key')) self.assertRaises(StateError, lambda: storage.remove('some key')) def test_internal_endpoint(self): # type: () -> None self.login(self.user_profile.email) # Store some data. initial_dict = {'key 1': 'value 1', 'key 2': 'value 2', 'key 3': 'value 3'} params = { 'storage': ujson.dumps(initial_dict) } result = self.client_put('/json/bot_storage', params) self.assert_json_success(result) # Assert the stored data for some keys. params = { 'keys': ujson.dumps(['key 1', 'key 3']) } result = self.client_get('/json/bot_storage', params) self.assert_json_success(result) self.assertEqual(result.json()['storage'], {'key 3': 'value 3', 'key 1': 'value 1'}) # Assert the stored data for all keys. result = self.client_get('/json/bot_storage') self.assert_json_success(result) self.assertEqual(result.json()['storage'], initial_dict) # Store some more data; update an entry and store a new entry dict_update = {'key 1': 'new value', 'key 4': 'value 4'} params = { 'storage': ujson.dumps(dict_update) } result = self.client_put('/json/bot_storage', params) self.assert_json_success(result) # Assert the data was updated. updated_dict = initial_dict.copy() updated_dict.update(dict_update) result = self.client_get('/json/bot_storage') self.assert_json_success(result) self.assertEqual(result.json()['storage'], updated_dict) # Assert errors on invalid requests. params = { # type: ignore # Ignore 'incompatible type "str": "List[str]"; expected "str": "str"' for testing 'keys': ["This is a list, but should be a serialized string."] } result = self.client_get('/json/bot_storage', params) self.assert_json_error(result, 'Argument "keys" is not valid JSON.') params = { 'keys': ujson.dumps(["key 1", "nonexistent key"]) } result = self.client_get('/json/bot_storage', params) self.assert_json_error(result, "Key does not exist.") params = { 'storage': ujson.dumps({'foo': [1, 2, 3]}) } result = self.client_put('/json/bot_storage', params) self.assert_json_error(result, "Value type is <class 'list'>, but should be str.") # Remove some entries. keys_to_remove = ['key 1', 'key 2'] params = { 'keys': ujson.dumps(keys_to_remove) } result = self.client_delete('/json/bot_storage', params) self.assert_json_success(result) # Assert the entries were removed. for key in keys_to_remove: updated_dict.pop(key) result = self.client_get('/json/bot_storage') self.assert_json_success(result) self.assertEqual(result.json()['storage'], updated_dict) # Try to remove an existing and a nonexistent key. params = { 'keys': ujson.dumps(['key 3', 'nonexistent key']) } result = self.client_delete('/json/bot_storage', params) self.assert_json_error(result, "Key does not exist.") # Assert an error has been thrown and no entries were removed. result = self.client_get('/json/bot_storage') self.assert_json_success(result) self.assertEqual(result.json()['storage'], updated_dict) # Remove the entire storage. result = self.client_delete('/json/bot_storage') self.assert_json_success(result) # Assert the entire storage has been removed. result = self.client_get('/json/bot_storage') self.assert_json_success(result) self.assertEqual(result.json()['storage'], {}) class TestServiceBotConfigHandler(ZulipTestCase): def setUp(self) -> None: self.user_profile = self.example_user("othello") self.bot_profile = self.create_test_bot('embedded', self.user_profile, full_name='Embedded bot', bot_type=UserProfile.EMBEDDED_BOT, service_name='helloworld') self.bot_handler = EmbeddedBotHandler(self.bot_profile) def test_basic_storage_and_retrieval(self) -> None: with self.assertRaises(ConfigError): self.bot_handler.get_config_info('foo') self.assertEqual(self.bot_handler.get_config_info('foo', optional=True), dict()) config_dict = {"entry 1": "value 1", "entry 2": "value 2"} for key, value in config_dict.items(): set_bot_config(self.bot_profile, key, value) self.assertEqual(self.bot_handler.get_config_info('foo'), config_dict) config_update = {"entry 2": "new value", "entry 3": "value 3"} for key, value in config_update.items(): set_bot_config(self.bot_profile, key, value) config_dict.update(config_update) self.assertEqual(self.bot_handler.get_config_info('foo'), config_dict) @override_settings(BOT_CONFIG_SIZE_LIMIT=100) def test_config_entry_limit(self) -> None: set_bot_config(self.bot_profile, "some key", 'x' * (settings.BOT_CONFIG_SIZE_LIMIT-8)) self.assertRaisesMessage(ConfigError, "Cannot store configuration. Request would require 101 characters. " "The current configuration size limit is 100 characters.", lambda: set_bot_config(self.bot_profile, "some key", 'x' * (settings.BOT_CONFIG_SIZE_LIMIT-8+1))) set_bot_config(self.bot_profile, "some key", 'x' * (settings.BOT_CONFIG_SIZE_LIMIT-20)) set_bot_config(self.bot_profile, "another key", 'x') self.assertRaisesMessage(ConfigError, "Cannot store configuration. Request would require 116 characters. " "The current configuration size limit is 100 characters.", lambda: set_bot_config(self.bot_profile, "yet another key", 'x')) def test_load_bot_config_template(self) -> None: bot_config = load_bot_config_template('giphy') self.assertTrue(isinstance(bot_config, dict)) self.assertEqual(len(bot_config), 1) def test_load_bot_config_template_for_bot_without_config_data(self) -> None: bot_config = load_bot_config_template('converter') self.assertTrue(isinstance(bot_config, dict)) self.assertEqual(len(bot_config), 0) class TestServiceBotEventTriggers(ZulipTestCase): def setUp(self) -> None: self.user_profile = self.example_user("othello") self.bot_profile = do_create_user(email="foo-bot@zulip.com", password="test", realm=get_realm("zulip"), full_name="FooBot", short_name="foo-bot", bot_type=UserProfile.OUTGOING_WEBHOOK_BOT, bot_owner=self.user_profile) self.second_bot_profile = do_create_user(email="bar-bot@zulip.com", password="test", realm=get_realm("zulip"), full_name="BarBot", short_name="bar-bot", bot_type=UserProfile.OUTGOING_WEBHOOK_BOT, bot_owner=self.user_profile) @mock.patch('zerver.lib.actions.queue_json_publish') def test_trigger_on_stream_mention_from_user(self, mock_queue_json_publish: mock.Mock) -> None: for bot_type, expected_queue_name in BOT_TYPE_TO_QUEUE_NAME.items(): self.bot_profile.bot_type = bot_type self.bot_profile.save() content = u'@**FooBot** foo bar!!!' recipient = 'Denmark' trigger = 'mention' message_type = Recipient._type_names[Recipient.STREAM] def check_values_passed(queue_name: Any, trigger_event: Union[Mapping[Any, Any], Any], x: Callable[[Any], None]=None) -> None: self.assertEqual(queue_name, expected_queue_name) self.assertEqual(trigger_event["message"]["content"], content) self.assertEqual(trigger_event["message"]["display_recipient"], recipient) self.assertEqual(trigger_event["message"]["sender_email"], self.user_profile.email) self.assertEqual(trigger_event["message"]["type"], message_type) self.assertEqual(trigger_event['trigger'], trigger) self.assertEqual(trigger_event['user_profile_id'], self.bot_profile.id) mock_queue_json_publish.side_effect = check_values_passed self.send_stream_message( self.user_profile.email, 'Denmark', content) self.assertTrue(mock_queue_json_publish.called) @mock.patch('zerver.lib.actions.queue_json_publish') def test_no_trigger_on_stream_message_without_mention(self, mock_queue_json_publish: mock.Mock) -> None: sender_email = self.user_profile.email self.send_stream_message(sender_email, "Denmark") self.assertFalse(mock_queue_json_publish.called) @mock.patch('zerver.lib.actions.queue_json_publish') def test_no_trigger_on_stream_mention_from_bot(self, mock_queue_json_publish: mock.Mock) -> None: for bot_type in BOT_TYPE_TO_QUEUE_NAME: self.bot_profile.bot_type = bot_type self.bot_profile.save() self.send_stream_message( self.second_bot_profile.email, 'Denmark', u'@**FooBot** foo bar!!!') self.assertFalse(mock_queue_json_publish.called) @mock.patch('zerver.lib.actions.queue_json_publish') def test_trigger_on_personal_message_from_user(self, mock_queue_json_publish: mock.Mock) -> None: for bot_type, expected_queue_name in BOT_TYPE_TO_QUEUE_NAME.items(): self.bot_profile.bot_type = bot_type self.bot_profile.save() sender_email = self.user_profile.email recipient_email = self.bot_profile.email def check_values_passed(queue_name: Any, trigger_event: Union[Mapping[Any, Any], Any], x: Callable[[Any], None]=None) -> None: self.assertEqual(queue_name, expected_queue_name) self.assertEqual(trigger_event["user_profile_id"], self.bot_profile.id) self.assertEqual(trigger_event["trigger"], "private_message") self.assertEqual(trigger_event["message"]["sender_email"], sender_email) display_recipients = [ trigger_event["message"]["display_recipient"][0]["email"], trigger_event["message"]["display_recipient"][1]["email"], ] self.assertTrue(sender_email in display_recipients) self.assertTrue(recipient_email in display_recipients) mock_queue_json_publish.side_effect = check_values_passed self.send_personal_message(sender_email, recipient_email, 'test') self.assertTrue(mock_queue_json_publish.called) @mock.patch('zerver.lib.actions.queue_json_publish') def test_no_trigger_on_personal_message_from_bot(self, mock_queue_json_publish: mock.Mock) -> None: for bot_type in BOT_TYPE_TO_QUEUE_NAME: self.bot_profile.bot_type = bot_type self.bot_profile.save() sender_email = self.second_bot_profile.email recipient_email = self.bot_profile.email self.send_personal_message(sender_email, recipient_email) self.assertFalse(mock_queue_json_publish.called) @mock.patch('zerver.lib.actions.queue_json_publish') def test_trigger_on_huddle_message_from_user(self, mock_queue_json_publish: mock.Mock) -> None: for bot_type, expected_queue_name in BOT_TYPE_TO_QUEUE_NAME.items(): self.bot_profile.bot_type = bot_type self.bot_profile.save() self.second_bot_profile.bot_type = bot_type self.second_bot_profile.save() sender_email = self.user_profile.email recipient_emails = [self.bot_profile.email, self.second_bot_profile.email] profile_ids = [self.bot_profile.id, self.second_bot_profile.id] def check_values_passed(queue_name: Any, trigger_event: Union[Mapping[Any, Any], Any], x: Callable[[Any], None]=None) -> None: self.assertEqual(queue_name, expected_queue_name) self.assertIn(trigger_event["user_profile_id"], profile_ids) profile_ids.remove(trigger_event["user_profile_id"]) self.assertEqual(trigger_event["trigger"], "private_message") self.assertEqual(trigger_event["message"]["sender_email"], sender_email) self.assertEqual(trigger_event["message"]["type"], u'private') mock_queue_json_publish.side_effect = check_values_passed self.send_huddle_message(sender_email, recipient_emails, 'test') self.assertEqual(mock_queue_json_publish.call_count, 2) mock_queue_json_publish.reset_mock() @mock.patch('zerver.lib.actions.queue_json_publish') def test_no_trigger_on_huddle_message_from_bot(self, mock_queue_json_publish: mock.Mock) -> None: for bot_type in BOT_TYPE_TO_QUEUE_NAME: self.bot_profile.bot_type = bot_type self.bot_profile.save() sender_email = self.second_bot_profile.email recipient_emails = [self.user_profile.email, self.bot_profile.email] self.send_huddle_message(sender_email, recipient_emails) self.assertFalse(mock_queue_json_publish.called)
[ "mock.Mock", "Any", "Union[Mapping[Any, Any], Any]", "mock.Mock", "mock.Mock", "mock.Mock", "Any", "Union[Mapping[Any, Any], Any]", "mock.Mock", "mock.Mock", "Any", "Union[Mapping[Any, Any], Any]", "mock.Mock" ]
[ 17897, 18310, 18366, 19455, 19777, 20287, 20623, 20679, 21812, 22345, 22891, 22947, 23917 ]
[ 17906, 18313, 18395, 19464, 19786, 20296, 20626, 20708, 21821, 22354, 22894, 22976, 23926 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_sessions.py
from typing import Any, Callable from zerver.lib.sessions import ( user_sessions, delete_session, delete_user_sessions, delete_realm_user_sessions, delete_all_user_sessions, delete_all_deactivated_user_sessions, ) from zerver.models import ( UserProfile, get_user_profile_by_id, get_realm, Realm ) from zerver.lib.test_classes import ZulipTestCase class TestSessions(ZulipTestCase): def do_test_session(self, user: str, action: Callable[[], Any], realm: Realm, expected_result: bool) -> None: self.login(user, realm=realm) self.assertIn('_auth_user_id', self.client.session) action() if expected_result: result = self.client_get('/', subdomain=realm.subdomain) self.assertEqual('/login', result.url) else: self.assertIn('_auth_user_id', self.client.session) def test_delete_session(self) -> None: user_profile = self.example_user('hamlet') email = user_profile.email self.login(email) self.assertIn('_auth_user_id', self.client.session) for session in user_sessions(user_profile): delete_session(session) result = self.client_get("/") self.assertEqual('/login', result.url) def test_delete_user_sessions(self) -> None: user_profile = self.example_user('hamlet') email = user_profile.email self.do_test_session(str(email), lambda: delete_user_sessions(user_profile), get_realm("zulip"), True) self.do_test_session(str(self.example_email("othello")), lambda: delete_user_sessions(user_profile), get_realm("zulip"), False) def test_delete_realm_user_sessions(self) -> None: realm = get_realm('zulip') self.do_test_session(self.example_email("hamlet"), lambda: delete_realm_user_sessions(realm), get_realm("zulip"), True) self.do_test_session(self.mit_email("sipbtest"), lambda: delete_realm_user_sessions(realm), get_realm("zephyr"), False) def test_delete_all_user_sessions(self) -> None: self.do_test_session(self.example_email("hamlet"), lambda: delete_all_user_sessions(), get_realm("zulip"), True) self.do_test_session(self.mit_email("sipbtest"), lambda: delete_all_user_sessions(), get_realm("zephyr"), True) def test_delete_all_deactivated_user_sessions(self) -> None: # Test that no exception is thrown with a logged-out session self.login(self.example_email("othello")) self.assertIn('_auth_user_id', self.client.session) self.client_post('/accounts/logout/') delete_all_deactivated_user_sessions() result = self.client_get("/") self.assertEqual('/login', result.url) # Test nothing happens to an active user's session self.login(self.example_email("othello")) self.assertIn('_auth_user_id', self.client.session) delete_all_deactivated_user_sessions() self.assertIn('_auth_user_id', self.client.session) # Test that a deactivated session gets logged out user_profile_3 = self.example_user('cordelia') email_3 = user_profile_3.email self.login(email_3) self.assertIn('_auth_user_id', self.client.session) user_profile_3.is_active = False user_profile_3.save() delete_all_deactivated_user_sessions() result = self.client_get("/") self.assertEqual('/login', result.url)
[ "str", "Callable[[], Any]", "Realm", "bool" ]
[ 453, 490, 540, 588 ]
[ 456, 507, 545, 592 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_settings.py
import ujson from django.http import HttpResponse from django.test import override_settings from mock import patch from typing import Any, Dict from zerver.lib.initial_password import initial_password from zerver.lib.sessions import get_session_dict_user from zerver.lib.test_classes import ZulipTestCase from zerver.lib.test_helpers import MockLDAP from zerver.lib.users import get_all_api_keys from zerver.models import get_realm, get_user, UserProfile class ChangeSettingsTest(ZulipTestCase): def check_well_formed_change_settings_response(self, result: Dict[str, Any]) -> None: self.assertIn("full_name", result) # DEPRECATED, to be deleted after all uses of check_for_toggle_param # are converted into check_for_toggle_param_patch. def check_for_toggle_param(self, pattern: str, param: str) -> None: self.login(self.example_email("hamlet")) user_profile = self.example_user('hamlet') json_result = self.client_post(pattern, {param: ujson.dumps(True)}) self.assert_json_success(json_result) # refetch user_profile object to correctly handle caching user_profile = self.example_user('hamlet') self.assertEqual(getattr(user_profile, param), True) json_result = self.client_post(pattern, {param: ujson.dumps(False)}) self.assert_json_success(json_result) # refetch user_profile object to correctly handle caching user_profile = self.example_user('hamlet') self.assertEqual(getattr(user_profile, param), False) # TODO: requires method consolidation, right now, there's no alternative # for check_for_toggle_param for PATCH. def check_for_toggle_param_patch(self, pattern: str, param: str) -> None: self.login(self.example_email("hamlet")) user_profile = self.example_user('hamlet') json_result = self.client_patch(pattern, {param: ujson.dumps(True)}) self.assert_json_success(json_result) # refetch user_profile object to correctly handle caching user_profile = self.example_user('hamlet') self.assertEqual(getattr(user_profile, param), True) json_result = self.client_patch(pattern, {param: ujson.dumps(False)}) self.assert_json_success(json_result) # refetch user_profile object to correctly handle caching user_profile = self.example_user('hamlet') self.assertEqual(getattr(user_profile, param), False) def test_successful_change_settings(self) -> None: """ A call to /json/settings with valid parameters changes the user's settings correctly and returns correct values. """ self.login(self.example_email("hamlet")) json_result = self.client_patch( "/json/settings", dict( full_name='Foo Bar', old_password=initial_password(self.example_email("hamlet")), new_password='foobar1', )) self.assert_json_success(json_result) result = ujson.loads(json_result.content) self.check_well_formed_change_settings_response(result) self.assertEqual(self.example_user('hamlet'). full_name, "Foo Bar") self.logout() self.login(self.example_email("hamlet"), "foobar1") user_profile = self.example_user('hamlet') self.assertEqual(get_session_dict_user(self.client.session), user_profile.id) def test_illegal_name_changes(self) -> None: user = self.example_user('hamlet') email = user.email self.login(email) full_name = user.full_name with self.settings(NAME_CHANGES_DISABLED=True): json_result = self.client_patch("/json/settings", dict(full_name='Foo Bar')) # We actually fail silently here, since this only happens if # somebody is trying to game our API, and there's no reason to # give them the courtesy of an error reason. self.assert_json_success(json_result) user = self.example_user('hamlet') self.assertEqual(user.full_name, full_name) # Now try a too-long name json_result = self.client_patch("/json/settings", dict(full_name='x' * 1000)) self.assert_json_error(json_result, 'Name too long!') # Now try a too-short name json_result = self.client_patch("/json/settings", dict(full_name='x')) self.assert_json_error(json_result, 'Name too short!') def test_illegal_characters_in_name_changes(self) -> None: email = self.example_email("hamlet") self.login(email) # Now try a name with invalid characters json_result = self.client_patch("/json/settings", dict(full_name='Opheli*')) self.assert_json_error(json_result, 'Invalid characters in name!') def test_change_email_to_disposable_email(self) -> None: email = self.example_email("hamlet") self.login(email) realm = get_realm("zulip") realm.disallow_disposable_email_addresses = True realm.emails_restricted_to_domains = False realm.save() json_result = self.client_patch("/json/settings", dict(email='hamlet@mailnator.com')) self.assert_json_error(json_result, 'Please use your real email address.') # This is basically a don't-explode test. def test_notify_settings(self) -> None: for notification_setting in UserProfile.notification_setting_types: self.check_for_toggle_param_patch("/json/settings/notifications", notification_setting) def test_toggling_boolean_user_display_settings(self) -> None: """Test updating each boolean setting in UserProfile property_types""" boolean_settings = (s for s in UserProfile.property_types if UserProfile.property_types[s] is bool) for display_setting in boolean_settings: self.check_for_toggle_param_patch("/json/settings/display", display_setting) def test_enter_sends_setting(self) -> None: self.check_for_toggle_param('/json/users/me/enter-sends', "enter_sends") def test_wrong_old_password(self) -> None: self.login(self.example_email("hamlet")) result = self.client_patch( "/json/settings", dict( old_password='bad_password', new_password="ignored", )) self.assert_json_error(result, "Wrong password!") @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend', 'zproject.backends.EmailAuthBackend', 'zproject.backends.ZulipDummyBackend'), AUTH_LDAP_BIND_PASSWORD='', AUTH_LDAP_USER_DN_TEMPLATE='uid=%(user)s,ou=users,dc=zulip,dc=com') def test_change_password_ldap_backend(self) -> None: ldap_user_attr_map = {'full_name': 'fn', 'short_name': 'sn'} ldap_patcher = patch('django_auth_ldap.config.ldap.initialize') mock_initialize = ldap_patcher.start() mock_ldap = MockLDAP() mock_initialize.return_value = mock_ldap mock_ldap.directory = { 'uid=hamlet,ou=users,dc=zulip,dc=com': { 'userPassword': 'ldappassword', 'fn': ['New LDAP fullname'] } } self.login(self.example_email("hamlet")) with self.settings(LDAP_APPEND_DOMAIN="zulip.com", AUTH_LDAP_USER_ATTR_MAP=ldap_user_attr_map): result = self.client_patch( "/json/settings", dict( old_password=initial_password(self.example_email("hamlet")), new_password="ignored", )) self.assert_json_error(result, "Your Zulip password is managed in LDAP") result = self.client_patch( "/json/settings", dict( old_password='ldappassword', new_password="ignored", )) self.assert_json_error(result, "Your Zulip password is managed in LDAP") with self.settings(LDAP_APPEND_DOMAIN="example.com", AUTH_LDAP_USER_ATTR_MAP=ldap_user_attr_map): result = self.client_patch( "/json/settings", dict( old_password=initial_password(self.example_email("hamlet")), new_password="ignored", )) self.assert_json_success(result) with self.settings(LDAP_APPEND_DOMAIN=None, AUTH_LDAP_USER_ATTR_MAP=ldap_user_attr_map): result = self.client_patch( "/json/settings", dict( old_password=initial_password(self.example_email("hamlet")), new_password="ignored", )) self.assert_json_error(result, "Your Zulip password is managed in LDAP") def test_changing_nothing_returns_error(self) -> None: """ We need to supply at least one non-empty parameter to this API, or it should fail. (Eventually, we should probably use a patch interface for these changes.) """ self.login(self.example_email("hamlet")) result = self.client_patch("/json/settings", dict(old_password='ignored',)) self.assert_json_error(result, "Please fill out all fields.") def do_test_change_user_display_setting(self, setting_name: str) -> None: test_changes = dict( default_language = 'de', emojiset = 'google', timezone = 'US/Mountain', ) # type: Dict[str, Any] email = self.example_email('hamlet') self.login(email) test_value = test_changes.get(setting_name) # Error if a setting in UserProfile.property_types does not have test values if test_value is None: raise AssertionError('No test created for %s' % (setting_name)) invalid_value = 'invalid_' + setting_name data = {setting_name: ujson.dumps(test_value)} result = self.client_patch("/json/settings/display", data) self.assert_json_success(result) user_profile = self.example_user('hamlet') self.assertEqual(getattr(user_profile, setting_name), test_value) # Test to make sure invalid settings are not accepted # and saved in the db. data = {setting_name: ujson.dumps(invalid_value)} result = self.client_patch("/json/settings/display", data) # the json error for multiple word setting names (ex: default_language) # displays as 'Invalid language'. Using setting_name.split('_') to format. self.assert_json_error(result, "Invalid %s '%s'" % (setting_name.split('_')[-1], invalid_value)) user_profile = self.example_user('hamlet') self.assertNotEqual(getattr(user_profile, setting_name), invalid_value) def test_change_user_display_setting(self) -> None: """Test updating each non-boolean setting in UserProfile property_types""" user_settings = (s for s in UserProfile.property_types if UserProfile.property_types[s] is not bool) for setting in user_settings: self.do_test_change_user_display_setting(setting) def do_change_emojiset(self, emojiset: str) -> HttpResponse: email = self.example_email('hamlet') self.login(email) data = {'emojiset': ujson.dumps(emojiset)} result = self.client_patch("/json/settings/display", data) return result def test_emojiset(self) -> None: """Test banned emojisets are not accepted.""" banned_emojisets = ['apple', 'emojione'] valid_emojisets = ['google', 'google-blob', 'text', 'twitter'] for emojiset in banned_emojisets: result = self.do_change_emojiset(emojiset) self.assert_json_error(result, "Invalid emojiset '%s'" % (emojiset)) for emojiset in valid_emojisets: result = self.do_change_emojiset(emojiset) self.assert_json_success(result) class UserChangesTest(ZulipTestCase): def test_update_api_key(self) -> None: user = self.example_user('hamlet') email = user.email self.login(email) old_api_keys = get_all_api_keys(user) result = self.client_post('/json/users/me/api_key/regenerate') self.assert_json_success(result) new_api_key = result.json()['api_key'] self.assertNotIn(new_api_key, old_api_keys) user = self.example_user('hamlet') current_api_keys = get_all_api_keys(user) self.assertIn(new_api_key, current_api_keys)
[ "Dict[str, Any]", "str", "str", "str", "str", "str", "str" ]
[ 566, 809, 821, 1790, 1802, 9992, 11904 ]
[ 580, 812, 824, 1793, 1805, 9995, 11907 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_signup.py
# -*- coding: utf-8 -*- import datetime from email.utils import parseaddr import re import django_otp from django.conf import settings from django.contrib.contenttypes.models import ContentType from django.contrib.sites.models import Site from django.http import HttpResponse, HttpRequest from django.test import TestCase, override_settings from django.utils.timezone import now as timezone_now from django.core.exceptions import ValidationError from two_factor.utils import default_device from mock import patch, MagicMock from zerver.lib.test_helpers import MockLDAP, get_test_image_file, avatar_disk_path from confirmation.models import Confirmation, create_confirmation_link, MultiuseInvite, \ generate_key, confirmation_url, get_object_from_key, ConfirmationKeyException, \ one_click_unsubscribe_link from confirmation import settings as confirmation_settings from zerver.forms import HomepageForm, WRONG_SUBDOMAIN_ERROR, check_subdomain_available from zerver.lib.actions import do_change_password from zerver.decorator import do_two_factor_login from zerver.views.auth import login_or_register_remote_user, \ redirect_and_log_into_subdomain, start_two_factor_auth from zerver.views.invite import get_invitee_emails_set from zerver.views.registration import confirmation_key, \ send_confirm_registration_email from zerver.models import ( get_realm, get_user, get_stream_recipient, PreregistrationUser, Realm, RealmDomain, Recipient, Message, ScheduledEmail, UserProfile, UserMessage, Stream, Subscription, flush_per_request_caches ) from zerver.lib.actions import ( set_default_streams, do_change_is_admin, get_stream, do_create_realm, do_create_default_stream_group, do_add_default_stream, ) from zerver.lib.send_email import send_email, send_future_email, FromAddress from zerver.lib.initial_password import initial_password from zerver.lib.actions import ( do_deactivate_realm, do_deactivate_user, do_set_realm_property, add_new_user_history, ) from zerver.lib.avatar import avatar_url from zerver.lib.mobile_auth_otp import xor_hex_strings, ascii_to_hex, \ otp_encrypt_api_key, is_valid_otp, hex_to_ascii, otp_decrypt_api_key from zerver.lib.notifications import enqueue_welcome_emails, \ followup_day2_email_delay from zerver.lib.subdomains import is_root_domain_available from zerver.lib.test_helpers import find_key_by_email, queries_captured, \ HostRequestMock, load_subdomain_token from zerver.lib.test_classes import ( ZulipTestCase, ) from zerver.lib.test_runner import slow from zerver.lib.sessions import get_session_dict_user from zerver.lib.name_restrictions import is_disposable_domain from zerver.context_processors import common_context from collections import defaultdict import re import smtplib import ujson from typing import Any, Dict, List, Optional, Set import urllib import os import pytz class RedirectAndLogIntoSubdomainTestCase(ZulipTestCase): def test_cookie_data(self) -> None: realm = Realm.objects.all().first() name = 'Hamlet' email = self.example_email("hamlet") response = redirect_and_log_into_subdomain(realm, name, email) data = load_subdomain_token(response) self.assertDictEqual(data, {'name': name, 'next': '', 'email': email, 'subdomain': realm.subdomain, 'is_signup': False}) response = redirect_and_log_into_subdomain(realm, name, email, is_signup=True) data = load_subdomain_token(response) self.assertDictEqual(data, {'name': name, 'next': '', 'email': email, 'subdomain': realm.subdomain, 'is_signup': True}) class DeactivationNoticeTestCase(ZulipTestCase): def test_redirection_for_deactivated_realm(self) -> None: realm = get_realm("zulip") realm.deactivated = True realm.save(update_fields=["deactivated"]) for url in ('/register/', '/login/'): result = self.client_get(url) self.assertEqual(result.status_code, 302) self.assertIn('deactivated', result.url) def test_redirection_for_active_realm(self) -> None: for url in ('/register/', '/login/'): result = self.client_get(url) self.assertEqual(result.status_code, 200) def test_deactivation_notice_when_realm_is_active(self) -> None: result = self.client_get('/accounts/deactivated/') self.assertEqual(result.status_code, 302) self.assertIn('login', result.url) def test_deactivation_notice_when_deactivated(self) -> None: realm = get_realm("zulip") realm.deactivated = True realm.save(update_fields=["deactivated"]) result = self.client_get('/accounts/deactivated/') self.assertIn("Zulip Dev, has been deactivated.", result.content.decode()) class AddNewUserHistoryTest(ZulipTestCase): def test_add_new_user_history_race(self) -> None: """Sends a message during user creation""" # Create a user who hasn't had historical messages added stream_dict = { "Denmark": {"description": "A Scandinavian country", "invite_only": False}, "Verona": {"description": "A city in Italy", "invite_only": False} } # type: Dict[str, Dict[str, Any]] realm = get_realm('zulip') set_default_streams(realm, stream_dict) with patch("zerver.lib.actions.add_new_user_history"): self.register(self.nonreg_email('test'), "test") user_profile = self.nonreg_user('test') subs = Subscription.objects.select_related("recipient").filter( user_profile=user_profile, recipient__type=Recipient.STREAM) streams = Stream.objects.filter(id__in=[sub.recipient.type_id for sub in subs]) self.send_stream_message(self.example_email('hamlet'), streams[0].name, "test") add_new_user_history(user_profile, streams) class InitialPasswordTest(ZulipTestCase): def test_none_initial_password_salt(self) -> None: with self.settings(INITIAL_PASSWORD_SALT=None): self.assertIsNone(initial_password('test@test.com')) class PasswordResetTest(ZulipTestCase): """ Log in, reset password, log out, log in with new password. """ def test_password_reset(self) -> None: email = self.example_email("hamlet") old_password = initial_password(email) self.login(email) # test password reset template result = self.client_get('/accounts/password/reset/') self.assert_in_response('Reset your password', result) # start the password reset process by supplying an email address result = self.client_post('/accounts/password/reset/', {'email': email}) # check the redirect link telling you to check mail for password reset link self.assertEqual(result.status_code, 302) self.assertTrue(result["Location"].endswith( "/accounts/password/reset/done/")) result = self.client_get(result["Location"]) self.assert_in_response("Check your email in a few minutes to finish the process.", result) # Check that the password reset email is from a noreply address. from django.core.mail import outbox from_email = outbox[0].from_email self.assertIn("Zulip Account Security", from_email) tokenized_no_reply_email = parseaddr(from_email)[1] self.assertTrue(re.search(self.TOKENIZED_NOREPLY_REGEX, tokenized_no_reply_email)) self.assertIn("Psst. Word on the street is that you", outbox[0].body) # Visit the password reset link. password_reset_url = self.get_confirmation_url_from_outbox( email, url_pattern=settings.EXTERNAL_HOST + r"(\S+)") result = self.client_get(password_reset_url) self.assertEqual(result.status_code, 200) # Reset your password result = self.client_post(password_reset_url, {'new_password1': 'new_password', 'new_password2': 'new_password'}) # password reset succeeded self.assertEqual(result.status_code, 302) self.assertTrue(result["Location"].endswith("/password/done/")) # log back in with new password self.login(email, password='new_password') user_profile = self.example_user('hamlet') self.assertEqual(get_session_dict_user(self.client.session), user_profile.id) # make sure old password no longer works self.login(email, password=old_password, fails=True) def test_password_reset_for_non_existent_user(self) -> None: email = 'nonexisting@mars.com' # start the password reset process by supplying an email address result = self.client_post('/accounts/password/reset/', {'email': email}) # check the redirect link telling you to check mail for password reset link self.assertEqual(result.status_code, 302) self.assertTrue(result["Location"].endswith( "/accounts/password/reset/done/")) result = self.client_get(result["Location"]) self.assert_in_response("Check your email in a few minutes to finish the process.", result) # Check that the password reset email is from a noreply address. from django.core.mail import outbox from_email = outbox[0].from_email self.assertIn("Zulip Account Security", from_email) tokenized_no_reply_email = parseaddr(from_email)[1] self.assertTrue(re.search(self.TOKENIZED_NOREPLY_REGEX, tokenized_no_reply_email)) self.assertIn('Someone (possibly you) requested a password', outbox[0].body) self.assertNotIn('does have an active account in the zulip.testserver', outbox[0].body) def test_password_reset_for_deactivated_user(self) -> None: user_profile = self.example_user("hamlet") email = user_profile.email do_deactivate_user(user_profile) # start the password reset process by supplying an email address result = self.client_post('/accounts/password/reset/', {'email': email}) # check the redirect link telling you to check mail for password reset link self.assertEqual(result.status_code, 302) self.assertTrue(result["Location"].endswith( "/accounts/password/reset/done/")) result = self.client_get(result["Location"]) self.assert_in_response("Check your email in a few minutes to finish the process.", result) # Check that the password reset email is from a noreply address. from django.core.mail import outbox from_email = outbox[0].from_email self.assertIn("Zulip Account Security", from_email) tokenized_no_reply_email = parseaddr(from_email)[1] self.assertTrue(re.search(self.TOKENIZED_NOREPLY_REGEX, tokenized_no_reply_email)) self.assertIn('Someone (possibly you) requested a password', outbox[0].body) self.assertNotIn('does have an active account in the zulip.testserver', outbox[0].body) self.assertIn('but your account has been deactivated', outbox[0].body) def test_password_reset_with_deactivated_realm(self) -> None: user_profile = self.example_user("hamlet") email = user_profile.email do_deactivate_realm(user_profile.realm) # start the password reset process by supplying an email address with patch('logging.info') as mock_logging: result = self.client_post('/accounts/password/reset/', {'email': email}) mock_logging.assert_called_once() # check the redirect link telling you to check mail for password reset link self.assertEqual(result.status_code, 302) self.assertTrue(result["Location"].endswith( "/accounts/password/reset/done/")) result = self.client_get(result["Location"]) self.assert_in_response("Check your email in a few minutes to finish the process.", result) # Check that the password reset email is from a noreply address. from django.core.mail import outbox self.assertEqual(len(outbox), 0) def test_wrong_subdomain(self) -> None: email = self.example_email("hamlet") # start the password reset process by supplying an email address result = self.client_post( '/accounts/password/reset/', {'email': email}, subdomain="zephyr") # check the redirect link telling you to check mail for password reset link self.assertEqual(result.status_code, 302) self.assertTrue(result["Location"].endswith( "/accounts/password/reset/done/")) result = self.client_get(result["Location"]) self.assert_in_response("Check your email in a few minutes to finish the process.", result) from django.core.mail import outbox self.assertEqual(len(outbox), 1) message = outbox.pop() tokenized_no_reply_email = parseaddr(message.from_email)[1] self.assertTrue(re.search(self.TOKENIZED_NOREPLY_REGEX, tokenized_no_reply_email)) self.assertIn('Someone (possibly you) requested a password reset email for', message.body) self.assertIn("but you do not have an account in that organization", message.body) self.assertIn("You do have active accounts in the following organization(s).\nhttp://zulip.testserver", message.body) def test_invalid_subdomain(self) -> None: email = self.example_email("hamlet") # start the password reset process by supplying an email address result = self.client_post( '/accounts/password/reset/', {'email': email}, subdomain="invalid") # check the redirect link telling you to check mail for password reset link self.assertEqual(result.status_code, 200) self.assert_in_success_response(["There is no Zulip organization hosted at this subdomain."], result) from django.core.mail import outbox self.assertEqual(len(outbox), 0) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend', 'zproject.backends.ZulipDummyBackend')) def test_ldap_auth_only(self) -> None: """If the email auth backend is not enabled, password reset should do nothing""" email = self.example_email("hamlet") with patch('logging.info') as mock_logging: result = self.client_post('/accounts/password/reset/', {'email': email}) mock_logging.assert_called_once() # check the redirect link telling you to check mail for password reset link self.assertEqual(result.status_code, 302) self.assertTrue(result["Location"].endswith( "/accounts/password/reset/done/")) result = self.client_get(result["Location"]) self.assert_in_response("Check your email in a few minutes to finish the process.", result) from django.core.mail import outbox self.assertEqual(len(outbox), 0) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend', 'zproject.backends.EmailAuthBackend', 'zproject.backends.ZulipDummyBackend')) def test_ldap_and_email_auth(self) -> None: """If both email and ldap auth backends are enabled, limit password reset to users outside the LDAP domain""" # If the domain matches, we don't generate an email with self.settings(LDAP_APPEND_DOMAIN="zulip.com"): email = self.example_email("hamlet") with patch('logging.info') as mock_logging: result = self.client_post('/accounts/password/reset/', {'email': email}) mock_logging.assert_called_once_with("Password reset not allowed for user in LDAP domain") from django.core.mail import outbox self.assertEqual(len(outbox), 0) # If the domain doesn't match, we do generate an email with self.settings(LDAP_APPEND_DOMAIN="example.com"): email = self.example_email("hamlet") with patch('logging.info') as mock_logging: result = self.client_post('/accounts/password/reset/', {'email': email}) self.assertEqual(result.status_code, 302) self.assertTrue(result["Location"].endswith( "/accounts/password/reset/done/")) result = self.client_get(result["Location"]) self.assertEqual(len(outbox), 1) message = outbox.pop() tokenized_no_reply_email = parseaddr(message.from_email)[1] self.assertTrue(re.search(self.TOKENIZED_NOREPLY_REGEX, tokenized_no_reply_email)) self.assertIn('Psst. Word on the street is that you need a new password', message.body) def test_redirect_endpoints(self) -> None: ''' These tests are mostly designed to give us 100% URL coverage in our URL coverage reports. Our mechanism for finding URL coverage doesn't handle redirects, so we just have a few quick tests here. ''' result = self.client_get('/accounts/password/reset/done/') self.assert_in_success_response(["Check your email"], result) result = self.client_get('/accounts/password/done/') self.assert_in_success_response(["We've reset your password!"], result) result = self.client_get('/accounts/send_confirm/alice@example.com') self.assert_in_success_response(["/accounts/home/"], result) result = self.client_get('/accounts/new/send_confirm/alice@example.com') self.assert_in_success_response(["/new/"], result) class LoginTest(ZulipTestCase): """ Logging in, registration, and logging out. """ def test_login(self) -> None: self.login(self.example_email("hamlet")) user_profile = self.example_user('hamlet') self.assertEqual(get_session_dict_user(self.client.session), user_profile.id) def test_login_deactivated_user(self) -> None: user_profile = self.example_user('hamlet') do_deactivate_user(user_profile) result = self.login_with_return(self.example_email("hamlet"), "xxx") self.assertEqual(result.status_code, 200) self.assert_in_response("Your account is no longer active.", result) self.assertIsNone(get_session_dict_user(self.client.session)) def test_login_bad_password(self) -> None: email = self.example_email("hamlet") result = self.login_with_return(email, password="wrongpassword") self.assert_in_success_response([email], result) self.assertIsNone(get_session_dict_user(self.client.session)) def test_login_nonexist_user(self) -> None: result = self.login_with_return("xxx@zulip.com", "xxx") self.assertEqual(result.status_code, 200) 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) -> None: with patch("logging.warning") as mock_warning: result = self.login_with_return(self.mit_email("sipbtest"), "xxx") mock_warning.assert_called_once() self.assertEqual(result.status_code, 200) self.assert_in_response("Your Zulip account is not a member of the " "organization associated with this subdomain.", result) self.assertIsNone(get_session_dict_user(self.client.session)) 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) self.assert_in_response("There is no Zulip organization hosted at this subdomain.", result) self.assertIsNone(get_session_dict_user(self.client.session)) def test_register(self) -> None: realm = get_realm("zulip") stream_dict = {"stream_"+str(i): {"description": "stream_%s_description" % i, "invite_only": False} for i in range(40)} # type: Dict[str, Dict[str, Any]] for stream_name in stream_dict.keys(): self.make_stream(stream_name, realm=realm) set_default_streams(realm, stream_dict) # Clear all the caches. flush_per_request_caches() ContentType.objects.clear_cache() Site.objects.clear_cache() with queries_captured() as queries: self.register(self.nonreg_email('test'), "test") # Ensure the number of queries we make is not O(streams) self.assert_length(queries, 79) user_profile = self.nonreg_user('test') self.assertEqual(get_session_dict_user(self.client.session), user_profile.id) self.assertFalse(user_profile.enable_stream_desktop_notifications) def test_register_deactivated(self) -> None: """ If you try to register for a deactivated realm, you get a clear error page. """ realm = get_realm("zulip") realm.deactivated = True realm.save(update_fields=["deactivated"]) result = self.client_post('/accounts/home/', {'email': self.nonreg_email('test')}, subdomain="zulip") self.assertEqual(result.status_code, 302) self.assertEqual('/accounts/deactivated/', result.url) with self.assertRaises(UserProfile.DoesNotExist): self.nonreg_user('test') def test_register_deactivated_partway_through(self) -> None: """ If you try to register for a deactivated realm, you get a clear error page. """ email = self.nonreg_email('test') result = self.client_post('/accounts/home/', {'email': email}, subdomain="zulip") self.assertEqual(result.status_code, 302) self.assertNotIn('deactivated', result.url) realm = get_realm("zulip") realm.deactivated = True realm.save(update_fields=["deactivated"]) result = self.submit_reg_form_for_user(email, "abcd1234", subdomain="zulip") self.assertEqual(result.status_code, 302) self.assertEqual('/accounts/deactivated/', result.url) with self.assertRaises(UserProfile.DoesNotExist): self.nonreg_user('test') def test_login_deactivated_realm(self) -> None: """ If you try to log in to a deactivated realm, you get a clear error page. """ realm = get_realm("zulip") realm.deactivated = True realm.save(update_fields=["deactivated"]) result = self.login_with_return(self.example_email("hamlet"), subdomain="zulip") self.assertEqual(result.status_code, 302) self.assertEqual('/accounts/deactivated/', result.url) def test_logout(self) -> None: self.login(self.example_email("hamlet")) # We use the logout API, not self.logout, to make sure we test # the actual logout code path. self.client_post('/accounts/logout/') self.assertIsNone(get_session_dict_user(self.client.session)) def test_non_ascii_login(self) -> None: """ You can log in even if your password contain non-ASCII characters. """ email = self.nonreg_email('test') password = u"hümbüǵ" # Registering succeeds. self.register(email, password) user_profile = self.nonreg_user('test') self.assertEqual(get_session_dict_user(self.client.session), user_profile.id) self.logout() self.assertIsNone(get_session_dict_user(self.client.session)) # Logging in succeeds. self.logout() self.login(email, password) self.assertEqual(get_session_dict_user(self.client.session), user_profile.id) @override_settings(TWO_FACTOR_AUTHENTICATION_ENABLED=False) def test_login_page_redirects_logged_in_user(self) -> None: """You will be redirected to the app's main page if you land on the login page when already logged in. """ self.login(self.example_email("cordelia")) response = self.client_get("/login/") self.assertEqual(response["Location"], "http://zulip.testserver") def test_options_request_to_login_page(self) -> None: response = self.client_options('/login/') self.assertEqual(response.status_code, 200) @override_settings(TWO_FACTOR_AUTHENTICATION_ENABLED=True) def test_login_page_redirects_logged_in_user_under_2fa(self) -> None: """You will be redirected to the app's main page if you land on the login page when already logged in. """ user_profile = self.example_user("cordelia") self.create_default_device(user_profile) self.login(self.example_email("cordelia")) self.login_2fa(user_profile) response = self.client_get("/login/") self.assertEqual(response["Location"], "http://zulip.testserver") def test_start_two_factor_auth(self) -> None: request = MagicMock(POST=dict()) with patch('zerver.views.auth.TwoFactorLoginView') as mock_view: mock_view.as_view.return_value = lambda *a, **k: HttpResponse() response = start_two_factor_auth(request) self.assertTrue(isinstance(response, HttpResponse)) def test_do_two_factor_login(self) -> None: user_profile = self.example_user('hamlet') self.create_default_device(user_profile) request = MagicMock() with patch('zerver.decorator.django_otp.login') as mock_login: do_two_factor_login(request, user_profile) mock_login.assert_called_once() class InviteUserBase(ZulipTestCase): def check_sent_emails(self, correct_recipients: List[str], custom_from_name: Optional[str]=None) -> None: from django.core.mail import outbox self.assertEqual(len(outbox), len(correct_recipients)) email_recipients = [email.recipients()[0] for email in outbox] self.assertEqual(sorted(email_recipients), sorted(correct_recipients)) if len(outbox) == 0: return if custom_from_name is not None: self.assertIn(custom_from_name, outbox[0].from_email) tokenized_no_reply_email = parseaddr(outbox[0].from_email)[1] self.assertTrue(re.search(self.TOKENIZED_NOREPLY_REGEX, tokenized_no_reply_email)) def invite(self, users: str, streams: List[str], body: str='', invite_as_admin: str="false") -> HttpResponse: """ Invites the specified users to Zulip with the specified streams. users should be a string containing the users to invite, comma or newline separated. streams should be a list of strings. """ return self.client_post("/json/invites", {"invitee_emails": users, "stream": streams, "invite_as_admin": invite_as_admin}) class InviteUserTest(InviteUserBase): def test_successful_invite_user(self) -> None: """ A call to /json/invites with valid parameters causes an invitation email to be sent. """ self.login(self.example_email("hamlet")) invitee = "alice-test@zulip.com" self.assert_json_success(self.invite(invitee, ["Denmark"])) self.assertTrue(find_key_by_email(invitee)) self.check_sent_emails([invitee], custom_from_name="Hamlet") def test_newbie_restrictions(self) -> None: user_profile = self.example_user('hamlet') invitee = "alice-test@zulip.com" stream_name = 'Denmark' self.login(user_profile.email) result = self.invite(invitee, [stream_name]) self.assert_json_success(result) user_profile.date_joined = timezone_now() - datetime.timedelta(days=10) user_profile.save() with self.settings(INVITES_MIN_USER_AGE_DAYS=5): result = self.invite(invitee, [stream_name]) self.assert_json_success(result) with self.settings(INVITES_MIN_USER_AGE_DAYS=15): result = self.invite(invitee, [stream_name]) self.assert_json_error_contains(result, "Your account is too new") def test_invite_limits(self) -> None: user_profile = self.example_user('hamlet') realm = user_profile.realm stream_name = 'Denmark' # These constants only need to be in descending order # for this test to trigger an InvitationError based # on max daily counts. site_max = 50 realm_max = 40 num_invitees = 30 max_daily_count = 20 daily_counts = [(1, max_daily_count)] invite_emails = [ 'foo-%02d@zulip.com' % (i,) for i in range(num_invitees) ] invitees = ','.join(invite_emails) self.login(user_profile.email) realm.max_invites = realm_max realm.date_created = timezone_now() realm.save() def try_invite() -> HttpResponse: with self.settings(OPEN_REALM_CREATION=True, INVITES_DEFAULT_REALM_DAILY_MAX=site_max, INVITES_NEW_REALM_LIMIT_DAYS=daily_counts): result = self.invite(invitees, [stream_name]) return result result = try_invite() self.assert_json_error_contains(result, 'enough remaining invites') # Next show that aggregate limits expire once the realm is old # enough. realm.date_created = timezone_now() - datetime.timedelta(days=8) realm.save() result = try_invite() self.assert_json_success(result) # Next get line coverage on bumping a realm's max_invites. realm.date_created = timezone_now() realm.max_invites = site_max + 10 realm.save() result = try_invite() self.assert_json_success(result) # Finally get coverage on the case that OPEN_REALM_CREATION is False. with self.settings(OPEN_REALM_CREATION=False): result = self.invite(invitees, [stream_name]) self.assert_json_success(result) def test_successful_invite_user_as_admin_from_admin_account(self) -> None: """ Test that a new user invited to a stream receives some initial history but only from public streams. """ self.login(self.example_email('iago')) invitee = self.nonreg_email('alice') self.assert_json_success(self.invite(invitee, ["Denmark"], invite_as_admin="true")) self.assertTrue(find_key_by_email(invitee)) self.submit_reg_form_for_user(invitee, "password") invitee_profile = self.nonreg_user('alice') self.assertTrue(invitee_profile.is_realm_admin) def test_invite_user_as_admin_from_normal_account(self) -> None: """ Test that a new user invited to a stream receives some initial history but only from public streams. """ self.login(self.example_email('hamlet')) invitee = self.nonreg_email('alice') response = self.invite(invitee, ["Denmark"], invite_as_admin="true") self.assert_json_error(response, "Must be an organization administrator") def test_successful_invite_user_with_name(self) -> None: """ A call to /json/invites with valid parameters causes an invitation email to be sent. """ self.login(self.example_email("hamlet")) email = "alice-test@zulip.com" invitee = "Alice Test <{}>".format(email) self.assert_json_success(self.invite(invitee, ["Denmark"])) self.assertTrue(find_key_by_email(email)) self.check_sent_emails([email], custom_from_name="Hamlet") def test_successful_invite_user_with_name_and_normal_one(self) -> None: """ A call to /json/invites with valid parameters causes an invitation email to be sent. """ self.login(self.example_email("hamlet")) email = "alice-test@zulip.com" email2 = "bob-test@zulip.com" invitee = "Alice Test <{}>, {}".format(email, email2) self.assert_json_success(self.invite(invitee, ["Denmark"])) self.assertTrue(find_key_by_email(email)) self.assertTrue(find_key_by_email(email2)) self.check_sent_emails([email, email2], custom_from_name="Hamlet") def test_require_realm_admin(self) -> None: """ The invite_by_admins_only realm setting works properly. """ realm = get_realm('zulip') realm.invite_by_admins_only = True realm.save() self.login("hamlet@zulip.com") email = "alice-test@zulip.com" email2 = "bob-test@zulip.com" invitee = "Alice Test <{}>, {}".format(email, email2) self.assert_json_error(self.invite(invitee, ["Denmark"]), "Must be an organization administrator") # Now verify an administrator can do it self.login("iago@zulip.com") self.assert_json_success(self.invite(invitee, ["Denmark"])) self.assertTrue(find_key_by_email(email)) self.assertTrue(find_key_by_email(email2)) self.check_sent_emails([email, email2]) def test_successful_invite_user_with_notifications_stream(self) -> None: """ A call to /json/invites with valid parameters unconditionally subscribes the invitee to the notifications stream if it exists and is public. """ realm = get_realm('zulip') notifications_stream = get_stream('Verona', realm) realm.notifications_stream_id = notifications_stream.id realm.save() self.login(self.example_email("hamlet")) invitee = 'alice-test@zulip.com' self.assert_json_success(self.invite(invitee, ['Denmark'])) self.assertTrue(find_key_by_email(invitee)) self.check_sent_emails([invitee]) prereg_user = PreregistrationUser.objects.get(email=invitee) stream_ids = [stream.id for stream in prereg_user.streams.all()] self.assertTrue(notifications_stream.id in stream_ids) def test_invite_user_signup_initial_history(self) -> None: """ Test that a new user invited to a stream receives some initial history but only from public streams. """ self.login(self.example_email('hamlet')) user_profile = self.example_user('hamlet') private_stream_name = "Secret" self.make_stream(private_stream_name, invite_only=True) self.subscribe(user_profile, private_stream_name) public_msg_id = self.send_stream_message( self.example_email("hamlet"), "Denmark", topic_name="Public topic", content="Public message", ) secret_msg_id = self.send_stream_message( self.example_email("hamlet"), private_stream_name, topic_name="Secret topic", content="Secret message", ) invitee = self.nonreg_email('alice') self.assert_json_success(self.invite(invitee, [private_stream_name, "Denmark"])) self.assertTrue(find_key_by_email(invitee)) self.submit_reg_form_for_user(invitee, "password") invitee_profile = self.nonreg_user('alice') invitee_msg_ids = [um.message_id for um in UserMessage.objects.filter(user_profile=invitee_profile)] self.assertTrue(public_msg_id in invitee_msg_ids) self.assertFalse(secret_msg_id in invitee_msg_ids) self.assertFalse(invitee_profile.is_realm_admin) # Test that exactly 2 new Zulip messages were sent, both notifications. last_3_messages = list(reversed(list(Message.objects.all().order_by("-id")[0:3]))) first_msg = last_3_messages[0] self.assertEqual(first_msg.id, secret_msg_id) # The first, from notification-bot to the user who invited the new user. second_msg = last_3_messages[1] self.assertEqual(second_msg.sender.email, "notification-bot@zulip.com") self.assertTrue(second_msg.content.startswith("alice_zulip.com <`alice@zulip.com`> accepted your")) # The second, from welcome-bot to the user who was invited. third_msg = last_3_messages[2] self.assertEqual(third_msg.sender.email, "welcome-bot@zulip.com") self.assertTrue(third_msg.content.startswith("Hello, and welcome to Zulip!")) def test_multi_user_invite(self) -> None: """ Invites multiple users with a variety of delimiters. """ self.login(self.example_email("hamlet")) # Intentionally use a weird string. self.assert_json_success(self.invite( """bob-test@zulip.com, carol-test@zulip.com, dave-test@zulip.com earl-test@zulip.com""", ["Denmark"])) for user in ("bob", "carol", "dave", "earl"): self.assertTrue(find_key_by_email("%s-test@zulip.com" % (user,))) self.check_sent_emails(["bob-test@zulip.com", "carol-test@zulip.com", "dave-test@zulip.com", "earl-test@zulip.com"]) def test_max_invites_model(self) -> None: realm = get_realm("zulip") self.assertEqual(realm.max_invites, settings.INVITES_DEFAULT_REALM_DAILY_MAX) realm.max_invites = 3 realm.save() self.assertEqual(get_realm("zulip").max_invites, 3) realm.max_invites = settings.INVITES_DEFAULT_REALM_DAILY_MAX realm.save() def test_invite_too_many_users(self) -> None: # Only a light test of this pathway; e.g. doesn't test that # the limit gets reset after 24 hours self.login(self.example_email("iago")) self.client_post("/json/invites", {"invitee_emails": "1@zulip.com, 2@zulip.com", "stream": ["Denmark"]}), self.assert_json_error( self.client_post("/json/invites", {"invitee_emails": ", ".join( [str(i) for i in range(get_realm("zulip").max_invites - 1)]), "stream": ["Denmark"]}), "You do not have enough remaining invites. " "Please contact zulip-admin@example.com to have your limit raised. " "No invitations were sent.") def test_missing_or_invalid_params(self) -> None: """ Tests inviting with various missing or invalid parameters. """ self.login(self.example_email("hamlet")) self.assert_json_error( self.client_post("/json/invites", {"invitee_emails": "foo@zulip.com"}), "You must specify at least one stream for invitees to join.") for address in ("noatsign.com", "outsideyourdomain@example.net"): self.assert_json_error( self.invite(address, ["Denmark"]), "Some emails did not validate, so we didn't send any invitations.") self.check_sent_emails([]) self.assert_json_error( self.invite("", ["Denmark"]), "You must specify at least one email address.") self.check_sent_emails([]) def test_guest_user_invitation(self) -> None: """ Guest user can't invite new users """ self.login(self.example_email("polonius")) invitee = "alice-test@zulip.com" self.assert_json_error(self.invite(invitee, ["Denmark"]), "Not allowed for guest users") self.assertEqual(find_key_by_email(invitee), None) self.check_sent_emails([]) def test_invalid_stream(self) -> None: """ Tests inviting to a non-existent stream. """ self.login(self.example_email("hamlet")) self.assert_json_error(self.invite("iago-test@zulip.com", ["NotARealStream"]), "Stream does not exist: NotARealStream. No invites were sent.") self.check_sent_emails([]) def test_invite_existing_user(self) -> None: """ If you invite an address already using Zulip, no invitation is sent. """ self.login(self.example_email("hamlet")) self.assert_json_error( self.client_post("/json/invites", {"invitee_emails": self.example_email("hamlet"), "stream": ["Denmark"]}), "We weren't able to invite anyone.") self.assertRaises(PreregistrationUser.DoesNotExist, lambda: PreregistrationUser.objects.get( email=self.example_email("hamlet"))) self.check_sent_emails([]) def test_invite_some_existing_some_new(self) -> None: """ If you invite a mix of already existing and new users, invitations are only sent to the new users. """ self.login(self.example_email("hamlet")) existing = [self.example_email("hamlet"), u"othello@zulip.com"] new = [u"foo-test@zulip.com", u"bar-test@zulip.com"] result = self.client_post("/json/invites", {"invitee_emails": "\n".join(existing + new), "stream": ["Denmark"]}) self.assert_json_error(result, "Some of those addresses are already using Zulip, \ so we didn't send them an invitation. We did send invitations to everyone else!") # We only created accounts for the new users. for email in existing: self.assertRaises(PreregistrationUser.DoesNotExist, lambda: PreregistrationUser.objects.get( email=email)) for email in new: self.assertTrue(PreregistrationUser.objects.get(email=email)) # We only sent emails to the new users. self.check_sent_emails(new) prereg_user = PreregistrationUser.objects.get(email='foo-test@zulip.com') self.assertEqual(prereg_user.email, 'foo-test@zulip.com') def test_invite_outside_domain_in_closed_realm(self) -> None: """ In a realm with `emails_restricted_to_domains = True`, you can't invite people with a different domain from that of the realm or your e-mail address. """ zulip_realm = get_realm("zulip") zulip_realm.emails_restricted_to_domains = True zulip_realm.save() self.login(self.example_email("hamlet")) external_address = "foo@example.com" self.assert_json_error( self.invite(external_address, ["Denmark"]), "Some emails did not validate, so we didn't send any invitations.") def test_invite_using_disposable_email(self) -> None: """ In a realm with `disallow_disposable_email_addresses = True`, you can't invite people with a disposable domain. """ zulip_realm = get_realm("zulip") zulip_realm.emails_restricted_to_domains = False zulip_realm.disallow_disposable_email_addresses = True zulip_realm.save() self.login(self.example_email("hamlet")) external_address = "foo@mailnator.com" self.assert_json_error( self.invite(external_address, ["Denmark"]), "Some emails did not validate, so we didn't send any invitations.") def test_invite_outside_domain_in_open_realm(self) -> None: """ In a realm with `emails_restricted_to_domains = False`, you can invite people with a different domain from that of the realm or your e-mail address. """ zulip_realm = get_realm("zulip") zulip_realm.emails_restricted_to_domains = False zulip_realm.save() self.login(self.example_email("hamlet")) external_address = "foo@example.com" self.assert_json_success(self.invite(external_address, ["Denmark"])) self.check_sent_emails([external_address]) def test_invite_outside_domain_before_closing(self) -> None: """ If you invite someone with a different domain from that of the realm when `emails_restricted_to_domains = False`, but `emails_restricted_to_domains` later changes to true, the invitation should succeed but the invitee's signup attempt should fail. """ zulip_realm = get_realm("zulip") zulip_realm.emails_restricted_to_domains = False zulip_realm.save() self.login(self.example_email("hamlet")) external_address = "foo@example.com" self.assert_json_success(self.invite(external_address, ["Denmark"])) self.check_sent_emails([external_address]) zulip_realm.emails_restricted_to_domains = True zulip_realm.save() result = self.submit_reg_form_for_user("foo@example.com", "password") self.assertEqual(result.status_code, 200) self.assert_in_response("only allows users with email addresses", result) def test_disposable_emails_before_closing(self) -> None: """ If you invite someone with a disposable email when `disallow_disposable_email_addresses = False`, but later changes to true, the invitation should succeed but the invitee's signup attempt should fail. """ zulip_realm = get_realm("zulip") zulip_realm.emails_restricted_to_domains = False zulip_realm.disallow_disposable_email_addresses = False zulip_realm.save() self.login(self.example_email("hamlet")) external_address = "foo@mailnator.com" self.assert_json_success(self.invite(external_address, ["Denmark"])) self.check_sent_emails([external_address]) zulip_realm.disallow_disposable_email_addresses = True zulip_realm.save() result = self.submit_reg_form_for_user("foo@mailnator.com", "password") self.assertEqual(result.status_code, 200) self.assert_in_response("Please sign up using a real email address.", result) def test_invite_with_email_containing_plus_before_closing(self) -> None: """ If you invite someone with an email containing plus when `emails_restricted_to_domains = False`, but later change `emails_restricted_to_domains = True`, the invitation should succeed but the invitee's signup attempt should fail as users are not allowed to signup using email containing + when the realm is restricted to domain. """ zulip_realm = get_realm("zulip") zulip_realm.emails_restricted_to_domains = False zulip_realm.save() self.login(self.example_email("hamlet")) external_address = "foo+label@zulip.com" self.assert_json_success(self.invite(external_address, ["Denmark"])) self.check_sent_emails([external_address]) zulip_realm.emails_restricted_to_domains = True zulip_realm.save() result = self.submit_reg_form_for_user(external_address, "password") self.assertEqual(result.status_code, 200) self.assert_in_response("Zulip Dev, does not allow signups using emails\n that contains +", result) def test_invalid_email_check_after_confirming_email(self) -> None: self.login(self.example_email("hamlet")) email = "test@zulip.com" self.assert_json_success(self.invite(email, ["Denmark"])) obj = Confirmation.objects.get(confirmation_key=find_key_by_email(email)) prereg_user = obj.content_object prereg_user.email = "invalid.email" prereg_user.save() result = self.submit_reg_form_for_user(email, "password") self.assertEqual(result.status_code, 200) self.assert_in_response("The email address you are trying to sign up with is not valid", result) def test_invite_with_non_ascii_streams(self) -> None: """ Inviting someone to streams with non-ASCII characters succeeds. """ self.login(self.example_email("hamlet")) invitee = "alice-test@zulip.com" stream_name = u"hümbüǵ" # Make sure we're subscribed before inviting someone. self.subscribe(self.example_user("hamlet"), stream_name) self.assert_json_success(self.invite(invitee, [stream_name])) def test_invitation_reminder_email(self) -> None: from django.core.mail import outbox # All users belong to zulip realm referrer_user = 'hamlet' current_user_email = self.example_email(referrer_user) self.login(current_user_email) invitee_email = self.nonreg_email('alice') self.assert_json_success(self.invite(invitee_email, ["Denmark"])) self.assertTrue(find_key_by_email(invitee_email)) self.check_sent_emails([invitee_email]) data = {"email": invitee_email, "referrer_email": current_user_email} invitee = PreregistrationUser.objects.get(email=data["email"]) referrer = self.example_user(referrer_user) link = create_confirmation_link(invitee, referrer.realm.host, Confirmation.INVITATION) context = common_context(referrer) context.update({ 'activate_url': link, 'referrer_name': referrer.full_name, 'referrer_email': referrer.email, 'referrer_realm_name': referrer.realm.name, }) with self.settings(EMAIL_BACKEND='django.core.mail.backends.console.EmailBackend'): send_future_email( "zerver/emails/invitation_reminder", referrer.realm, to_email=data["email"], from_address=FromAddress.NOREPLY, context=context) email_jobs_to_deliver = ScheduledEmail.objects.filter( scheduled_timestamp__lte=timezone_now()) self.assertEqual(len(email_jobs_to_deliver), 1) email_count = len(outbox) for job in email_jobs_to_deliver: send_email(**ujson.loads(job.data)) self.assertEqual(len(outbox), email_count + 1) self.assertIn(FromAddress.NOREPLY, outbox[-1].from_email) # Now verify that signing up clears invite_reminder emails email_jobs_to_deliver = ScheduledEmail.objects.filter( scheduled_timestamp__lte=timezone_now(), type=ScheduledEmail.INVITATION_REMINDER) self.assertEqual(len(email_jobs_to_deliver), 1) self.register(invitee_email, "test") email_jobs_to_deliver = ScheduledEmail.objects.filter( scheduled_timestamp__lte=timezone_now(), type=ScheduledEmail.INVITATION_REMINDER) self.assertEqual(len(email_jobs_to_deliver), 0) # make sure users can't take a valid confirmation key from another # pathway and use it with the invitation url route def test_confirmation_key_of_wrong_type(self) -> None: user = self.example_user('hamlet') url = create_confirmation_link(user, 'host', Confirmation.USER_REGISTRATION) registration_key = url.split('/')[-1] # Mainly a test of get_object_from_key, rather than of the invitation pathway with self.assertRaises(ConfirmationKeyException) as cm: get_object_from_key(registration_key, Confirmation.INVITATION) self.assertEqual(cm.exception.error_type, ConfirmationKeyException.DOES_NOT_EXIST) # Verify that using the wrong type doesn't work in the main confirm code path email_change_url = create_confirmation_link(user, 'host', Confirmation.EMAIL_CHANGE) email_change_key = email_change_url.split('/')[-1] url = '/accounts/do_confirm/' + email_change_key result = self.client_get(url) self.assert_in_success_response(["Whoops. We couldn't find your " "confirmation link in the system."], result) def test_confirmation_expired(self) -> None: user = self.example_user('hamlet') url = create_confirmation_link(user, 'host', Confirmation.USER_REGISTRATION) registration_key = url.split('/')[-1] conf = Confirmation.objects.filter(confirmation_key=registration_key).first() conf.date_sent -= datetime.timedelta(weeks=3) conf.save() target_url = '/' + url.split('/', 3)[3] result = self.client_get(target_url) self.assert_in_success_response(["Whoops. The confirmation link has expired " "or been deactivated."], result) class InvitationsTestCase(InviteUserBase): def test_successful_get_open_invitations(self) -> None: """ A GET call to /json/invites returns all unexpired invitations. """ days_to_activate = getattr(settings, 'ACCOUNT_ACTIVATION_DAYS', "Wrong") active_value = getattr(confirmation_settings, 'STATUS_ACTIVE', "Wrong") self.assertNotEqual(days_to_activate, "Wrong") self.assertNotEqual(active_value, "Wrong") self.login(self.example_email("iago")) user_profile = self.example_user("iago") prereg_user_one = PreregistrationUser(email="TestOne@zulip.com", referred_by=user_profile) prereg_user_one.save() expired_datetime = timezone_now() - datetime.timedelta(days=(days_to_activate+1)) prereg_user_two = PreregistrationUser(email="TestTwo@zulip.com", referred_by=user_profile) prereg_user_two.save() PreregistrationUser.objects.filter(id=prereg_user_two.id).update(invited_at=expired_datetime) prereg_user_three = PreregistrationUser(email="TestThree@zulip.com", referred_by=user_profile, status=active_value) prereg_user_three.save() result = self.client_get("/json/invites") self.assertEqual(result.status_code, 200) self.assert_in_success_response(["TestOne@zulip.com"], result) self.assert_not_in_success_response(["TestTwo@zulip.com", "TestThree@zulip.com"], result) def test_successful_delete_invitation(self) -> None: """ A DELETE call to /json/invites/<ID> should delete the invite and any scheduled invitation reminder emails. """ self.login(self.example_email("iago")) invitee = "DeleteMe@zulip.com" self.assert_json_success(self.invite(invitee, ['Denmark'])) prereg_user = PreregistrationUser.objects.get(email=invitee) # Verify that the scheduled email exists. ScheduledEmail.objects.get(address__iexact=invitee, type=ScheduledEmail.INVITATION_REMINDER) result = self.client_delete('/json/invites/' + str(prereg_user.id)) self.assertEqual(result.status_code, 200) error_result = self.client_delete('/json/invites/' + str(prereg_user.id)) self.assert_json_error(error_result, "No such invitation") self.assertRaises(ScheduledEmail.DoesNotExist, lambda: ScheduledEmail.objects.get(address__iexact=invitee, type=ScheduledEmail.INVITATION_REMINDER)) def test_successful_resend_invitation(self) -> None: """ A POST call to /json/invites/<ID>/resend should send an invitation reminder email and delete any scheduled invitation reminder email. """ self.login(self.example_email("iago")) invitee = "resend_me@zulip.com" self.assert_json_success(self.invite(invitee, ['Denmark'])) prereg_user = PreregistrationUser.objects.get(email=invitee) # Verify and then clear from the outbox the original invite email self.check_sent_emails([invitee], custom_from_name="Zulip") from django.core.mail import outbox outbox.pop() # Verify that the scheduled email exists. scheduledemail_filter = ScheduledEmail.objects.filter( address=invitee, type=ScheduledEmail.INVITATION_REMINDER) self.assertEqual(scheduledemail_filter.count(), 1) original_timestamp = scheduledemail_filter.values_list('scheduled_timestamp', flat=True) # Resend invite result = self.client_post('/json/invites/' + str(prereg_user.id) + '/resend') self.assertEqual(ScheduledEmail.objects.filter( address=invitee, type=ScheduledEmail.INVITATION_REMINDER).count(), 1) # Check that we have exactly one scheduled email, and that it is different self.assertEqual(scheduledemail_filter.count(), 1) self.assertNotEqual(original_timestamp, scheduledemail_filter.values_list('scheduled_timestamp', flat=True)) self.assertEqual(result.status_code, 200) error_result = self.client_post('/json/invites/' + str(9999) + '/resend') self.assert_json_error(error_result, "No such invitation") self.check_sent_emails([invitee], custom_from_name="Zulip") def test_accessing_invites_in_another_realm(self) -> None: invitor = UserProfile.objects.exclude(realm=get_realm('zulip')).first() prereg_user = PreregistrationUser.objects.create( email='email', referred_by=invitor, realm=invitor.realm) self.login(self.example_email("iago")) error_result = self.client_post('/json/invites/' + str(prereg_user.id) + '/resend') self.assert_json_error(error_result, "No such invitation") error_result = self.client_delete('/json/invites/' + str(prereg_user.id)) self.assert_json_error(error_result, "No such invitation") class InviteeEmailsParserTests(TestCase): def setUp(self) -> None: self.email1 = "email1@zulip.com" self.email2 = "email2@zulip.com" self.email3 = "email3@zulip.com" def test_if_emails_separated_by_commas_are_parsed_and_striped_correctly(self) -> None: emails_raw = "{} ,{}, {}".format(self.email1, self.email2, self.email3) expected_set = {self.email1, self.email2, self.email3} self.assertEqual(get_invitee_emails_set(emails_raw), expected_set) def test_if_emails_separated_by_newlines_are_parsed_and_striped_correctly(self) -> None: emails_raw = "{}\n {}\n {} ".format(self.email1, self.email2, self.email3) expected_set = {self.email1, self.email2, self.email3} self.assertEqual(get_invitee_emails_set(emails_raw), expected_set) def test_if_emails_from_email_client_separated_by_newlines_are_parsed_correctly(self) -> None: emails_raw = "Email One <{}>\nEmailTwo<{}>\nEmail Three<{}>".format(self.email1, self.email2, self.email3) expected_set = {self.email1, self.email2, self.email3} self.assertEqual(get_invitee_emails_set(emails_raw), expected_set) def test_if_emails_in_mixed_style_are_parsed_correctly(self) -> None: emails_raw = "Email One <{}>,EmailTwo<{}>\n{}".format(self.email1, self.email2, self.email3) expected_set = {self.email1, self.email2, self.email3} self.assertEqual(get_invitee_emails_set(emails_raw), expected_set) class MultiuseInviteTest(ZulipTestCase): def setUp(self) -> None: self.realm = get_realm('zulip') self.realm.invite_required = True self.realm.save() def generate_multiuse_invite_link(self, streams: List[Stream]=None, date_sent: Optional[datetime.datetime]=None) -> str: invite = MultiuseInvite(realm=self.realm, referred_by=self.example_user("iago")) invite.save() if streams is not None: invite.streams.set(streams) if date_sent is None: date_sent = timezone_now() key = generate_key() Confirmation.objects.create(content_object=invite, date_sent=date_sent, confirmation_key=key, type=Confirmation.MULTIUSE_INVITE) return confirmation_url(key, self.realm.host, Confirmation.MULTIUSE_INVITE) def check_user_able_to_register(self, email: str, invite_link: str) -> None: password = "password" result = self.client_post(invite_link, {'email': email}) self.assertEqual(result.status_code, 302) self.assertTrue(result["Location"].endswith( "/accounts/send_confirm/%s" % (email,))) result = self.client_get(result["Location"]) self.assert_in_response("Check your email so we can get started.", result) confirmation_url = self.get_confirmation_url_from_outbox(email) result = self.client_get(confirmation_url) self.assertEqual(result.status_code, 200) result = self.submit_reg_form_for_user(email, password) self.assertEqual(result.status_code, 302) from django.core.mail import outbox outbox.pop() def test_valid_multiuse_link(self) -> None: email1 = self.nonreg_email("test") email2 = self.nonreg_email("test1") email3 = self.nonreg_email("alice") date_sent = timezone_now() - datetime.timedelta(days=settings.INVITATION_LINK_VALIDITY_DAYS - 1) invite_link = self.generate_multiuse_invite_link(date_sent=date_sent) self.check_user_able_to_register(email1, invite_link) self.check_user_able_to_register(email2, invite_link) self.check_user_able_to_register(email3, invite_link) def test_expired_multiuse_link(self) -> None: email = self.nonreg_email('newuser') date_sent = timezone_now() - datetime.timedelta(days=settings.INVITATION_LINK_VALIDITY_DAYS) invite_link = self.generate_multiuse_invite_link(date_sent=date_sent) result = self.client_post(invite_link, {'email': email}) self.assertEqual(result.status_code, 200) self.assert_in_response("The confirmation link has expired or been deactivated.", result) def test_invalid_multiuse_link(self) -> None: email = self.nonreg_email('newuser') invite_link = "/join/invalid_key/" result = self.client_post(invite_link, {'email': email}) self.assertEqual(result.status_code, 200) self.assert_in_response("Whoops. The confirmation link is malformed.", result) def test_invalid_multiuse_link_in_open_realm(self) -> None: self.realm.invite_required = False self.realm.save() email = self.nonreg_email('newuser') invite_link = "/join/invalid_key/" with patch('zerver.views.registration.get_realm_from_request', return_value=self.realm): with patch('zerver.views.registration.get_realm', return_value=self.realm): self.check_user_able_to_register(email, invite_link) def test_multiuse_link_with_specified_streams(self) -> None: name1 = "newuser" name2 = "bob" email1 = self.nonreg_email(name1) email2 = self.nonreg_email(name2) stream_names = ["Rome", "Scotland", "Venice"] streams = [get_stream(stream_name, self.realm) for stream_name in stream_names] invite_link = self.generate_multiuse_invite_link(streams=streams) self.check_user_able_to_register(email1, invite_link) self.check_user_subscribed_only_to_streams(name1, streams) stream_names = ["Rome", "Verona"] streams = [get_stream(stream_name, self.realm) for stream_name in stream_names] invite_link = self.generate_multiuse_invite_link(streams=streams) self.check_user_able_to_register(email2, invite_link) self.check_user_subscribed_only_to_streams(name2, streams) def test_create_multiuse_link_api_call(self) -> None: self.login(self.example_email('iago')) result = self.client_post('/json/invites/multiuse') self.assert_json_success(result) invite_link = result.json()["invite_link"] self.check_user_able_to_register(self.nonreg_email("test"), invite_link) def test_create_multiuse_link_with_specified_streams_api_call(self) -> None: self.login(self.example_email('iago')) stream_names = ["Rome", "Scotland", "Venice"] streams = [get_stream(stream_name, self.realm) for stream_name in stream_names] stream_ids = [stream.id for stream in streams] result = self.client_post('/json/invites/multiuse', {"stream_ids": ujson.dumps(stream_ids)}) self.assert_json_success(result) invite_link = result.json()["invite_link"] self.check_user_able_to_register(self.nonreg_email("test"), invite_link) self.check_user_subscribed_only_to_streams("test", streams) def test_only_admin_can_create_multiuse_link_api_call(self) -> None: self.login(self.example_email('iago')) # Only admins should be able to create multiuse invites even if # invite_by_admins_only is set to False. self.realm.invite_by_admins_only = False self.realm.save() result = self.client_post('/json/invites/multiuse') self.assert_json_success(result) invite_link = result.json()["invite_link"] self.check_user_able_to_register(self.nonreg_email("test"), invite_link) self.login(self.example_email('hamlet')) result = self.client_post('/json/invites/multiuse') self.assert_json_error(result, "Must be an organization administrator") def test_create_multiuse_link_invalid_stream_api_call(self) -> None: self.login(self.example_email('iago')) result = self.client_post('/json/invites/multiuse', {"stream_ids": ujson.dumps([54321])}) self.assert_json_error(result, "Invalid stream id 54321. No invites were sent.") class EmailUnsubscribeTests(ZulipTestCase): def test_error_unsubscribe(self) -> None: # An invalid unsubscribe token "test123" produces an error. result = self.client_get('/accounts/unsubscribe/missed_messages/test123') self.assert_in_response('Unknown email unsubscribe request', result) # An unknown message type "fake" produces an error. user_profile = self.example_user('hamlet') unsubscribe_link = one_click_unsubscribe_link(user_profile, "fake") result = self.client_get(urllib.parse.urlparse(unsubscribe_link).path) self.assert_in_response('Unknown email unsubscribe request', result) def test_missedmessage_unsubscribe(self) -> None: """ We provide one-click unsubscribe links in missed message e-mails that you can click even when logged out to update your email notification settings. """ user_profile = self.example_user('hamlet') user_profile.enable_offline_email_notifications = True user_profile.save() unsubscribe_link = one_click_unsubscribe_link(user_profile, "missed_messages") result = self.client_get(urllib.parse.urlparse(unsubscribe_link).path) self.assertEqual(result.status_code, 200) user_profile.refresh_from_db() self.assertFalse(user_profile.enable_offline_email_notifications) def test_welcome_unsubscribe(self) -> None: """ We provide one-click unsubscribe links in welcome e-mails that you can click even when logged out to stop receiving them. """ user_profile = self.example_user('hamlet') # Simulate a new user signing up, which enqueues 2 welcome e-mails. enqueue_welcome_emails(user_profile) self.assertEqual(2, ScheduledEmail.objects.filter(user=user_profile).count()) # Simulate unsubscribing from the welcome e-mails. unsubscribe_link = one_click_unsubscribe_link(user_profile, "welcome") result = self.client_get(urllib.parse.urlparse(unsubscribe_link).path) # The welcome email jobs are no longer scheduled. self.assertEqual(result.status_code, 200) self.assertEqual(0, ScheduledEmail.objects.filter(user=user_profile).count()) def test_digest_unsubscribe(self) -> None: """ We provide one-click unsubscribe links in digest e-mails that you can click even when logged out to stop receiving them. Unsubscribing from these emails also dequeues any digest email jobs that have been queued. """ user_profile = self.example_user('hamlet') self.assertTrue(user_profile.enable_digest_emails) # Enqueue a fake digest email. context = {'name': '', 'realm_uri': '', 'unread_pms': [], 'hot_conversations': [], 'new_users': [], 'new_streams': {'plain': []}, 'unsubscribe_link': ''} send_future_email('zerver/emails/digest', user_profile.realm, to_user_id=user_profile.id, context=context) self.assertEqual(1, ScheduledEmail.objects.filter(user=user_profile).count()) # Simulate unsubscribing from digest e-mails. unsubscribe_link = one_click_unsubscribe_link(user_profile, "digest") result = self.client_get(urllib.parse.urlparse(unsubscribe_link).path) # The setting is toggled off, and scheduled jobs have been removed. self.assertEqual(result.status_code, 200) # Circumvent user_profile caching. user_profile.refresh_from_db() self.assertFalse(user_profile.enable_digest_emails) self.assertEqual(0, ScheduledEmail.objects.filter(user=user_profile).count()) def test_login_unsubscribe(self) -> None: """ We provide one-click unsubscribe links in login e-mails that you can click even when logged out to update your email notification settings. """ user_profile = self.example_user('hamlet') user_profile.enable_login_emails = True user_profile.save() unsubscribe_link = one_click_unsubscribe_link(user_profile, "login") result = self.client_get(urllib.parse.urlparse(unsubscribe_link).path) self.assertEqual(result.status_code, 200) user_profile.refresh_from_db() self.assertFalse(user_profile.enable_login_emails) class RealmCreationTest(ZulipTestCase): @override_settings(OPEN_REALM_CREATION=True) def check_able_to_create_realm(self, email: str) -> None: password = "test" string_id = "zuliptest" realm = get_realm(string_id) # Make sure the realm does not exist self.assertIsNone(realm) # Create new realm with the email result = self.client_post('/new/', {'email': email}) self.assertEqual(result.status_code, 302) self.assertTrue(result["Location"].endswith( "/accounts/new/send_confirm/%s" % (email,))) result = self.client_get(result["Location"]) self.assert_in_response("Check your email so we can get started.", result) # Visit the confirmation link. confirmation_url = self.get_confirmation_url_from_outbox(email) result = self.client_get(confirmation_url) self.assertEqual(result.status_code, 200) result = self.submit_reg_form_for_user(email, password, realm_subdomain=string_id) self.assertEqual(result.status_code, 302) self.assertTrue(result["Location"].startswith('http://zuliptest.testserver/accounts/login/subdomain/')) # Make sure the realm is created realm = get_realm(string_id) self.assertIsNotNone(realm) self.assertEqual(realm.string_id, string_id) self.assertEqual(get_user(email, realm).realm, realm) # Check defaults self.assertEqual(realm.org_type, Realm.CORPORATE) self.assertEqual(realm.emails_restricted_to_domains, False) self.assertEqual(realm.invite_required, True) # Check welcome messages for stream_name, text, message_count in [ ('announce', 'This is', 1), (Realm.INITIAL_PRIVATE_STREAM_NAME, 'This is', 1), ('general', 'Welcome to', 1), ('new members', 'stream is', 1), ('zulip', 'Here is', 3)]: stream = get_stream(stream_name, realm) recipient = get_stream_recipient(stream.id) messages = Message.objects.filter(recipient=recipient).order_by('pub_date') self.assertEqual(len(messages), message_count) self.assertIn(text, messages[0].content) def test_create_realm_non_existing_email(self) -> None: self.check_able_to_create_realm("user1@test.com") def test_create_realm_existing_email(self) -> None: self.check_able_to_create_realm("hamlet@zulip.com") def test_create_realm_as_system_bot(self) -> None: result = self.client_post('/new/', {'email': 'notification-bot@zulip.com'}) self.assertEqual(result.status_code, 200) self.assert_in_response('notification-bot@zulip.com is an email address reserved', result) def test_create_realm_no_creation_key(self) -> None: """ Trying to create a realm without a creation_key should fail when OPEN_REALM_CREATION is false. """ email = "user1@test.com" with self.settings(OPEN_REALM_CREATION=False): # Create new realm with the email, but no creation key. result = self.client_post('/new/', {'email': email}) self.assertEqual(result.status_code, 200) self.assert_in_response('New organization creation disabled', result) @override_settings(OPEN_REALM_CREATION=True) def test_create_realm_with_subdomain(self) -> None: password = "test" string_id = "zuliptest" email = "user1@test.com" realm_name = "Test" # Make sure the realm does not exist self.assertIsNone(get_realm(string_id)) # Create new realm with the email result = self.client_post('/new/', {'email': email}) self.assertEqual(result.status_code, 302) self.assertTrue(result["Location"].endswith( "/accounts/new/send_confirm/%s" % (email,))) result = self.client_get(result["Location"]) self.assert_in_response("Check your email so we can get started.", result) # Visit the confirmation link. confirmation_url = self.get_confirmation_url_from_outbox(email) result = self.client_get(confirmation_url) self.assertEqual(result.status_code, 200) result = self.submit_reg_form_for_user(email, password, realm_subdomain = string_id, realm_name=realm_name, # Pass HTTP_HOST for the target subdomain HTTP_HOST=string_id + ".testserver") self.assertEqual(result.status_code, 302) # Make sure the realm is created realm = get_realm(string_id) self.assertIsNotNone(realm) self.assertEqual(realm.string_id, string_id) self.assertEqual(get_user(email, realm).realm, realm) self.assertEqual(realm.name, realm_name) self.assertEqual(realm.subdomain, string_id) @override_settings(OPEN_REALM_CREATION=True) def test_mailinator_signup(self) -> None: result = self.client_post('/new/', {'email': "hi@mailinator.com"}) self.assert_in_response('Please use your real email address.', result) @override_settings(OPEN_REALM_CREATION=True) def test_subdomain_restrictions(self) -> None: password = "test" email = "user1@test.com" realm_name = "Test" result = self.client_post('/new/', {'email': email}) self.client_get(result["Location"]) confirmation_url = self.get_confirmation_url_from_outbox(email) self.client_get(confirmation_url) errors = {'id': "length 3 or greater", '-id': "cannot start or end with a", 'string-ID': "lowercase letters", 'string_id': "lowercase letters", 'stream': "unavailable", 'streams': "unavailable", 'about': "unavailable", 'abouts': "unavailable", 'zephyr': "unavailable"} for string_id, error_msg in errors.items(): result = self.submit_reg_form_for_user(email, password, realm_subdomain = string_id, realm_name = realm_name) self.assert_in_response(error_msg, result) # test valid subdomain result = self.submit_reg_form_for_user(email, password, realm_subdomain = 'a-0', realm_name = realm_name) self.assertEqual(result.status_code, 302) self.assertTrue(result.url.startswith('http://a-0.testserver/accounts/login/subdomain/')) @override_settings(OPEN_REALM_CREATION=True) def test_subdomain_restrictions_root_domain(self) -> None: password = "test" email = "user1@test.com" realm_name = "Test" result = self.client_post('/new/', {'email': email}) self.client_get(result["Location"]) confirmation_url = self.get_confirmation_url_from_outbox(email) self.client_get(confirmation_url) # test root domain will fail with ROOT_DOMAIN_LANDING_PAGE with self.settings(ROOT_DOMAIN_LANDING_PAGE=True): result = self.submit_reg_form_for_user(email, password, realm_subdomain = '', realm_name = realm_name) self.assert_in_response('unavailable', result) # test valid use of root domain result = self.submit_reg_form_for_user(email, password, realm_subdomain = '', realm_name = realm_name) self.assertEqual(result.status_code, 302) self.assertTrue(result.url.startswith('http://testserver/accounts/login/subdomain/')) @override_settings(OPEN_REALM_CREATION=True) def test_subdomain_restrictions_root_domain_option(self) -> None: password = "test" email = "user1@test.com" realm_name = "Test" result = self.client_post('/new/', {'email': email}) self.client_get(result["Location"]) confirmation_url = self.get_confirmation_url_from_outbox(email) self.client_get(confirmation_url) # test root domain will fail with ROOT_DOMAIN_LANDING_PAGE with self.settings(ROOT_DOMAIN_LANDING_PAGE=True): result = self.submit_reg_form_for_user(email, password, realm_subdomain = 'abcdef', realm_in_root_domain = 'true', realm_name = realm_name) self.assert_in_response('unavailable', result) # test valid use of root domain result = self.submit_reg_form_for_user(email, password, realm_subdomain = 'abcdef', realm_in_root_domain = 'true', realm_name = realm_name) self.assertEqual(result.status_code, 302) self.assertTrue(result.url.startswith('http://testserver/accounts/login/subdomain/')) def test_is_root_domain_available(self) -> None: self.assertTrue(is_root_domain_available()) with self.settings(ROOT_DOMAIN_LANDING_PAGE=True): self.assertFalse(is_root_domain_available()) realm = get_realm("zulip") realm.string_id = Realm.SUBDOMAIN_FOR_ROOT_DOMAIN realm.save() self.assertFalse(is_root_domain_available()) def test_subdomain_check_api(self) -> None: result = self.client_get("/json/realm/subdomain/zulip") self.assert_in_success_response(["Subdomain unavailable. Please choose a different one."], result) result = self.client_get("/json/realm/subdomain/zu_lip") self.assert_in_success_response(["Subdomain can only have lowercase letters, numbers, and \'-\'s."], result) result = self.client_get("/json/realm/subdomain/hufflepuff") self.assert_in_success_response(["available"], result) self.assert_not_in_success_response(["unavailable"], result) def test_subdomain_check_management_command(self) -> None: # Short names should work check_subdomain_available('aa', from_management_command=True) # So should reserved ones check_subdomain_available('zulip', from_management_command=True) # malformed names should still not with self.assertRaises(ValidationError): check_subdomain_available('-ba_d-', from_management_command=True) class UserSignUpTest(ZulipTestCase): def _assert_redirected_to(self, result: HttpResponse, url: str) -> None: self.assertEqual(result.status_code, 302) self.assertEqual(result['LOCATION'], url) def test_bad_email_configuration_for_accounts_home(self) -> None: """ Make sure we redirect for SMTP errors. """ email = self.nonreg_email('newguy') smtp_mock = patch( 'zerver.views.registration.send_confirm_registration_email', side_effect=smtplib.SMTPException('uh oh') ) error_mock = patch('logging.error') with smtp_mock, error_mock as err: result = self.client_post('/accounts/home/', {'email': email}) self._assert_redirected_to(result, '/config-error/smtp') self.assertEqual( err.call_args_list[0][0][0], 'Error in accounts_home: uh oh' ) def test_bad_email_configuration_for_create_realm(self) -> None: """ Make sure we redirect for SMTP errors. """ email = self.nonreg_email('newguy') smtp_mock = patch( 'zerver.views.registration.send_confirm_registration_email', side_effect=smtplib.SMTPException('uh oh') ) error_mock = patch('logging.error') with smtp_mock, error_mock as err: result = self.client_post('/new/', {'email': email}) self._assert_redirected_to(result, '/config-error/smtp') self.assertEqual( err.call_args_list[0][0][0], 'Error in create_realm: uh oh' ) def test_user_default_language_and_timezone(self) -> None: """ Check if the default language of new user is the default language of the realm. """ email = self.nonreg_email('newguy') password = "newpassword" timezone = "US/Mountain" realm = get_realm('zulip') do_set_realm_property(realm, 'default_language', u"de") result = self.client_post('/accounts/home/', {'email': email}) self.assertEqual(result.status_code, 302) self.assertTrue(result["Location"].endswith( "/accounts/send_confirm/%s" % (email,))) result = self.client_get(result["Location"]) self.assert_in_response("Check your email so we can get started.", result) # Visit the confirmation link. confirmation_url = self.get_confirmation_url_from_outbox(email) result = self.client_get(confirmation_url) self.assertEqual(result.status_code, 200) # Pick a password and agree to the ToS. result = self.submit_reg_form_for_user(email, password, timezone=timezone) self.assertEqual(result.status_code, 302) user_profile = self.nonreg_user('newguy') self.assertEqual(user_profile.default_language, realm.default_language) self.assertEqual(user_profile.timezone, timezone) from django.core.mail import outbox outbox.pop() def test_default_twenty_four_hour_time(self) -> None: """ Check if the default twenty_four_hour_time setting of new user is the default twenty_four_hour_time of the realm. """ email = self.nonreg_email('newguy') password = "newpassword" realm = get_realm('zulip') do_set_realm_property(realm, 'default_twenty_four_hour_time', True) result = self.client_post('/accounts/home/', {'email': email}) self.assertEqual(result.status_code, 302) self.assertTrue(result["Location"].endswith( "/accounts/send_confirm/%s" % (email,))) result = self.client_get(result["Location"]) self.assert_in_response("Check your email so we can get started.", result) # Visit the confirmation link. confirmation_url = self.get_confirmation_url_from_outbox(email) result = self.client_get(confirmation_url) self.assertEqual(result.status_code, 200) result = self.submit_reg_form_for_user(email, password) self.assertEqual(result.status_code, 302) user_profile = self.nonreg_user('newguy') self.assertEqual(user_profile.twenty_four_hour_time, realm.default_twenty_four_hour_time) def test_signup_already_active(self) -> None: """ Check if signing up with an active email redirects to a login page. """ email = self.example_email("hamlet") result = self.client_post('/accounts/home/', {'email': email}) self.assertEqual(result.status_code, 302) self.assertIn('login', result['Location']) result = self.client_get(result.url) self.assert_in_response("You've already registered", result) def test_signup_system_bot(self) -> None: email = "notification-bot@zulip.com" result = self.client_post('/accounts/home/', {'email': email}, subdomain="lear") self.assertEqual(result.status_code, 302) self.assertIn('login', result['Location']) result = self.client_get(result.url) # This is not really the right error message, but at least it's an error. self.assert_in_response("You've already registered", result) def test_signup_existing_email(self) -> None: """ Check if signing up with an email used in another realm succeeds. """ email = self.example_email('hamlet') password = "newpassword" realm = get_realm('lear') result = self.client_post('/accounts/home/', {'email': email}, subdomain="lear") self.assertEqual(result.status_code, 302) result = self.client_get(result["Location"], subdomain="lear") confirmation_url = self.get_confirmation_url_from_outbox(email) result = self.client_get(confirmation_url, subdomain="lear") self.assertEqual(result.status_code, 200) result = self.submit_reg_form_for_user(email, password, subdomain="lear") self.assertEqual(result.status_code, 302) get_user(email, realm) self.assertEqual(UserProfile.objects.filter(email=email).count(), 2) def test_signup_invalid_name(self) -> None: """ Check if an invalid name during signup is handled properly. """ email = "newguy@zulip.com" password = "newpassword" result = self.client_post('/accounts/home/', {'email': email}) self.assertEqual(result.status_code, 302) self.assertTrue(result["Location"].endswith( "/accounts/send_confirm/%s" % (email,))) result = self.client_get(result["Location"]) self.assert_in_response("Check your email so we can get started.", result) # Visit the confirmation link. confirmation_url = self.get_confirmation_url_from_outbox(email) result = self.client_get(confirmation_url) self.assertEqual(result.status_code, 200) # Pick a password and agree to the ToS. result = self.submit_reg_form_for_user(email, password, full_name="<invalid>") self.assert_in_success_response(["Invalid characters in name!"], result) # Verify that the user is asked for name and password self.assert_in_success_response(['id_password', 'id_full_name'], result) def test_signup_without_password(self) -> None: """ Check if signing up without a password works properly when password_auth_enabled is False. """ email = self.nonreg_email('newuser') result = self.client_post('/accounts/home/', {'email': email}) self.assertEqual(result.status_code, 302) self.assertTrue(result["Location"].endswith( "/accounts/send_confirm/%s" % (email,))) result = self.client_get(result["Location"]) self.assert_in_response("Check your email so we can get started.", result) # Visit the confirmation link. confirmation_url = self.get_confirmation_url_from_outbox(email) result = self.client_get(confirmation_url) self.assertEqual(result.status_code, 200) with patch('zerver.views.registration.password_auth_enabled', return_value=False): result = self.client_post( '/accounts/register/', {'full_name': 'New User', 'key': find_key_by_email(email), 'terms': True}) # User should now be logged in. self.assertEqual(result.status_code, 302) user_profile = self.nonreg_user('newuser') self.assertEqual(get_session_dict_user(self.client.session), user_profile.id) def test_signup_without_full_name(self) -> None: """ Check if signing up without a full name redirects to a registration form. """ email = "newguy@zulip.com" password = "newpassword" result = self.client_post('/accounts/home/', {'email': email}) self.assertEqual(result.status_code, 302) self.assertTrue(result["Location"].endswith( "/accounts/send_confirm/%s" % (email,))) result = self.client_get(result["Location"]) self.assert_in_response("Check your email so we can get started.", result) # Visit the confirmation link. confirmation_url = self.get_confirmation_url_from_outbox(email) result = self.client_get(confirmation_url) self.assertEqual(result.status_code, 200) result = self.client_post( '/accounts/register/', {'password': password, 'key': find_key_by_email(email), 'terms': True, 'from_confirmation': '1'}) self.assert_in_success_response(["You're almost there."], result) # Verify that the user is asked for name and password self.assert_in_success_response(['id_password', 'id_full_name'], result) def test_signup_with_full_name(self) -> None: """ Check if signing up without a full name redirects to a registration form. """ email = "newguy@zulip.com" password = "newpassword" result = self.client_post('/accounts/home/', {'email': email}) self.assertEqual(result.status_code, 302) self.assertTrue(result["Location"].endswith( "/accounts/send_confirm/%s" % (email,))) result = self.client_get(result["Location"]) self.assert_in_response("Check your email so we can get started.", result) # Visit the confirmation link. confirmation_url = self.get_confirmation_url_from_outbox(email) result = self.client_get(confirmation_url) self.assertEqual(result.status_code, 200) result = self.client_post( '/accounts/register/', {'password': password, 'key': find_key_by_email(email), 'terms': True, 'full_name': "New Guy", 'from_confirmation': '1'}) self.assert_in_success_response(["You're almost there."], result) def test_signup_with_default_stream_group(self) -> None: # Check if user is subscribed to the streams of default # stream group as well as default streams. email = self.nonreg_email('newguy') password = "newpassword" realm = get_realm("zulip") result = self.client_post('/accounts/home/', {'email': email}) self.assertEqual(result.status_code, 302) result = self.client_get(result["Location"]) confirmation_url = self.get_confirmation_url_from_outbox(email) result = self.client_get(confirmation_url) self.assertEqual(result.status_code, 200) default_streams = [] for stream_name in ["venice", "verona"]: stream = get_stream(stream_name, realm) do_add_default_stream(stream) default_streams.append(stream) group1_streams = [] for stream_name in ["scotland", "denmark"]: stream = get_stream(stream_name, realm) group1_streams.append(stream) do_create_default_stream_group(realm, "group 1", "group 1 description", group1_streams) result = self.submit_reg_form_for_user(email, password, default_stream_groups=["group 1"]) self.check_user_subscribed_only_to_streams("newguy", default_streams + group1_streams) def test_signup_with_multiple_default_stream_groups(self) -> None: # Check if user is subscribed to the streams of default # stream groups as well as default streams. email = self.nonreg_email('newguy') password = "newpassword" realm = get_realm("zulip") result = self.client_post('/accounts/home/', {'email': email}) self.assertEqual(result.status_code, 302) result = self.client_get(result["Location"]) confirmation_url = self.get_confirmation_url_from_outbox(email) result = self.client_get(confirmation_url) self.assertEqual(result.status_code, 200) default_streams = [] for stream_name in ["venice", "verona"]: stream = get_stream(stream_name, realm) do_add_default_stream(stream) default_streams.append(stream) group1_streams = [] for stream_name in ["scotland", "denmark"]: stream = get_stream(stream_name, realm) group1_streams.append(stream) do_create_default_stream_group(realm, "group 1", "group 1 description", group1_streams) group2_streams = [] for stream_name in ["scotland", "rome"]: stream = get_stream(stream_name, realm) group2_streams.append(stream) do_create_default_stream_group(realm, "group 2", "group 2 description", group2_streams) result = self.submit_reg_form_for_user(email, password, default_stream_groups=["group 1", "group 2"]) self.check_user_subscribed_only_to_streams( "newguy", list(set(default_streams + group1_streams + group2_streams))) def test_signup_without_user_settings_from_another_realm(self) -> None: email = self.example_email('hamlet') password = "newpassword" subdomain = "lear" realm = get_realm("lear") # Make an account in the Zulip realm, but we're not copying from there. hamlet_in_zulip = get_user(self.example_email("hamlet"), get_realm("zulip")) hamlet_in_zulip.left_side_userlist = True hamlet_in_zulip.default_language = "de" hamlet_in_zulip.emojiset = "twitter" hamlet_in_zulip.high_contrast_mode = True hamlet_in_zulip.enter_sends = True hamlet_in_zulip.tutorial_status = UserProfile.TUTORIAL_FINISHED hamlet_in_zulip.save() result = self.client_post('/accounts/home/', {'email': email}, subdomain=subdomain) self.assertEqual(result.status_code, 302) result = self.client_get(result["Location"], subdomain=subdomain) confirmation_url = self.get_confirmation_url_from_outbox(email) result = self.client_get(confirmation_url, subdomain=subdomain) self.assertEqual(result.status_code, 200) result = self.submit_reg_form_for_user(email, password, source_realm="on", HTTP_HOST=subdomain + ".testserver") hamlet = get_user(self.example_email("hamlet"), realm) self.assertEqual(hamlet.left_side_userlist, False) self.assertEqual(hamlet.default_language, "en") self.assertEqual(hamlet.emojiset, "google-blob") self.assertEqual(hamlet.high_contrast_mode, False) self.assertEqual(hamlet.enable_stream_sounds, False) self.assertEqual(hamlet.enter_sends, False) self.assertEqual(hamlet.tutorial_status, UserProfile.TUTORIAL_WAITING) def test_signup_with_user_settings_from_another_realm(self) -> None: email = self.example_email('hamlet') password = "newpassword" subdomain = "lear" lear_realm = get_realm("lear") zulip_realm = get_realm("zulip") self.login(self.example_email("hamlet")) with get_test_image_file('img.png') as image_file: self.client_post("/json/users/me/avatar", {'file': image_file}) hamlet_in_zulip = get_user(self.example_email("hamlet"), zulip_realm) hamlet_in_zulip.left_side_userlist = True hamlet_in_zulip.default_language = "de" hamlet_in_zulip.emojiset = "twitter" hamlet_in_zulip.high_contrast_mode = True hamlet_in_zulip.enter_sends = True hamlet_in_zulip.tutorial_status = UserProfile.TUTORIAL_FINISHED hamlet_in_zulip.save() result = self.client_post('/accounts/home/', {'email': email}, subdomain=subdomain) self.assertEqual(result.status_code, 302) result = self.client_get(result["Location"], subdomain=subdomain) confirmation_url = self.get_confirmation_url_from_outbox(email) result = self.client_get(confirmation_url, subdomain=subdomain) self.assertEqual(result.status_code, 200) result = self.submit_reg_form_for_user(email, password, source_realm="zulip", HTTP_HOST=subdomain + ".testserver") hamlet_in_lear = get_user(self.example_email("hamlet"), lear_realm) self.assertEqual(hamlet_in_lear.left_side_userlist, True) self.assertEqual(hamlet_in_lear.default_language, "de") self.assertEqual(hamlet_in_lear.emojiset, "twitter") self.assertEqual(hamlet_in_lear.high_contrast_mode, True) self.assertEqual(hamlet_in_lear.enter_sends, True) self.assertEqual(hamlet_in_lear.enable_stream_sounds, False) self.assertEqual(hamlet_in_lear.tutorial_status, UserProfile.TUTORIAL_FINISHED) zulip_path_id = avatar_disk_path(hamlet_in_zulip) hamlet_path_id = avatar_disk_path(hamlet_in_zulip) self.assertEqual(open(zulip_path_id, "rb").read(), open(hamlet_path_id, "rb").read()) def test_signup_invalid_subdomain(self) -> None: """ Check if attempting to authenticate to the wrong subdomain logs an error and redirects. """ email = "newuser@zulip.com" password = "newpassword" result = self.client_post('/accounts/home/', {'email': email}) self.assertEqual(result.status_code, 302) self.assertTrue(result["Location"].endswith( "/accounts/send_confirm/%s" % (email,))) result = self.client_get(result["Location"]) self.assert_in_response("Check your email so we can get started.", result) # Visit the confirmation link. confirmation_url = self.get_confirmation_url_from_outbox(email) result = self.client_get(confirmation_url) self.assertEqual(result.status_code, 200) def invalid_subdomain(**kwargs: Any) -> Any: return_data = kwargs.get('return_data', {}) return_data['invalid_subdomain'] = True with patch('zerver.views.registration.authenticate', side_effect=invalid_subdomain): with patch('logging.error') as mock_error: result = self.client_post( '/accounts/register/', {'password': password, 'full_name': 'New User', 'key': find_key_by_email(email), 'terms': True}) mock_error.assert_called_once() self.assertEqual(result.status_code, 302) def test_replace_subdomain_in_confirmation_link(self) -> None: """ Check that manually changing the subdomain in a registration confirmation link doesn't allow you to register to a different realm. """ email = "newuser@zulip.com" self.client_post('/accounts/home/', {'email': email}) result = self.client_post( '/accounts/register/', {'password': "password", 'key': find_key_by_email(email), 'terms': True, 'full_name': "New User", 'from_confirmation': '1'}, subdomain="zephyr") self.assert_in_success_response(["We couldn't find your confirmation link"], result) def test_failed_signup_due_to_restricted_domain(self) -> None: realm = get_realm('zulip') realm.invite_required = False realm.save() request = HostRequestMock(host = realm.host) request.session = {} # type: ignore email = 'user@acme.com' form = HomepageForm({'email': email}, realm=realm) self.assertIn("Your email address, {}, is not in one of the domains".format(email), form.errors['email'][0]) def test_failed_signup_due_to_disposable_email(self) -> None: realm = get_realm('zulip') realm.emails_restricted_to_domains = False realm.disallow_disposable_email_addresses = True realm.save() request = HostRequestMock(host = realm.host) request.session = {} # type: ignore email = 'abc@mailnator.com' form = HomepageForm({'email': email}, realm=realm) self.assertIn("Please use your real email address", form.errors['email'][0]) def test_failed_signup_due_to_email_containing_plus(self) -> None: realm = get_realm('zulip') realm.emails_restricted_to_domains = True realm.save() request = HostRequestMock(host = realm.host) request.session = {} # type: ignore email = 'iago+label@zulip.com' form = HomepageForm({'email': email}, realm=realm) self.assertIn("Email addresses containing + are not allowed in this organization.", form.errors['email'][0]) def test_failed_signup_due_to_invite_required(self) -> None: realm = get_realm('zulip') realm.invite_required = True realm.save() request = HostRequestMock(host = realm.host) request.session = {} # type: ignore email = 'user@zulip.com' form = HomepageForm({'email': email}, realm=realm) self.assertIn("Please request an invite for {} from".format(email), form.errors['email'][0]) def test_failed_signup_due_to_nonexistent_realm(self) -> None: request = HostRequestMock(host = 'acme.' + settings.EXTERNAL_HOST) request.session = {} # type: ignore email = 'user@acme.com' form = HomepageForm({'email': email}, realm=None) self.assertIn("organization you are trying to join using {} does " "not exist".format(email), form.errors['email'][0]) def test_access_signup_page_in_root_domain_without_realm(self) -> None: result = self.client_get('/register', subdomain="", follow=True) self.assert_in_success_response(["Find your Zulip accounts"], result) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend', 'zproject.backends.ZulipDummyBackend')) def test_ldap_registration_from_confirmation(self) -> None: password = "testing" email = "newuser@zulip.com" subdomain = "zulip" ldap_user_attr_map = {'full_name': 'fn', 'short_name': 'sn'} ldap_patcher = patch('django_auth_ldap.config.ldap.initialize') mock_initialize = ldap_patcher.start() mock_ldap = MockLDAP() mock_initialize.return_value = mock_ldap mock_ldap.directory = { 'uid=newuser,ou=users,dc=zulip,dc=com': { 'userPassword': 'testing', 'fn': ['New LDAP fullname'] } } with patch('zerver.views.registration.get_subdomain', return_value=subdomain): result = self.client_post('/register/', {'email': email}) self.assertEqual(result.status_code, 302) self.assertTrue(result["Location"].endswith( "/accounts/send_confirm/%s" % (email,))) result = self.client_get(result["Location"]) self.assert_in_response("Check your email so we can get started.", result) # Visit the confirmation link. from django.core.mail import outbox for message in reversed(outbox): if email in message.to: confirmation_link_pattern = re.compile(settings.EXTERNAL_HOST + r"(\S+)>") confirmation_url = confirmation_link_pattern.search( message.body).groups()[0] break else: raise AssertionError("Couldn't find a confirmation email.") with self.settings( POPULATE_PROFILE_VIA_LDAP=True, LDAP_APPEND_DOMAIN='zulip.com', AUTH_LDAP_BIND_PASSWORD='', AUTH_LDAP_USER_ATTR_MAP=ldap_user_attr_map, AUTH_LDAP_USER_DN_TEMPLATE='uid=%(user)s,ou=users,dc=zulip,dc=com'): result = self.client_get(confirmation_url) self.assertEqual(result.status_code, 200) # Full name should be set from LDAP result = self.submit_reg_form_for_user(email, password, full_name="Ignore", from_confirmation="1", # Pass HTTP_HOST for the target subdomain HTTP_HOST=subdomain + ".testserver") self.assert_in_success_response(["You're almost there.", "New LDAP fullname", "newuser@zulip.com"], result) # Verify that the user is asked for name self.assert_in_success_response(['id_full_name'], result) # TODO: Ideally, we wouldn't ask for a password if LDAP is # enabled, in which case this assert should be invertedq. self.assert_in_success_response(['id_password'], result) # Test the TypeError exception handler mock_ldap.directory = { 'uid=newuser,ou=users,dc=zulip,dc=com': { 'userPassword': 'testing', 'fn': None # This will raise TypeError } } result = self.submit_reg_form_for_user(email, password, from_confirmation='1', # Pass HTTP_HOST for the target subdomain HTTP_HOST=subdomain + ".testserver") self.assert_in_success_response(["You're almost there.", "newuser@zulip.com"], result) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend', 'zproject.backends.ZulipDummyBackend')) def test_ldap_registration_end_to_end(self) -> None: password = "testing" email = "newuser@zulip.com" subdomain = "zulip" ldap_user_attr_map = {'full_name': 'fn', 'short_name': 'sn'} ldap_patcher = patch('django_auth_ldap.config.ldap.initialize') mock_initialize = ldap_patcher.start() mock_ldap = MockLDAP() mock_initialize.return_value = mock_ldap full_name = 'New LDAP fullname' mock_ldap.directory = { 'uid=newuser,ou=users,dc=zulip,dc=com': { 'userPassword': 'testing', 'fn': [full_name], 'sn': ['shortname'], } } with patch('zerver.views.registration.get_subdomain', return_value=subdomain): result = self.client_post('/register/', {'email': email}) self.assertEqual(result.status_code, 302) self.assertTrue(result["Location"].endswith( "/accounts/send_confirm/%s" % (email,))) result = self.client_get(result["Location"]) self.assert_in_response("Check your email so we can get started.", result) with self.settings( POPULATE_PROFILE_VIA_LDAP=True, LDAP_APPEND_DOMAIN='zulip.com', AUTH_LDAP_BIND_PASSWORD='', AUTH_LDAP_USER_ATTR_MAP=ldap_user_attr_map, AUTH_LDAP_USER_DN_TEMPLATE='uid=%(user)s,ou=users,dc=zulip,dc=com'): # Click confirmation link result = self.submit_reg_form_for_user(email, password, full_name="Ignore", from_confirmation="1", # Pass HTTP_HOST for the target subdomain HTTP_HOST=subdomain + ".testserver") # Full name should be set from LDAP self.assert_in_success_response(["You're almost there.", full_name, "newuser@zulip.com"], result) # Submit the final form with the wrong password. result = self.submit_reg_form_for_user(email, 'wrongpassword', full_name=full_name, # Pass HTTP_HOST for the target subdomain HTTP_HOST=subdomain + ".testserver") # Didn't create an account with self.assertRaises(UserProfile.DoesNotExist): user_profile = UserProfile.objects.get(email=email) self.assertEqual(result.status_code, 302) self.assertEqual(result.url, "/accounts/login/?email=newuser%40zulip.com") # Submit the final form with the wrong password. result = self.submit_reg_form_for_user(email, password, full_name=full_name, # Pass HTTP_HOST for the target subdomain HTTP_HOST=subdomain + ".testserver") user_profile = UserProfile.objects.get(email=email) # Name comes from form which was set by LDAP. self.assertEqual(user_profile.full_name, full_name) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend', 'zproject.backends.ZulipDummyBackend')) def test_ldap_auto_registration_on_login(self) -> None: """The most common way for LDAP authentication to be used is with a server that doesn't have a terms-of-service required, in which case we offer a complete single-sign-on experience (where the user just enters their LDAP username and password, and their account is created if it doesn't already exist). This test verifies that flow. """ password = "testing" email = "newuser@zulip.com" subdomain = "zulip" ldap_user_attr_map = {'full_name': 'fn', 'short_name': 'sn'} ldap_patcher = patch('django_auth_ldap.config.ldap.initialize') mock_initialize = ldap_patcher.start() mock_ldap = MockLDAP() mock_initialize.return_value = mock_ldap full_name = 'New LDAP fullname' mock_ldap.directory = { 'uid=newuser,ou=users,dc=zulip,dc=com': { 'userPassword': 'testing', 'fn': [full_name], 'sn': ['shortname'], } } with self.settings( POPULATE_PROFILE_VIA_LDAP=True, LDAP_APPEND_DOMAIN='zulip.com', AUTH_LDAP_BIND_PASSWORD='', AUTH_LDAP_USER_ATTR_MAP=ldap_user_attr_map, AUTH_LDAP_USER_DN_TEMPLATE='uid=%(user)s,ou=users,dc=zulip,dc=com'): self.login_with_return(email, password, HTTP_HOST=subdomain + ".testserver") user_profile = UserProfile.objects.get(email=email) # Name comes from form which was set by LDAP. self.assertEqual(user_profile.full_name, full_name) @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend', 'zproject.backends.ZulipDummyBackend')) def test_ldap_registration_when_names_changes_are_disabled(self) -> None: password = "testing" email = "newuser@zulip.com" subdomain = "zulip" ldap_user_attr_map = {'full_name': 'fn', 'short_name': 'sn'} ldap_patcher = patch('django_auth_ldap.config.ldap.initialize') mock_initialize = ldap_patcher.start() mock_ldap = MockLDAP() mock_initialize.return_value = mock_ldap mock_ldap.directory = { 'uid=newuser,ou=users,dc=zulip,dc=com': { 'userPassword': 'testing', 'fn': ['New LDAP fullname'], 'sn': ['New LDAP shortname'], } } with patch('zerver.views.registration.get_subdomain', return_value=subdomain): result = self.client_post('/register/', {'email': email}) self.assertEqual(result.status_code, 302) self.assertTrue(result["Location"].endswith( "/accounts/send_confirm/%s" % (email,))) result = self.client_get(result["Location"]) self.assert_in_response("Check your email so we can get started.", result) with self.settings( POPULATE_PROFILE_VIA_LDAP=True, LDAP_APPEND_DOMAIN='zulip.com', AUTH_LDAP_BIND_PASSWORD='', AUTH_LDAP_USER_ATTR_MAP=ldap_user_attr_map, AUTH_LDAP_USER_DN_TEMPLATE='uid=%(user)s,ou=users,dc=zulip,dc=com'): # Click confirmation link. This will 'authenticated_full_name' # session variable which will be used to set the fullname of # the user. result = self.submit_reg_form_for_user(email, password, full_name="Ignore", from_confirmation="1", # Pass HTTP_HOST for the target subdomain HTTP_HOST=subdomain + ".testserver") with patch('zerver.views.registration.name_changes_disabled', return_value=True): result = self.submit_reg_form_for_user(email, password, # Pass HTTP_HOST for the target subdomain HTTP_HOST=subdomain + ".testserver") user_profile = UserProfile.objects.get(email=email) # Name comes from LDAP session. self.assertEqual(user_profile.full_name, 'New LDAP fullname') @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend', 'zproject.backends.EmailAuthBackend', 'zproject.backends.ZulipDummyBackend')) def test_signup_with_ldap_and_email_enabled_using_email(self) -> None: password = "mynewpassword" email = "newuser@zulip.com" subdomain = "zulip" ldap_user_attr_map = {'full_name': 'fn', 'short_name': 'sn'} ldap_patcher = patch('django_auth_ldap.config.ldap.initialize') mock_initialize = ldap_patcher.start() mock_ldap = MockLDAP() mock_initialize.return_value = mock_ldap mock_ldap.directory = { 'uid=newuser,ou=users,dc=zulip,dc=com': { 'userPassword': 'testing', 'fn': ['New LDAP fullname'], 'sn': ['New LDAP shortname'], } } with patch('zerver.views.registration.get_subdomain', return_value=subdomain): result = self.client_post('/register/', {'email': email}) self.assertEqual(result.status_code, 302) self.assertTrue(result["Location"].endswith( "/accounts/send_confirm/%s" % (email,))) result = self.client_get(result["Location"]) self.assert_in_response("Check your email so we can get started.", result) # If the user's email is inside the LDAP domain and we just # have a wrong password, then we refuse to create an account with self.settings( POPULATE_PROFILE_VIA_LDAP=True, # Important: This doesn't match the new user LDAP_APPEND_DOMAIN='zulip.com', AUTH_LDAP_BIND_PASSWORD='', AUTH_LDAP_USER_ATTR_MAP=ldap_user_attr_map, AUTH_LDAP_USER_DN_TEMPLATE='uid=%(user)s,ou=users,dc=zulip,dc=com'): result = self.submit_reg_form_for_user( email, password, from_confirmation="1", # Pass HTTP_HOST for the target subdomain HTTP_HOST=subdomain + ".testserver") self.assertEqual(result.status_code, 200) result = self.submit_reg_form_for_user(email, password, full_name="Non-LDAP Full Name", # Pass HTTP_HOST for the target subdomain HTTP_HOST=subdomain + ".testserver") self.assertEqual(result.status_code, 302) # We get redirected back to the login page because password was wrong self.assertEqual(result.url, "/accounts/login/?email=newuser%40zulip.com") self.assertFalse(UserProfile.objects.filter(email=email).exists()) # If the user's email is outside the LDAP domain, though, we # successfully create an account with a password in the Zulip # database. with self.settings( POPULATE_PROFILE_VIA_LDAP=True, # Important: This doesn't match the new user LDAP_APPEND_DOMAIN='example.com', AUTH_LDAP_BIND_PASSWORD='', AUTH_LDAP_USER_ATTR_MAP=ldap_user_attr_map, AUTH_LDAP_USER_DN_TEMPLATE='uid=%(user)s,ou=users,dc=zulip,dc=com'): with patch('zerver.views.registration.logging.warning') as mock_warning: result = self.submit_reg_form_for_user( email, password, from_confirmation="1", # Pass HTTP_HOST for the target subdomain HTTP_HOST=subdomain + ".testserver") self.assertEqual(result.status_code, 200) mock_warning.assert_called_once_with("New account email newuser@zulip.com could not be found in LDAP") result = self.submit_reg_form_for_user(email, password, full_name="Non-LDAP Full Name", # Pass HTTP_HOST for the target subdomain HTTP_HOST=subdomain + ".testserver") self.assertEqual(result.status_code, 302) self.assertEqual(result.url, "http://zulip.testserver/") user_profile = UserProfile.objects.get(email=email) # Name comes from the POST request, not LDAP self.assertEqual(user_profile.full_name, 'Non-LDAP Full Name') def test_registration_when_name_changes_are_disabled(self) -> None: """ Test `name_changes_disabled` when we are not running under LDAP. """ password = "testing" email = "newuser@zulip.com" subdomain = "zulip" with patch('zerver.views.registration.get_subdomain', return_value=subdomain): result = self.client_post('/register/', {'email': email}) self.assertEqual(result.status_code, 302) self.assertTrue(result["Location"].endswith( "/accounts/send_confirm/%s" % (email,))) result = self.client_get(result["Location"]) self.assert_in_response("Check your email so we can get started.", result) with patch('zerver.views.registration.name_changes_disabled', return_value=True): result = self.submit_reg_form_for_user(email, password, full_name="New Name", # Pass HTTP_HOST for the target subdomain HTTP_HOST=subdomain + ".testserver") user_profile = UserProfile.objects.get(email=email) # 'New Name' comes from POST data; not from LDAP session. self.assertEqual(user_profile.full_name, 'New Name') def test_realm_creation_through_ldap(self) -> None: password = "testing" email = "newuser@zulip.com" subdomain = "zulip" realm_name = "Zulip" ldap_user_attr_map = {'full_name': 'fn', 'short_name': 'sn'} ldap_patcher = patch('django_auth_ldap.config.ldap.initialize') mock_initialize = ldap_patcher.start() mock_ldap = MockLDAP() mock_initialize.return_value = mock_ldap mock_ldap.directory = { 'uid=newuser,ou=users,dc=zulip,dc=com': { 'userPassword': 'testing', 'fn': ['New User Name'] } } with patch('zerver.views.registration.get_subdomain', return_value=subdomain): result = self.client_post('/register/', {'email': email}) self.assertEqual(result.status_code, 302) self.assertTrue(result["Location"].endswith( "/accounts/send_confirm/%s" % (email,))) result = self.client_get(result["Location"]) self.assert_in_response("Check your email so we can get started.", result) # Visit the confirmation link. from django.core.mail import outbox for message in reversed(outbox): if email in message.to: confirmation_link_pattern = re.compile(settings.EXTERNAL_HOST + r"(\S+)>") confirmation_url = confirmation_link_pattern.search( message.body).groups()[0] break else: raise AssertionError("Couldn't find a confirmation email.") with self.settings( POPULATE_PROFILE_VIA_LDAP=True, LDAP_APPEND_DOMAIN='zulip.com', AUTH_LDAP_BIND_PASSWORD='', AUTH_LDAP_USER_ATTR_MAP=ldap_user_attr_map, AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',), AUTH_LDAP_USER_DN_TEMPLATE='uid=%(user)s,ou=users,dc=zulip,dc=com', TERMS_OF_SERVICE=False, ): result = self.client_get(confirmation_url) self.assertEqual(result.status_code, 200) key = find_key_by_email(email), confirmation = Confirmation.objects.get(confirmation_key=key[0]) prereg_user = confirmation.content_object prereg_user.realm_creation = True prereg_user.save() result = self.submit_reg_form_for_user(email, password, realm_name=realm_name, realm_subdomain=subdomain, from_confirmation='1', # Pass HTTP_HOST for the target subdomain HTTP_HOST=subdomain + ".testserver") self.assert_in_success_response(["You're almost there.", "newuser@zulip.com"], result) mock_ldap.reset() mock_initialize.stop() @patch('DNS.dnslookup', return_value=[['sipbtest:*:20922:101:Fred Sipb,,,:/mit/sipbtest:/bin/athena/tcsh']]) def test_registration_of_mirror_dummy_user(self, ignored: Any) -> None: password = "test" subdomain = "zephyr" user_profile = self.mit_user("sipbtest") email = user_profile.email user_profile.is_mirror_dummy = True user_profile.is_active = False user_profile.save() result = self.client_post('/register/', {'email': email}, subdomain="zephyr") self.assertEqual(result.status_code, 302) self.assertTrue(result["Location"].endswith( "/accounts/send_confirm/%s" % (email,))) result = self.client_get(result["Location"], subdomain="zephyr") self.assert_in_response("Check your email so we can get started.", result) # Visit the confirmation link. from django.core.mail import outbox for message in reversed(outbox): if email in message.to: confirmation_link_pattern = re.compile(settings.EXTERNAL_HOST + r"(\S+)>") confirmation_url = confirmation_link_pattern.search( message.body).groups()[0] break else: raise AssertionError("Couldn't find a confirmation email.") result = self.client_get(confirmation_url, subdomain="zephyr") self.assertEqual(result.status_code, 200) # If the mirror dummy user is already active, attempting to # submit the registration form should raise an AssertionError # (this is an invalid state, so it's a bug we got here): user_profile.is_active = True user_profile.save() with self.assertRaisesRegex(AssertionError, "Mirror dummy user is already active!"): result = self.submit_reg_form_for_user( email, password, from_confirmation='1', # Pass HTTP_HOST for the target subdomain HTTP_HOST=subdomain + ".testserver") user_profile.is_active = False user_profile.save() result = self.submit_reg_form_for_user(email, password, from_confirmation='1', # Pass HTTP_HOST for the target subdomain HTTP_HOST=subdomain + ".testserver") self.assertEqual(result.status_code, 200) result = self.submit_reg_form_for_user(email, password, # Pass HTTP_HOST for the target subdomain HTTP_HOST=subdomain + ".testserver") self.assertEqual(result.status_code, 302) self.assertEqual(get_session_dict_user(self.client.session), user_profile.id) def test_registration_of_active_mirror_dummy_user(self) -> None: """ Trying to activate an already-active mirror dummy user should raise an AssertionError. """ user_profile = self.mit_user("sipbtest") email = user_profile.email user_profile.is_mirror_dummy = True user_profile.is_active = True user_profile.save() with self.assertRaisesRegex(AssertionError, "Mirror dummy user is already active!"): self.client_post('/register/', {'email': email}, subdomain="zephyr") class DeactivateUserTest(ZulipTestCase): def test_deactivate_user(self) -> None: email = self.example_email("hamlet") self.login(email) user = self.example_user('hamlet') self.assertTrue(user.is_active) result = self.client_delete('/json/users/me') self.assert_json_success(result) user = self.example_user('hamlet') self.assertFalse(user.is_active) self.login(email, fails=True) def test_do_not_deactivate_final_admin(self) -> None: email = self.example_email("iago") self.login(email) user = self.example_user('iago') self.assertTrue(user.is_active) result = self.client_delete('/json/users/me') self.assert_json_error(result, "Cannot deactivate the only organization administrator") user = self.example_user('iago') self.assertTrue(user.is_active) self.assertTrue(user.is_realm_admin) email = self.example_email("hamlet") user_2 = self.example_user('hamlet') do_change_is_admin(user_2, True) self.assertTrue(user_2.is_realm_admin) result = self.client_delete('/json/users/me') self.assert_json_success(result) do_change_is_admin(user, True) class TestLoginPage(ZulipTestCase): def test_login_page_wrong_subdomain_error(self) -> None: result = self.client_get("/login/?subdomain=1") self.assertIn(WRONG_SUBDOMAIN_ERROR, result.content.decode('utf8')) @patch('django.http.HttpRequest.get_host') def test_login_page_redirects_for_root_alias(self, mock_get_host: MagicMock) -> None: mock_get_host.return_value = 'www.testserver' with self.settings(ROOT_DOMAIN_LANDING_PAGE=True): result = self.client_get("/en/login/") self.assertEqual(result.status_code, 302) self.assertEqual(result.url, '/accounts/find/') @patch('django.http.HttpRequest.get_host') def test_login_page_redirects_for_root_domain(self, mock_get_host: MagicMock) -> None: mock_get_host.return_value = 'testserver' with self.settings(ROOT_DOMAIN_LANDING_PAGE=True): result = self.client_get("/en/login/") self.assertEqual(result.status_code, 302) self.assertEqual(result.url, '/accounts/find/') mock_get_host.return_value = 'www.testserver.com' with self.settings(ROOT_DOMAIN_LANDING_PAGE=True, EXTERNAL_HOST='www.testserver.com', ROOT_SUBDOMAIN_ALIASES=['test']): result = self.client_get("/en/login/") self.assertEqual(result.status_code, 302) self.assertEqual(result.url, '/accounts/find/') @patch('django.http.HttpRequest.get_host') def test_login_page_works_without_subdomains(self, mock_get_host: MagicMock) -> None: mock_get_host.return_value = 'www.testserver' with self.settings(ROOT_SUBDOMAIN_ALIASES=['www']): result = self.client_get("/en/login/") self.assertEqual(result.status_code, 200) mock_get_host.return_value = 'testserver' with self.settings(ROOT_SUBDOMAIN_ALIASES=['www']): result = self.client_get("/en/login/") self.assertEqual(result.status_code, 200) class TestFindMyTeam(ZulipTestCase): def test_template(self) -> None: result = self.client_get('/accounts/find/') self.assertIn("Find your Zulip accounts", result.content.decode('utf8')) def test_result(self) -> None: result = self.client_post('/accounts/find/', dict(emails="iago@zulip.com,cordelia@zulip.com")) self.assertEqual(result.status_code, 302) self.assertEqual(result.url, "/accounts/find/?emails=iago%40zulip.com%2Ccordelia%40zulip.com") result = self.client_get(result.url) content = result.content.decode('utf8') self.assertIn("Emails sent! You will only receive emails", content) self.assertIn(self.example_email("iago"), content) self.assertIn(self.example_email("cordelia"), content) from django.core.mail import outbox # 3 = 1 + 2 -- Cordelia gets an email each for the "zulip" and "lear" realms. self.assertEqual(len(outbox), 3) def test_find_team_ignore_invalid_email(self) -> None: result = self.client_post('/accounts/find/', dict(emails="iago@zulip.com,invalid_email@zulip.com")) self.assertEqual(result.status_code, 302) self.assertEqual(result.url, "/accounts/find/?emails=iago%40zulip.com%2Cinvalid_email%40zulip.com") result = self.client_get(result.url) content = result.content.decode('utf8') self.assertIn("Emails sent! You will only receive emails", content) self.assertIn(self.example_email("iago"), content) self.assertIn("invalid_email@", content) from django.core.mail import outbox self.assertEqual(len(outbox), 1) def test_find_team_reject_invalid_email(self) -> None: result = self.client_post('/accounts/find/', dict(emails="invalid_string")) self.assertEqual(result.status_code, 200) self.assertIn(b"Enter a valid email", result.content) from django.core.mail import outbox self.assertEqual(len(outbox), 0) # Just for coverage on perhaps-unnecessary validation code. result = self.client_get('/accounts/find/?emails=invalid') self.assertEqual(result.status_code, 200) def test_find_team_zero_emails(self) -> None: data = {'emails': ''} result = self.client_post('/accounts/find/', data) self.assertIn('This field is required', result.content.decode('utf8')) self.assertEqual(result.status_code, 200) from django.core.mail import outbox self.assertEqual(len(outbox), 0) def test_find_team_one_email(self) -> None: data = {'emails': self.example_email("hamlet")} result = self.client_post('/accounts/find/', data) self.assertEqual(result.status_code, 302) self.assertEqual(result.url, '/accounts/find/?emails=hamlet%40zulip.com') from django.core.mail import outbox self.assertEqual(len(outbox), 1) def test_find_team_deactivated_user(self) -> None: do_deactivate_user(self.example_user("hamlet")) data = {'emails': self.example_email("hamlet")} result = self.client_post('/accounts/find/', data) self.assertEqual(result.status_code, 302) self.assertEqual(result.url, '/accounts/find/?emails=hamlet%40zulip.com') from django.core.mail import outbox self.assertEqual(len(outbox), 0) def test_find_team_deactivated_realm(self) -> None: do_deactivate_realm(get_realm("zulip")) data = {'emails': self.example_email("hamlet")} result = self.client_post('/accounts/find/', data) self.assertEqual(result.status_code, 302) self.assertEqual(result.url, '/accounts/find/?emails=hamlet%40zulip.com') from django.core.mail import outbox self.assertEqual(len(outbox), 0) def test_find_team_bot_email(self) -> None: data = {'emails': self.example_email("webhook_bot")} result = self.client_post('/accounts/find/', data) self.assertEqual(result.status_code, 302) self.assertEqual(result.url, '/accounts/find/?emails=webhook-bot%40zulip.com') from django.core.mail import outbox self.assertEqual(len(outbox), 0) def test_find_team_more_than_ten_emails(self) -> None: data = {'emails': ','.join(['hamlet-{}@zulip.com'.format(i) for i in range(11)])} result = self.client_post('/accounts/find/', data) self.assertEqual(result.status_code, 200) self.assertIn("Please enter at most 10", result.content.decode('utf8')) from django.core.mail import outbox self.assertEqual(len(outbox), 0) class ConfirmationKeyTest(ZulipTestCase): def test_confirmation_key(self) -> None: request = MagicMock() request.session = { 'confirmation_key': {'confirmation_key': 'xyzzy'} } result = confirmation_key(request) self.assert_json_success(result) self.assert_in_response('xyzzy', result) class MobileAuthOTPTest(ZulipTestCase): def test_xor_hex_strings(self) -> None: self.assertEqual(xor_hex_strings('1237c81ab', '18989fd12'), '0aaf57cb9') with self.assertRaises(AssertionError): xor_hex_strings('1', '31') def test_is_valid_otp(self) -> None: self.assertEqual(is_valid_otp('1234'), False) self.assertEqual(is_valid_otp('1234abcd' * 8), True) self.assertEqual(is_valid_otp('1234abcZ' * 8), False) def test_ascii_to_hex(self) -> None: self.assertEqual(ascii_to_hex('ZcdR1234'), '5a63645231323334') self.assertEqual(hex_to_ascii('5a63645231323334'), 'ZcdR1234') def test_otp_encrypt_api_key(self) -> None: api_key = '12ac' * 8 otp = '7be38894' * 8 result = otp_encrypt_api_key(api_key, otp) self.assertEqual(result, '4ad1e9f7' * 8) decryped = otp_decrypt_api_key(result, otp) self.assertEqual(decryped, api_key) class FollowupEmailTest(ZulipTestCase): def test_followup_day2_email(self) -> None: user_profile = self.example_user('hamlet') # Test date_joined == Sunday user_profile.date_joined = datetime.datetime(2018, 1, 7, 1, 0, 0, 0, pytz.UTC) self.assertEqual(followup_day2_email_delay(user_profile), datetime.timedelta(days=2, hours=-1)) # Test date_joined == Tuesday user_profile.date_joined = datetime.datetime(2018, 1, 2, 1, 0, 0, 0, pytz.UTC) self.assertEqual(followup_day2_email_delay(user_profile), datetime.timedelta(days=2, hours=-1)) # Test date_joined == Thursday user_profile.date_joined = datetime.datetime(2018, 1, 4, 1, 0, 0, 0, pytz.UTC) self.assertEqual(followup_day2_email_delay(user_profile), datetime.timedelta(days=1, hours=-1)) # Test date_joined == Friday user_profile.date_joined = datetime.datetime(2018, 1, 5, 1, 0, 0, 0, pytz.UTC) self.assertEqual(followup_day2_email_delay(user_profile), datetime.timedelta(days=3, hours=-1)) # Time offset of America/Phoenix is -07:00 user_profile.timezone = 'America/Phoenix' # Test date_joined == Friday in UTC, but Thursday in the user's timezone user_profile.date_joined = datetime.datetime(2018, 1, 5, 1, 0, 0, 0, pytz.UTC) self.assertEqual(followup_day2_email_delay(user_profile), datetime.timedelta(days=1, hours=-1)) class NoReplyEmailTest(ZulipTestCase): def test_noreply_email_address(self) -> None: self.assertTrue(re.search(self.TOKENIZED_NOREPLY_REGEX, FromAddress.tokenized_no_reply_address())) with self.settings(ADD_TOKENS_TO_NOREPLY_ADDRESS=False): self.assertEqual(FromAddress.tokenized_no_reply_address(), "noreply@testserver") class TwoFactorAuthTest(ZulipTestCase): @patch('two_factor.models.totp') def test_two_factor_login(self, mock_totp): # type: (MagicMock) -> None token = 123456 email = self.example_email('hamlet') password = 'testing' user_profile = self.example_user('hamlet') user_profile.set_password(password) user_profile.save() self.create_default_device(user_profile) def totp(*args, **kwargs): # type: (*Any, **Any) -> int return token mock_totp.side_effect = totp with self.settings(AUTHENTICATION_BACKENDS=('zproject.backends.EmailAuthBackend',), TWO_FACTOR_CALL_GATEWAY='two_factor.gateways.fake.Fake', TWO_FACTOR_SMS_GATEWAY='two_factor.gateways.fake.Fake', TWO_FACTOR_AUTHENTICATION_ENABLED=True): first_step_data = {"username": email, "password": password, "two_factor_login_view-current_step": "auth"} result = self.client_post("/accounts/login/", first_step_data) self.assertEqual(result.status_code, 200) second_step_data = {"token-otp_token": str(token), "two_factor_login_view-current_step": "token"} result = self.client_post("/accounts/login/", second_step_data) self.assertEqual(result.status_code, 302) self.assertEqual(result["Location"], "http://zulip.testserver") # Going to login page should redirect to '/' if user is already # logged in. result = self.client_get('/accounts/login/') self.assertEqual(result["Location"], "http://zulip.testserver") class NameRestrictionsTest(ZulipTestCase): def test_whitelisted_disposable_domains(self) -> None: self.assertFalse(is_disposable_domain('OPayQ.com'))
[ "List[str]", "str", "List[str]", "str", "str", "str", "HttpResponse", "str", "Any", "Any", "MagicMock", "MagicMock", "MagicMock" ]
[ 26450, 27138, 27152, 60739, 60757, 70957, 81788, 81807, 100579, 126484, 131420, 131837, 132655 ]
[ 26459, 27141, 27161, 60742, 60760, 70960, 81800, 81810, 100582, 126487, 131429, 131846, 132664 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_slack_importer.py
# -*- coding: utf-8 -*- from django.conf import settings from django.utils.timezone import now as timezone_now from zerver.data_import.slack import ( rm_tree, get_slack_api_data, get_user_email, build_avatar_url, build_avatar, get_admin, get_user_timezone, users_to_zerver_userprofile, get_subscription, channels_to_zerver_stream, slack_workspace_to_realm, get_message_sending_user, channel_message_to_zerver_message, convert_slack_workspace_messages, do_convert_data, process_avatars, process_message_files, ) from zerver.data_import.import_util import ( build_zerver_realm, build_subscription, build_recipient, build_usermessages, build_defaultstream, ) from zerver.data_import.sequencer import ( NEXT_ID, ) from zerver.lib.import_realm import ( do_import_realm, ) from zerver.lib.avatar_hash import ( user_avatar_path_from_ids, ) from zerver.lib.test_classes import ( ZulipTestCase, ) from zerver.lib.topic import ( EXPORT_TOPIC_NAME, ) from zerver.models import ( Realm, get_realm, RealmAuditLog, Recipient, ) from zerver.lib import mdiff import ujson import json import logging import shutil import requests import os import mock from typing import Any, AnyStr, Dict, List, Optional, Set, Tuple def remove_folder(path: str) -> None: if os.path.exists(path): shutil.rmtree(path) # This method will be used by the mock to replace requests.get def mocked_requests_get(*args: List[str], **kwargs: List[str]) -> mock.Mock: class MockResponse: def __init__(self, json_data: Dict[str, Any], status_code: int) -> None: self.json_data = json_data self.status_code = status_code def json(self) -> Dict[str, Any]: return self.json_data if args[0] == 'https://slack.com/api/users.list?token=valid-token': return MockResponse({"members": "user_data"}, 200) elif args[0] == 'https://slack.com/api/users.list?token=invalid-token': return MockResponse({"ok": False, "error": "invalid_auth"}, 200) else: return MockResponse(None, 404) class SlackImporter(ZulipTestCase): logger = logging.getLogger() # set logger to a higher level to suppress 'logger.INFO' outputs logger.setLevel(logging.WARNING) @mock.patch('requests.get', side_effect=mocked_requests_get) def test_get_slack_api_data(self, mock_get: mock.Mock) -> None: token = 'valid-token' slack_user_list_url = "https://slack.com/api/users.list" self.assertEqual(get_slack_api_data(token, slack_user_list_url, "members"), "user_data") token = 'invalid-token' with self.assertRaises(Exception) as invalid: get_slack_api_data(token, slack_user_list_url, "members") self.assertEqual(invalid.exception.args, ('Enter a valid token!',),) token = 'status404' wrong_url = "https://slack.com/api/wrong" with self.assertRaises(Exception) as invalid: get_slack_api_data(token, wrong_url, "members") self.assertEqual(invalid.exception.args, ('Something went wrong. Please try again!',),) def test_build_zerver_realm(self) -> None: realm_id = 2 realm_subdomain = "test-realm" time = float(timezone_now().timestamp()) test_realm = build_zerver_realm(realm_id, realm_subdomain, time, 'Slack') # type: List[Dict[str, Any]] test_zerver_realm_dict = test_realm[0] self.assertEqual(test_zerver_realm_dict['id'], realm_id) self.assertEqual(test_zerver_realm_dict['string_id'], realm_subdomain) self.assertEqual(test_zerver_realm_dict['name'], realm_subdomain) self.assertEqual(test_zerver_realm_dict['date_created'], time) def test_get_admin(self) -> None: user_data = [{'is_admin': True, 'is_owner': False, 'is_primary_owner': False}, {'is_admin': True, 'is_owner': True, 'is_primary_owner': False}, {'is_admin': True, 'is_owner': True, 'is_primary_owner': True}, {'is_admin': False, 'is_owner': False, 'is_primary_owner': False}] self.assertEqual(get_admin(user_data[0]), True) self.assertEqual(get_admin(user_data[1]), True) self.assertEqual(get_admin(user_data[2]), True) self.assertEqual(get_admin(user_data[3]), False) def test_get_timezone(self) -> None: user_chicago_timezone = {"tz": "America/Chicago"} user_timezone_none = {"tz": None} user_no_timezone = {} # type: Dict[str, Any] self.assertEqual(get_user_timezone(user_chicago_timezone), "America/Chicago") self.assertEqual(get_user_timezone(user_timezone_none), "America/New_York") self.assertEqual(get_user_timezone(user_no_timezone), "America/New_York") @mock.patch("zerver.data_import.slack.get_data_file") def test_users_to_zerver_userprofile(self, mock_get_data_file: mock.Mock) -> None: custom_profile_field_user1 = {"Xf06054BBB": {"value": "random1"}, "Xf023DSCdd": {"value": "employee"}} custom_profile_field_user2 = {"Xf06054BBB": {"value": "random2"}, "Xf023DSCdd": {"value": "employer"}} user_data = [{"id": "U08RGD1RD", "team_id": "T5YFFM2QY", "name": "john", "deleted": False, "real_name": "John Doe", "profile": {"image_32": "", "email": "jon@gmail.com", "avatar_hash": "hash", "phone": "+1-123-456-77-868", "fields": custom_profile_field_user1}}, {"id": "U0CBK5KAT", "team_id": "T5YFFM2QY", "is_admin": True, "is_bot": False, "is_owner": True, "is_primary_owner": True, 'name': 'Jane', "real_name": "Jane Doe", "deleted": False, "profile": {"image_32": "https://secure.gravatar.com/avatar/random.png", "fields": custom_profile_field_user2, "email": "jane@foo.com", "avatar_hash": "hash"}}, {"id": "U09TYF5Sk", "team_id": "T5YFFM2QY", "name": "Bot", "real_name": "Bot", "is_bot": True, "deleted": False, "profile": {"image_32": "https://secure.gravatar.com/avatar/random1.png", "skype": "test_skype_name", "email": "bot1@zulipchat.com", "avatar_hash": "hash"}}] mock_get_data_file.return_value = user_data # As user with slack_id 'U0CBK5KAT' is the primary owner, that user should be imported first # and hence has zulip_id = 1 test_added_users = {'U08RGD1RD': 1, 'U0CBK5KAT': 0, 'U09TYF5Sk': 2} slack_data_dir = './random_path' timestamp = int(timezone_now().timestamp()) mock_get_data_file.return_value = user_data zerver_userprofile, avatar_list, added_users, customprofilefield, \ customprofilefield_value = users_to_zerver_userprofile(slack_data_dir, user_data, 1, timestamp, 'test_domain') # Test custom profile fields self.assertEqual(customprofilefield[0]['field_type'], 1) self.assertEqual(customprofilefield[3]['name'], 'skype') cpf_name = {cpf['name'] for cpf in customprofilefield} self.assertIn('phone', cpf_name) self.assertIn('skype', cpf_name) cpf_name.remove('phone') cpf_name.remove('skype') for name in cpf_name: self.assertTrue(name.startswith('slack custom field ')) self.assertEqual(len(customprofilefield_value), 6) self.assertEqual(customprofilefield_value[0]['field'], 0) self.assertEqual(customprofilefield_value[0]['user_profile'], 1) self.assertEqual(customprofilefield_value[3]['user_profile'], 0) self.assertEqual(customprofilefield_value[5]['value'], 'test_skype_name') # test that the primary owner should always be imported first self.assertDictEqual(added_users, test_added_users) self.assertEqual(len(avatar_list), 3) self.assertEqual(zerver_userprofile[1]['id'], test_added_users['U0CBK5KAT']) self.assertEqual(len(zerver_userprofile), 3) self.assertEqual(zerver_userprofile[1]['id'], 0) self.assertEqual(zerver_userprofile[1]['is_realm_admin'], True) self.assertEqual(zerver_userprofile[1]['is_staff'], False) self.assertEqual(zerver_userprofile[1]['is_active'], True) self.assertEqual(zerver_userprofile[0]['is_staff'], False) self.assertEqual(zerver_userprofile[0]['is_bot'], False) self.assertEqual(zerver_userprofile[0]['enable_desktop_notifications'], True) self.assertEqual(zerver_userprofile[2]['bot_type'], 1) self.assertEqual(zerver_userprofile[2]['avatar_source'], 'U') def test_build_defaultstream(self) -> None: realm_id = 1 stream_id = 1 default_channel_general = build_defaultstream(realm_id, stream_id, 1) test_default_channel = {'stream': 1, 'realm': 1, 'id': 1} self.assertDictEqual(test_default_channel, default_channel_general) default_channel_general = build_defaultstream(realm_id, stream_id, 1) test_default_channel = {'stream': 1, 'realm': 1, 'id': 1} self.assertDictEqual(test_default_channel, default_channel_general) def test_build_pm_recipient_sub_from_user(self) -> None: zulip_user_id = 3 recipient_id = 5 subscription_id = 7 sub = build_subscription(recipient_id, zulip_user_id, subscription_id) recipient = build_recipient(zulip_user_id, recipient_id, Recipient.PERSONAL) self.assertEqual(recipient['id'], sub['recipient']) self.assertEqual(recipient['type_id'], sub['user_profile']) self.assertEqual(recipient['type'], Recipient.PERSONAL) self.assertEqual(recipient['type_id'], 3) self.assertEqual(sub['recipient'], 5) self.assertEqual(sub['id'], 7) self.assertEqual(sub['active'], True) def test_build_subscription(self) -> None: channel_members = ["U061A1R2R", "U061A3E0G", "U061A5N1G", "U064KUGRJ"] added_users = {"U061A1R2R": 1, "U061A3E0G": 8, "U061A5N1G": 7, "U064KUGRJ": 5} subscription_id_count = 0 recipient_id = 12 zerver_subscription = [] # type: List[Dict[str, Any]] final_subscription_id = get_subscription(channel_members, zerver_subscription, recipient_id, added_users, subscription_id_count) # sanity checks self.assertEqual(final_subscription_id, 4) self.assertEqual(zerver_subscription[0]['recipient'], 12) self.assertEqual(zerver_subscription[0]['id'], 0) self.assertEqual(zerver_subscription[0]['user_profile'], added_users[channel_members[0]]) self.assertEqual(zerver_subscription[2]['user_profile'], added_users[channel_members[2]]) self.assertEqual(zerver_subscription[3]['id'], 3) self.assertEqual(zerver_subscription[1]['recipient'], zerver_subscription[3]['recipient']) self.assertEqual(zerver_subscription[1]['pin_to_top'], False) @mock.patch("zerver.data_import.slack.get_data_file") def test_channels_to_zerver_stream(self, mock_get_data_file: mock.Mock) -> None: added_users = {"U061A1R2R": 1, "U061A3E0G": 8, "U061A5N1G": 7, "U064KUGRJ": 5} zerver_userprofile = [{'id': 1}, {'id': 8}, {'id': 7}, {'id': 5}] realm_id = 3 channel_data = [{'id': "C061A0WJG", 'name': 'random', 'created': '1433558319', 'is_general': False, 'members': ['U061A1R2R', 'U061A5N1G'], 'is_archived': True, 'topic': {'value': 'random'}, 'purpose': {'value': 'no purpose'}}, {'id': "C061A0YJG", 'name': 'general', 'created': '1433559319', 'is_general': False, 'is_archived': False, 'members': ['U061A1R2R', 'U061A5N1G', 'U064KUGRJ'], 'topic': {'value': 'general'}, 'purpose': {'value': 'general'}}, {'id': "C061A0YJP", 'name': 'general1', 'created': '1433559319', 'is_general': False, 'is_archived': False, 'members': ['U061A1R2R'], 'topic': {'value': 'general channel'}, 'purpose': {'value': 'For everyone'}}, {'id': "C061A0HJG", 'name': 'feedback', 'created': '1433558359', 'is_general': False, 'members': ['U061A3E0G'], 'is_archived': False, 'topic': {'value': ''}, 'purpose': {'value': ''}}] mock_get_data_file.return_value = channel_data channel_to_zerver_stream_output = channels_to_zerver_stream('./random_path', realm_id, added_users, zerver_userprofile) zerver_defaultstream = channel_to_zerver_stream_output[0] zerver_stream = channel_to_zerver_stream_output[1] added_channels = channel_to_zerver_stream_output[2] zerver_subscription = channel_to_zerver_stream_output[3] zerver_recipient = channel_to_zerver_stream_output[4] added_recipient = channel_to_zerver_stream_output[5] test_added_channels = {'feedback': ("C061A0HJG", 3), 'general': ("C061A0YJG", 1), 'general1': ("C061A0YJP", 2), 'random': ("C061A0WJG", 0)} test_added_recipient = {'feedback': 3, 'general': 1, 'general1': 2, 'random': 0} # zerver defaultstream already tested in helper functions self.assertEqual(zerver_defaultstream, [{'id': 0, 'realm': 3, 'stream': 0}, {'id': 1, 'realm': 3, 'stream': 1}]) self.assertDictEqual(test_added_channels, added_channels) self.assertDictEqual(test_added_recipient, added_recipient) # functioning of zerver subscriptions are already tested in the helper functions # This is to check the concatenation of the output lists from the helper functions # subscriptions for stream self.assertEqual(zerver_subscription[3]['recipient'], 1) self.assertEqual(zerver_subscription[5]['recipient'], 2) # subscription for users self.assertEqual(zerver_subscription[6]['recipient'], 3) self.assertEqual(zerver_subscription[7]['user_profile'], 1) # recipients for stream self.assertEqual(zerver_recipient[1]['id'], zerver_subscription[3]['recipient']) self.assertEqual(zerver_recipient[2]['type_id'], zerver_stream[2]['id']) self.assertEqual(zerver_recipient[0]['type'], 2) # recipients for users (already tested in helped function) self.assertEqual(zerver_recipient[3]['type'], 2) self.assertEqual(zerver_recipient[4]['type'], 1) # stream mapping self.assertEqual(zerver_stream[0]['name'], channel_data[0]['name']) self.assertEqual(zerver_stream[0]['deactivated'], channel_data[0]['is_archived']) self.assertEqual(zerver_stream[0]['description'], 'no purpose') self.assertEqual(zerver_stream[0]['invite_only'], False) self.assertEqual(zerver_stream[0]['realm'], realm_id) self.assertEqual(zerver_stream[2]['id'], test_added_channels[zerver_stream[2]['name']][1]) @mock.patch("zerver.data_import.slack.users_to_zerver_userprofile", return_value=[[], [], {}, [], []]) @mock.patch("zerver.data_import.slack.channels_to_zerver_stream", return_value=[[], [], {}, [], [], {}]) def test_slack_workspace_to_realm(self, mock_channels_to_zerver_stream: mock.Mock, mock_users_to_zerver_userprofile: mock.Mock) -> None: realm_id = 1 user_list = [] # type: List[Dict[str, Any]] realm, added_users, added_recipient, added_channels, avatar_list, em = slack_workspace_to_realm( 'testdomain', realm_id, user_list, 'test-realm', './random_path', {}) test_zerver_realmdomain = [{'realm': realm_id, 'allow_subdomains': False, 'domain': 'testdomain', 'id': realm_id}] # Functioning already tests in helper functions self.assertEqual(added_users, {}) self.assertEqual(added_channels, {}) self.assertEqual(added_recipient, {}) self.assertEqual(avatar_list, []) zerver_realmdomain = realm['zerver_realmdomain'] self.assertListEqual(zerver_realmdomain, test_zerver_realmdomain) self.assertEqual(realm['zerver_userpresence'], []) self.assertEqual(realm['zerver_stream'], []) self.assertEqual(realm['zerver_userprofile'], []) self.assertEqual(realm['zerver_realm'][0]['description'], 'Organization imported from Slack!') def test_get_message_sending_user(self) -> None: message_with_file = {'subtype': 'file', 'type': 'message', 'file': {'user': 'U064KUGRJ'}} message_without_file = {'subtype': 'file', 'type': 'messge', 'user': 'U064KUGRJ'} user_file = get_message_sending_user(message_with_file) self.assertEqual(user_file, 'U064KUGRJ') user_without_file = get_message_sending_user(message_without_file) self.assertEqual(user_without_file, 'U064KUGRJ') def test_build_zerver_message(self) -> None: zerver_usermessage = [] # type: List[Dict[str, Any]] # recipient_id -> set of user_ids subscriber_map = { 2: {3, 7, 15, 16}, # these we care about 4: {12}, 6: {19, 21}, } recipient_id = 2 mentioned_user_ids = [7] message_id = 9 um_id = NEXT_ID('user_message') build_usermessages( zerver_usermessage=zerver_usermessage, subscriber_map=subscriber_map, recipient_id=recipient_id, mentioned_user_ids=mentioned_user_ids, message_id=message_id, ) self.assertEqual(zerver_usermessage[0]['id'], um_id + 1) self.assertEqual(zerver_usermessage[0]['message'], message_id) self.assertEqual(zerver_usermessage[0]['flags_mask'], 1) self.assertEqual(zerver_usermessage[1]['id'], um_id + 2) self.assertEqual(zerver_usermessage[1]['message'], message_id) self.assertEqual(zerver_usermessage[1]['user_profile'], 7) self.assertEqual(zerver_usermessage[1]['flags_mask'], 9) # mentioned self.assertEqual(zerver_usermessage[2]['id'], um_id + 3) self.assertEqual(zerver_usermessage[2]['message'], message_id) self.assertEqual(zerver_usermessage[3]['id'], um_id + 4) self.assertEqual(zerver_usermessage[3]['message'], message_id) @mock.patch("zerver.data_import.slack.build_usermessages", return_value = 2) def test_channel_message_to_zerver_message(self, mock_build_usermessage: mock.Mock) -> None: user_data = [{"id": "U066MTL5U", "name": "john doe", "deleted": False, "real_name": "John"}, {"id": "U061A5N1G", "name": "jane doe", "deleted": False, "real_name": "Jane"}, {"id": "U061A1R2R", "name": "jon", "deleted": False, "real_name": "Jon"}] added_users = {"U066MTL5U": 5, "U061A5N1G": 24, "U061A1R2R": 43} reactions = [{"name": "grinning", "users": ["U061A5N1G"], "count": 1}] all_messages = [{"text": "<@U066MTL5U> has joined the channel", "subtype": "channel_join", "user": "U066MTL5U", "ts": "1434139102.000002", "channel_name": "random"}, {"text": "<@U061A5N1G>: hey!", "user": "U061A1R2R", "ts": "1437868294.000006", "has_image": True, "channel_name": "random"}, {"text": "random", "user": "U061A5N1G", "reactions": reactions, "ts": "1439868294.000006", "channel_name": "random"}, {"text": "without a user", "user": None, # this message will be ignored as it has no user "ts": "1239868294.000006", "channel_name": "general"}, {"text": "<http://journals.plos.org/plosone/article>", "user": "U061A1R2R", "ts": "1463868370.000008", "channel_name": "general"}, {"text": "added bot", "user": "U061A5N1G", "subtype": "bot_add", "ts": "1433868549.000010", "channel_name": "general"}, # This message will be ignored since it has no user and file is None. # See #9217 for the situation; likely file uploads on archived channels {'upload': False, 'file': None, 'text': 'A file was shared', 'channel_name': 'general', 'type': 'message', 'ts': '1433868549.000011', 'subtype': 'file_share'}, {"text": "random test", "user": "U061A1R2R", "ts": "1433868669.000012", "channel_name": "general"}] # type: List[Dict[str, Any]] added_recipient = {'random': 2, 'general': 1} zerver_usermessage = [] # type: List[Dict[str, Any]] subscriber_map = dict() # type: Dict[int, Set[int]] added_channels = {'random': ('c5', 1), 'general': ('c6', 2)} # type: Dict[str, Tuple[str, int]] zerver_message, zerver_usermessage, attachment, uploads, reaction = \ channel_message_to_zerver_message( 1, user_data, added_users, added_recipient, all_messages, [], subscriber_map, added_channels, 'domain') # functioning already tested in helper function self.assertEqual(zerver_usermessage, []) # subtype: channel_join is filtered self.assertEqual(len(zerver_message), 5) self.assertEqual(uploads, []) self.assertEqual(attachment, []) # Test reactions self.assertEqual(reaction[0]['user_profile'], 24) self.assertEqual(reaction[0]['emoji_name'], reactions[0]['name']) # Message conversion already tested in tests.test_slack_message_conversion self.assertEqual(zerver_message[0]['content'], '@**Jane**: hey!') self.assertEqual(zerver_message[0]['has_link'], False) self.assertEqual(zerver_message[2]['content'], 'http://journals.plos.org/plosone/article') self.assertEqual(zerver_message[2]['has_link'], True) self.assertEqual(zerver_message[3][EXPORT_TOPIC_NAME], 'imported from slack') self.assertEqual(zerver_message[3]['content'], '/me added bot') self.assertEqual(zerver_message[4]['recipient'], added_recipient['general']) self.assertEqual(zerver_message[2][EXPORT_TOPIC_NAME], 'imported from slack') self.assertEqual(zerver_message[1]['recipient'], added_recipient['random']) self.assertEqual(zerver_message[3]['id'], zerver_message[0]['id'] + 3) self.assertEqual(zerver_message[4]['id'], zerver_message[0]['id'] + 4) self.assertIsNone(zerver_message[3]['rendered_content']) self.assertEqual(zerver_message[0]['has_image'], False) self.assertEqual(zerver_message[0]['pub_date'], float(all_messages[1]['ts'])) self.assertEqual(zerver_message[2]['rendered_content_version'], 1) self.assertEqual(zerver_message[0]['sender'], 43) self.assertEqual(zerver_message[3]['sender'], 24) @mock.patch("zerver.data_import.slack.channel_message_to_zerver_message") @mock.patch("zerver.data_import.slack.get_all_messages") def test_convert_slack_workspace_messages(self, mock_get_all_messages: mock.Mock, mock_message: mock.Mock) -> None: os.makedirs('var/test-slack-import', exist_ok=True) added_channels = {'random': ('c5', 1), 'general': ('c6', 2)} # type: Dict[str, Tuple[str, int]] time = float(timezone_now().timestamp()) zerver_message = [{'id': 1, 'ts': time}, {'id': 5, 'ts': time}] realm = {'zerver_subscription': []} # type: Dict[str, Any] user_list = [] # type: List[Dict[str, Any]] reactions = [{"name": "grinning", "users": ["U061A5N1G"], "count": 1}] attachments = uploads = [] # type: List[Dict[str, Any]] zerver_usermessage = [{'id': 3}, {'id': 5}, {'id': 6}, {'id': 9}] mock_get_all_messages.side_effect = [zerver_message] mock_message.side_effect = [[zerver_message[:1], zerver_usermessage[:2], attachments, uploads, reactions[:1]], [zerver_message[1:2], zerver_usermessage[2:5], attachments, uploads, reactions[1:1]]] test_reactions, uploads, zerver_attachment = convert_slack_workspace_messages( './random_path', user_list, 2, {}, {}, added_channels, realm, [], 'domain', 'var/test-slack-import', chunk_size=1) messages_file_1 = os.path.join('var', 'test-slack-import', 'messages-000001.json') self.assertTrue(os.path.exists(messages_file_1)) messages_file_2 = os.path.join('var', 'test-slack-import', 'messages-000002.json') self.assertTrue(os.path.exists(messages_file_2)) with open(messages_file_1) as f: message_json = ujson.load(f) self.assertEqual(message_json['zerver_message'], zerver_message[:1]) self.assertEqual(message_json['zerver_usermessage'], zerver_usermessage[:2]) with open(messages_file_2) as f: message_json = ujson.load(f) self.assertEqual(message_json['zerver_message'], zerver_message[1:2]) self.assertEqual(message_json['zerver_usermessage'], zerver_usermessage[2:5]) self.assertEqual(test_reactions, reactions) @mock.patch("zerver.data_import.slack.process_uploads", return_value = []) @mock.patch("zerver.data_import.slack.build_attachment", return_value = []) @mock.patch("zerver.data_import.slack.build_avatar_url") @mock.patch("zerver.data_import.slack.build_avatar") @mock.patch("zerver.data_import.slack.get_slack_api_data") def test_slack_import_to_existing_database(self, mock_get_slack_api_data: mock.Mock, mock_build_avatar_url: mock.Mock, mock_build_avatar: mock.Mock, mock_process_uploads: mock.Mock, mock_attachment: mock.Mock) -> None: test_slack_dir = os.path.join(settings.DEPLOY_ROOT, "zerver", "tests", "fixtures", "slack_fixtures") test_slack_zip_file = os.path.join(test_slack_dir, "test_slack_importer.zip") test_slack_unzipped_file = os.path.join(test_slack_dir, "test_slack_importer") test_realm_subdomain = 'test-slack-import' output_dir = os.path.join(settings.DEPLOY_ROOT, "var", "test-slack-importer-data") token = 'valid-token' # If the test fails, the 'output_dir' would not be deleted and hence it would give an # error when we run the tests next time, as 'do_convert_data' expects an empty 'output_dir' # hence we remove it before running 'do_convert_data' rm_tree(output_dir) # Also the unzipped data file should be removed if the test fails at 'do_convert_data' rm_tree(test_slack_unzipped_file) user_data_fixture = ujson.loads(self.fixture_data('user_data.json', type='slack_fixtures')) mock_get_slack_api_data.side_effect = [user_data_fixture['members'], {}] do_convert_data(test_slack_zip_file, output_dir, token) self.assertTrue(os.path.exists(output_dir)) self.assertTrue(os.path.exists(output_dir + '/realm.json')) # test import of the converted slack data into an existing database do_import_realm(output_dir, test_realm_subdomain) realm = get_realm(test_realm_subdomain) self.assertTrue(realm.name, test_realm_subdomain) # test RealmAuditLog realmauditlog = RealmAuditLog.objects.filter(realm=realm) realmauditlog_event_type = {log.event_type for log in realmauditlog} self.assertEqual(realmauditlog_event_type, {'subscription_created'}) Realm.objects.filter(name=test_realm_subdomain).delete() remove_folder(output_dir) # remove tar file created in 'do_convert_data' function os.remove(output_dir + '.tar.gz') self.assertFalse(os.path.exists(output_dir)) def test_message_files(self) -> None: alice_id = 7 alice = dict( id=alice_id, profile=dict( email='alice@example.com', ), ) files = [ dict( url_private='files.slack.com/apple.png', title='Apple', name='apple.png', mimetype='image/png', timestamp=9999, created=8888, size=3000000, ), dict( url_private='example.com/banana.zip', title='banana', ), ] message = dict( user=alice_id, files=files, ) domain_name = 'example.com' realm_id = 5 message_id = 99 user = 'alice' users = [alice] added_users = { 'alice': alice_id, } zerver_attachment = [] # type: List[Dict[str, Any]] uploads_list = [] # type: List[Dict[str, Any]] info = process_message_files( message=message, domain_name=domain_name, realm_id=realm_id, message_id=message_id, user=user, users=users, added_users=added_users, zerver_attachment=zerver_attachment, uploads_list=uploads_list, ) self.assertEqual(len(zerver_attachment), 1) self.assertEqual(len(uploads_list), 1) image_path = zerver_attachment[0]['path_id'] self.assertIn('/SlackImportAttachment/', image_path) expected_content = '[Apple](/user_uploads/{image_path})\n[banana](example.com/banana.zip)'.format(image_path=image_path) self.assertEqual(info['content'], expected_content) self.assertTrue(info['has_link']) self.assertTrue(info['has_image']) self.assertEqual(uploads_list[0]['s3_path'], image_path) self.assertEqual(uploads_list[0]['realm_id'], realm_id) self.assertEqual(uploads_list[0]['user_profile_email'], 'alice@example.com')
[ "str", "List[str]", "List[str]", "Dict[str, Any]", "int", "mock.Mock", "mock.Mock", "mock.Mock", "mock.Mock", "mock.Mock", "mock.Mock", "mock.Mock", "mock.Mock", "mock.Mock", "mock.Mock", "mock.Mock", "mock.Mock", "mock.Mock" ]
[ 1351, 1517, 1538, 1625, 1654, 2447, 4997, 11937, 16402, 16485, 19669, 24405, 24476, 27002, 27083, 27160, 27240, 27315 ]
[ 1354, 1526, 1547, 1639, 1657, 2456, 5006, 11946, 16411, 16494, 19678, 24414, 24485, 27011, 27092, 27169, 27249, 27324 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_slack_message_conversion.py
# -*- coding: utf-8 -*- from django.conf import settings from zerver.data_import.slack_message_conversion import ( convert_to_zulip_markdown, get_user_full_name ) from zerver.lib.test_classes import ( ZulipTestCase, ) from zerver.lib.test_runner import slow from zerver.lib import mdiff import ujson import os from typing import Any, AnyStr, Dict, List, Optional, Set, Tuple class SlackMessageConversion(ZulipTestCase): def assertEqual(self, first: Any, second: Any, msg: str="") -> None: if isinstance(first, str) and isinstance(second, str): if first != second: raise AssertionError("Actual and expected outputs do not match; showing diff.\n" + mdiff.diff_strings(first, second) + msg) else: super().assertEqual(first, second) def load_slack_message_conversion_tests(self) -> Dict[Any, Any]: test_fixtures = {} data_file = open(os.path.join(os.path.dirname(__file__), 'fixtures/slack_message_conversion.json'), 'r') data = ujson.loads('\n'.join(data_file.readlines())) for test in data['regular_tests']: test_fixtures[test['name']] = test return test_fixtures @slow("Aggregate of runs of individual slack message conversion tests") def test_message_conversion_fixtures(self) -> None: format_tests = self.load_slack_message_conversion_tests() valid_keys = set(['name', "input", "conversion_output"]) for name, test in format_tests.items(): # Check that there aren't any unexpected keys as those are often typos self.assertEqual(len(set(test.keys()) - valid_keys), 0) slack_user_map = {} # type: Dict[str, int] users = [{}] # type: List[Dict[str, Any]] channel_map = {} # type: Dict[str, Tuple[str, int]] converted = convert_to_zulip_markdown(test['input'], users, channel_map, slack_user_map) converted_text = converted[0] print("Running Slack Message Conversion test: %s" % (name,)) self.assertEqual(converted_text, test['conversion_output']) def test_mentioned_data(self) -> None: slack_user_map = {'U08RGD1RD': 540, 'U0CBK5KAT': 554, 'U09TYF5SK': 571} # For this test, only relevant keys are 'id', 'name', 'deleted' # and 'real_name' users = [{"id": "U0CBK5KAT", "name": "aaron.anzalone", "deleted": False, "real_name": ""}, {"id": "U08RGD1RD", "name": "john", "deleted": False, "real_name": "John Doe"}, {"id": "U09TYF5Sk", "name": "Jane", "deleted": True}] # Deleted users don't have 'real_name' key in Slack channel_map = {'general': ('C5Z73A7RA', 137)} message = 'Hi <@U08RGD1RD|john>: How are you? <#C5Z73A7RA|general>' text, mentioned_users, has_link = convert_to_zulip_markdown(message, users, channel_map, slack_user_map) full_name = get_user_full_name(users[1]) self.assertEqual(full_name, 'John Doe') self.assertEqual(get_user_full_name(users[2]), 'Jane') self.assertEqual(text, 'Hi @**%s**: How are you? #**general**' % (full_name)) self.assertEqual(mentioned_users, [540]) # multiple mentioning message = 'Hi <@U08RGD1RD|john>: How are you?<@U0CBK5KAT> asked.' text, mentioned_users, has_link = convert_to_zulip_markdown(message, users, channel_map, slack_user_map) self.assertEqual(text, 'Hi @**%s**: How are you?@**%s** asked.' % ('John Doe', 'aaron.anzalone')) self.assertEqual(mentioned_users, [540, 554]) # Check wrong mentioning message = 'Hi <@U08RGD1RD|jon>: How are you?' text, mentioned_users, has_link = convert_to_zulip_markdown(message, users, channel_map, slack_user_map) self.assertEqual(text, message) self.assertEqual(mentioned_users, []) def test_has_link(self) -> None: slack_user_map = {} # type: Dict[str, int] message = '<http://journals.plos.org/plosone/article>' text, mentioned_users, has_link = convert_to_zulip_markdown(message, [], {}, slack_user_map) self.assertEqual(text, 'http://journals.plos.org/plosone/article') self.assertEqual(has_link, True) message = '<mailto:foo@foo.com>' text, mentioned_users, has_link = convert_to_zulip_markdown(message, [], {}, slack_user_map) self.assertEqual(text, 'mailto:foo@foo.com') self.assertEqual(has_link, True) message = 'random message' text, mentioned_users, has_link = convert_to_zulip_markdown(message, [], {}, slack_user_map) self.assertEqual(has_link, False)
[ "Any", "Any" ]
[ 468, 481 ]
[ 471, 484 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_soft_deactivation.py
# -*- coding: utf-8 -*- from django.utils.timezone import now as timezone_now from zerver.lib.soft_deactivation import ( do_soft_deactivate_user, do_soft_deactivate_users, get_users_for_soft_deactivation, do_soft_activate_users ) from zerver.lib.test_classes import ZulipTestCase from zerver.models import ( Client, UserProfile, UserActivity, get_realm, Recipient ) class UserSoftDeactivationTests(ZulipTestCase): def test_do_soft_deactivate_user(self) -> None: user = self.example_user('hamlet') self.assertFalse(user.long_term_idle) do_soft_deactivate_user(user) user.refresh_from_db() self.assertTrue(user.long_term_idle) def test_do_soft_deactivate_users(self) -> None: users = [ self.example_user('hamlet'), self.example_user('iago'), self.example_user('cordelia'), ] for user in users: self.assertFalse(user.long_term_idle) # We are sending this message to ensure that users have at least # one UserMessage row. self.send_huddle_message(users[0].email, [user.email for user in users]) do_soft_deactivate_users(users) for user in users: user.refresh_from_db() self.assertTrue(user.long_term_idle) def test_get_users_for_soft_deactivation(self) -> None: users = [ self.example_user('hamlet'), self.example_user('iago'), self.example_user('cordelia'), self.example_user('ZOE'), self.example_user('othello'), self.example_user('prospero'), self.example_user('aaron'), self.example_user('polonius'), ] client, _ = Client.objects.get_or_create(name='website') query = '/json/users/me/pointer' last_visit = timezone_now() count = 150 for user_profile in UserProfile.objects.all(): UserActivity.objects.get_or_create( user_profile=user_profile, client=client, query=query, count=count, last_visit=last_visit ) filter_kwargs = dict(user_profile__realm=get_realm('zulip')) users_to_deactivate = get_users_for_soft_deactivation(-1, filter_kwargs) self.assert_length(users_to_deactivate, 8) for user in users_to_deactivate: self.assertTrue(user in users) def test_do_soft_activate_users(self) -> None: users = [ self.example_user('hamlet'), self.example_user('iago'), self.example_user('cordelia'), ] self.send_huddle_message(users[0].email, [user.email for user in users]) do_soft_deactivate_users(users) for user in users: self.assertTrue(user.long_term_idle) do_soft_activate_users(users) for user in users: user.refresh_from_db() self.assertFalse(user.long_term_idle)
[]
[]
[]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_subdomains.py
import mock from typing import Any, Dict, List from django.test import TestCase, override_settings from zerver.lib.subdomains import get_subdomain from zerver.models import Realm class SubdomainsTest(TestCase): def test_get_subdomain(self) -> None: def request_mock(host: str) -> Any: request = mock.Mock(spec=['get_host']) request.attach_mock(mock.Mock(return_value=host), 'get_host') return request def test(expected: str, host: str, *, plusport: bool=True, external_host: str='example.org', realm_hosts: Dict[str, str]={}, root_aliases: List[str]=[]) -> None: with self.settings(EXTERNAL_HOST=external_host, REALM_HOSTS=realm_hosts, ROOT_SUBDOMAIN_ALIASES=root_aliases): self.assertEqual(get_subdomain(request_mock(host)), expected) if plusport and ':' not in host: self.assertEqual(get_subdomain(request_mock(host + ':443')), expected) ROOT = Realm.SUBDOMAIN_FOR_ROOT_DOMAIN # Basics test(ROOT, 'example.org') test('foo', 'foo.example.org') test(ROOT, 'www.example.org', root_aliases=['www']) # Unrecognized patterns fall back to root test(ROOT, 'arbitrary.com') test(ROOT, 'foo.example.org.evil.com') # REALM_HOSTS adds a name, test('bar', 'chat.barbar.com', realm_hosts={'bar': 'chat.barbar.com'}) # ... exactly, ... test(ROOT, 'surchat.barbar.com', realm_hosts={'bar': 'chat.barbar.com'}) test(ROOT, 'foo.chat.barbar.com', realm_hosts={'bar': 'chat.barbar.com'}) # ... and leaves the subdomain in place too. test('bar', 'bar.example.org', realm_hosts={'bar': 'chat.barbar.com'}) # Any port is fine in Host if there's none in EXTERNAL_HOST, ... test('foo', 'foo.example.org:443', external_host='example.org') test('foo', 'foo.example.org:12345', external_host='example.org') # ... but an explicit port in EXTERNAL_HOST must be explicitly matched in Host. test(ROOT, 'foo.example.org', external_host='example.org:12345') test(ROOT, 'foo.example.org', external_host='example.org:443', plusport=False) test('foo', 'foo.example.org:443', external_host='example.org:443')
[ "str", "str", "str" ]
[ 289, 482, 493 ]
[ 292, 485, 496 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_submessage.py
import mock from zerver.lib.test_classes import ZulipTestCase from zerver.lib.message import ( MessageDict, ) from zerver.models import ( Message, SubMessage, ) from typing import Any, Dict, List class TestBasics(ZulipTestCase): def test_get_raw_db_rows(self) -> None: cordelia = self.example_user('cordelia') hamlet = self.example_user('hamlet') stream_name = 'Verona' message_id = self.send_stream_message( sender_email=cordelia.email, stream_name=stream_name, ) def get_raw_rows() -> List[Dict[str, Any]]: query = SubMessage.get_raw_db_rows([message_id]) rows = list(query) return rows rows = get_raw_rows() self.assertEqual(rows, []) sm1 = SubMessage.objects.create( msg_type='whatever', content='stuff1', message_id=message_id, sender=cordelia, ) sm2 = SubMessage.objects.create( msg_type='whatever', content='stuff2', message_id=message_id, sender=hamlet, ) expected_data = [ dict( id=sm1.id, message_id=message_id, sender_id=cordelia.id, msg_type='whatever', content='stuff1', ), dict( id=sm2.id, message_id=message_id, sender_id=hamlet.id, msg_type='whatever', content='stuff2', ), ] self.assertEqual(get_raw_rows(), expected_data) message = Message.objects.get(id=message_id) message_json = MessageDict.wide_dict(message) rows = message_json['submessages'] rows.sort(key=lambda r: r['id']) self.assertEqual(rows, expected_data) msg_rows = MessageDict.get_raw_db_rows([message_id]) rows = msg_rows[0]['submessages'] rows.sort(key=lambda r: r['id']) self.assertEqual(rows, expected_data) def test_endpoint_errors(self) -> None: cordelia = self.example_user('cordelia') stream_name = 'Verona' message_id = self.send_stream_message( sender_email=cordelia.email, stream_name=stream_name, ) self.login(cordelia.email) payload = dict( message_id=message_id, msg_type='whatever', content='not json', ) result = self.client_post('/json/submessage', payload) self.assert_json_error(result, 'Invalid json for submessage') hamlet = self.example_user('hamlet') bad_message_id = self.send_personal_message( from_email=hamlet.email, to_email=hamlet.email, ) payload = dict( message_id=bad_message_id, msg_type='whatever', content='does not matter', ) result = self.client_post('/json/submessage', payload) self.assert_json_error(result, 'Invalid message(s)') def test_endpoint_success(self) -> None: cordelia = self.example_user('cordelia') hamlet = self.example_user('hamlet') stream_name = 'Verona' message_id = self.send_stream_message( sender_email=cordelia.email, stream_name=stream_name, ) self.login(cordelia.email) payload = dict( message_id=message_id, msg_type='whatever', content='{"name": "alice", "salary": 20}' ) with mock.patch('zerver.lib.actions.send_event') as m: result = self.client_post('/json/submessage', payload) self.assert_json_success(result) submessage = SubMessage.objects.get(message_id=message_id) expected_data = dict( message_id=message_id, submessage_id=submessage.id, content=payload['content'], msg_type='whatever', sender_id=cordelia.id, type='submessage', ) self.assertEqual(m.call_count, 1) data = m.call_args[0][1] self.assertEqual(data, expected_data) users = m.call_args[0][2] self.assertIn(cordelia.id, users) self.assertIn(hamlet.id, users) rows = SubMessage.get_raw_db_rows([message_id]) self.assertEqual(len(rows), 1) row = rows[0] expected_data = dict( id=row['id'], message_id=message_id, content='{"name": "alice", "salary": 20}', msg_type='whatever', sender_id=cordelia.id, ) self.assertEqual(row, expected_data)
[]
[]
[]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_subs.py
# -*- coding: utf-8 -*- from typing import Any, Dict, List, Mapping, Optional, Sequence, Set from django.conf import settings from django.core.exceptions import ValidationError from django.http import HttpRequest, HttpResponse from django.test import override_settings from django.utils.timezone import now as timezone_now from zerver.lib import cache from zerver.lib.test_helpers import ( get_subscription, queries_captured, tornado_redirected_to_list ) from zerver.lib.test_classes import ( ZulipTestCase, ) from zerver.decorator import ( JsonableError ) from zerver.lib.response import ( json_error, json_success, ) from zerver.lib.streams import ( access_stream_by_id, access_stream_by_name, filter_stream_authorization, list_to_streams, ) from zerver.lib.stream_subscription import ( get_active_subscriptions_for_stream_id, num_subscribers_for_stream_id, ) from zerver.lib.test_runner import ( slow ) from zerver.models import ( get_display_recipient, Message, Realm, Recipient, Stream, Subscription, DefaultStream, UserProfile, get_user_profile_by_id, active_non_guest_user_ids, get_default_stream_groups, flush_per_request_caches, DefaultStreamGroup, get_client, ) from zerver.lib.actions import ( do_add_default_stream, do_change_is_admin, do_set_realm_property, do_create_realm, do_remove_default_stream, bulk_get_subscriber_user_ids, gather_subscriptions_helper, bulk_add_subscriptions, bulk_remove_subscriptions, gather_subscriptions, get_default_streams_for_realm, get_realm, get_stream, get_user, set_default_streams, check_stream_name, do_get_streams, create_stream_if_needed, create_streams_if_needed, ensure_stream, do_deactivate_stream, do_deactivate_user, stream_welcome_message, do_create_default_stream_group, do_add_streams_to_default_stream_group, do_remove_streams_from_default_stream_group, do_remove_default_stream_group, do_change_default_stream_group_description, do_change_default_stream_group_name, lookup_default_stream_groups, can_access_stream_user_ids, validate_user_access_to_subscribers_helper, get_average_weekly_stream_traffic, round_to_2_significant_digits ) from zerver.views.streams import ( compose_views ) from zerver.lib.message import ( aggregate_unread_data, get_raw_unread_data, ) from zerver.lib.stream_recipient import StreamRecipientMap from django.http import HttpResponse from datetime import timedelta import mock import random import ujson import urllib class TestMiscStuff(ZulipTestCase): def test_empty_results(self) -> None: # These are essentially just tests to ensure line # coverage for codepaths that won't ever really be # called in practice. user_profile = self.example_user('cordelia') result = bulk_get_subscriber_user_ids( stream_dicts=[], user_profile=user_profile, sub_dict={}, stream_recipient=StreamRecipientMap(), ) self.assertEqual(result, {}) streams = do_get_streams( user_profile=user_profile, include_public=False, include_subscribed=False, include_all_active=False, include_default=False, ) self.assertEqual(streams, []) class TestCreateStreams(ZulipTestCase): def test_creating_streams(self) -> None: stream_names = [u'new1', u'new2', u'new3'] stream_descriptions = [u'des1', u'des2', u'des3'] realm = get_realm('zulip') # Test stream creation events. events = [] # type: List[Mapping[str, Any]] with tornado_redirected_to_list(events): ensure_stream(realm, "Public stream", invite_only=False) self.assert_length(events, 1) self.assertEqual(events[0]['event']['type'], 'stream') self.assertEqual(events[0]['event']['op'], 'create') # Send public stream creation event to all active users. self.assertEqual(events[0]['users'], active_non_guest_user_ids(realm.id)) self.assertEqual(events[0]['event']['streams'][0]['name'], "Public stream") events = [] with tornado_redirected_to_list(events): ensure_stream(realm, "Private stream", invite_only=True) self.assert_length(events, 1) self.assertEqual(events[0]['event']['type'], 'stream') self.assertEqual(events[0]['event']['op'], 'create') # Send private stream creation event to only realm admins. self.assertEqual(events[0]['users'], [self.example_user("iago").id]) self.assertEqual(events[0]['event']['streams'][0]['name'], "Private stream") new_streams, existing_streams = create_streams_if_needed( realm, [{"name": stream_name, "description": stream_description, "invite_only": True, "is_announcement_only": True} for (stream_name, stream_description) in zip(stream_names, stream_descriptions)]) self.assertEqual(len(new_streams), 3) self.assertEqual(len(existing_streams), 0) actual_stream_names = {stream.name for stream in new_streams} self.assertEqual(actual_stream_names, set(stream_names)) actual_stream_descriptions = {stream.description for stream in new_streams} self.assertEqual(actual_stream_descriptions, set(stream_descriptions)) for stream in new_streams: self.assertTrue(stream.invite_only) self.assertTrue(stream.is_announcement_only) new_streams, existing_streams = create_streams_if_needed( realm, [{"name": stream_name, "description": stream_description, "invite_only": True} for (stream_name, stream_description) in zip(stream_names, stream_descriptions)]) self.assertEqual(len(new_streams), 0) self.assertEqual(len(existing_streams), 3) actual_stream_names = {stream.name for stream in existing_streams} self.assertEqual(actual_stream_names, set(stream_names)) actual_stream_descriptions = {stream.description for stream in existing_streams} self.assertEqual(actual_stream_descriptions, set(stream_descriptions)) for stream in existing_streams: self.assertTrue(stream.invite_only) def test_history_public_to_subscribers_on_stream_creation(self) -> None: realm = get_realm('zulip') stream_dicts = [ { "name": "publicstream", "description": "Public stream with public history" }, { "name": "privatestream", "description": "Private stream with non-public history", "invite_only": True }, { "name": "privatewithhistory", "description": "Private stream with public history", "invite_only": True, "history_public_to_subscribers": True }, { "name": "publictrywithouthistory", "description": "Public stream without public history (disallowed)", "invite_only": False, "history_public_to_subscribers": False }, ] # type: List[Mapping[str, Any]] created, existing = create_streams_if_needed(realm, stream_dicts) self.assertEqual(len(created), 4) self.assertEqual(len(existing), 0) for stream in created: if stream.name == 'publicstream': self.assertTrue(stream.history_public_to_subscribers) if stream.name == 'privatestream': self.assertFalse(stream.history_public_to_subscribers) if stream.name == 'privatewithhistory': self.assertTrue(stream.history_public_to_subscribers) if stream.name == 'publictrywithouthistory': self.assertTrue(stream.history_public_to_subscribers) def test_history_public_to_subscribers_zephyr_realm(self) -> None: realm = get_realm('zephyr') stream, created = create_stream_if_needed(realm, "private_stream", invite_only=True) self.assertTrue(created) self.assertTrue(stream.invite_only) self.assertFalse(stream.history_public_to_subscribers) stream, created = create_stream_if_needed(realm, "public_stream", invite_only=False) self.assertTrue(created) self.assertFalse(stream.invite_only) self.assertFalse(stream.history_public_to_subscribers) def test_welcome_message(self) -> None: realm = get_realm('zulip') name = u'New Stream' new_stream = ensure_stream( realm=realm, stream_name=name ) welcome_message = stream_welcome_message(new_stream) self.assertEqual( welcome_message, u'Welcome to #**New Stream**.' ) new_stream.description = 'Talk about **stuff**.' welcome_message = stream_welcome_message(new_stream) self.assertEqual( welcome_message, 'Welcome to #**New Stream**.' '\n\n' '**Description**: Talk about **stuff**.' ) class RecipientTest(ZulipTestCase): def test_recipient(self) -> None: realm = get_realm('zulip') stream = get_stream('Verona', realm) recipient = Recipient.objects.get( type_id=stream.id, type=Recipient.STREAM, ) self.assertEqual(str(recipient), '<Recipient: Verona (%d, %d)>' % ( stream.id, Recipient.STREAM)) class StreamAdminTest(ZulipTestCase): def test_make_stream_public(self) -> None: user_profile = self.example_user('hamlet') email = user_profile.email self.login(email) self.make_stream('private_stream', invite_only=True) do_change_is_admin(user_profile, True) params = { 'stream_name': ujson.dumps('private_stream'), 'is_private': ujson.dumps(False) } stream_id = get_stream('private_stream', user_profile.realm).id result = self.client_patch("/json/streams/%d" % (stream_id,), params) self.assert_json_error(result, 'Invalid stream id') stream = self.subscribe(user_profile, 'private_stream') self.assertFalse(stream.is_in_zephyr_realm) do_change_is_admin(user_profile, True) params = { 'stream_name': ujson.dumps('private_stream'), 'is_private': ujson.dumps(False) } result = self.client_patch("/json/streams/%d" % (stream_id,), params) self.assert_json_success(result) realm = user_profile.realm stream = get_stream('private_stream', realm) self.assertFalse(stream.invite_only) self.assertTrue(stream.history_public_to_subscribers) def test_make_stream_private(self) -> None: user_profile = self.example_user('hamlet') email = user_profile.email self.login(email) realm = user_profile.realm self.make_stream('public_stream', realm=realm) do_change_is_admin(user_profile, True) params = { 'stream_name': ujson.dumps('public_stream'), 'is_private': ujson.dumps(True) } stream_id = get_stream('public_stream', realm).id result = self.client_patch("/json/streams/%d" % (stream_id,), params) self.assert_json_success(result) stream = get_stream('public_stream', realm) self.assertTrue(stream.invite_only) self.assertFalse(stream.history_public_to_subscribers) def test_make_stream_public_zephyr_mirror(self) -> None: user_profile = self.mit_user('starnine') email = user_profile.email self.login(email, realm=get_realm("zephyr")) realm = user_profile.realm self.make_stream('target_stream', realm=realm, invite_only=True) self.subscribe(user_profile, 'target_stream') do_change_is_admin(user_profile, True) params = { 'stream_name': ujson.dumps('target_stream'), 'is_private': ujson.dumps(False) } stream_id = get_stream('target_stream', realm).id result = self.client_patch("/json/streams/%d" % (stream_id,), params, subdomain="zephyr") self.assert_json_success(result) stream = get_stream('target_stream', realm) self.assertFalse(stream.invite_only) self.assertFalse(stream.history_public_to_subscribers) def test_make_stream_private_with_public_history(self) -> None: user_profile = self.example_user('hamlet') email = user_profile.email self.login(email) realm = user_profile.realm self.make_stream('public_history_stream', realm=realm) do_change_is_admin(user_profile, True) params = { 'stream_name': ujson.dumps('public_history_stream'), 'is_private': ujson.dumps(True), 'history_public_to_subscribers': ujson.dumps(True), } stream_id = get_stream('public_history_stream', realm).id result = self.client_patch("/json/streams/%d" % (stream_id,), params) self.assert_json_success(result) stream = get_stream('public_history_stream', realm) self.assertTrue(stream.invite_only) self.assertTrue(stream.history_public_to_subscribers) def test_try_make_stream_public_with_private_history(self) -> None: user_profile = self.example_user('hamlet') email = user_profile.email self.login(email) realm = user_profile.realm self.make_stream('public_stream', realm=realm) do_change_is_admin(user_profile, True) params = { 'stream_name': ujson.dumps('public_stream'), 'is_private': ujson.dumps(False), 'history_public_to_subscribers': ujson.dumps(False), } stream_id = get_stream('public_stream', realm).id result = self.client_patch("/json/streams/%d" % (stream_id,), params) self.assert_json_success(result) stream = get_stream('public_stream', realm) self.assertFalse(stream.invite_only) self.assertTrue(stream.history_public_to_subscribers) def test_deactivate_stream_backend(self) -> None: user_profile = self.example_user('hamlet') email = user_profile.email self.login(email) stream = self.make_stream('new_stream') self.subscribe(user_profile, stream.name) do_change_is_admin(user_profile, True) result = self.client_delete('/json/streams/%d' % (stream.id,)) self.assert_json_success(result) subscription_exists = get_active_subscriptions_for_stream_id(stream.id).filter( user_profile=user_profile, ).exists() self.assertFalse(subscription_exists) def test_deactivate_stream_removes_default_stream(self) -> None: stream = self.make_stream('new_stream') do_add_default_stream(stream) self.assertEqual(1, DefaultStream.objects.filter(stream_id=stream.id).count()) do_deactivate_stream(stream) self.assertEqual(0, DefaultStream.objects.filter(stream_id=stream.id).count()) def test_vacate_private_stream_removes_default_stream(self) -> None: stream = self.make_stream('new_stream', invite_only=True) self.subscribe(self.example_user("hamlet"), stream.name) do_add_default_stream(stream) self.assertEqual(1, DefaultStream.objects.filter(stream_id=stream.id).count()) self.unsubscribe(self.example_user("hamlet"), stream.name) self.assertEqual(0, DefaultStream.objects.filter(stream_id=stream.id).count()) # Fetch stream again from database. stream = Stream.objects.get(id=stream.id) self.assertTrue(stream.deactivated) def test_deactivate_stream_backend_requires_existing_stream(self) -> None: user_profile = self.example_user('hamlet') email = user_profile.email self.login(email) self.make_stream('new_stream') do_change_is_admin(user_profile, True) result = self.client_delete('/json/streams/999999999') self.assert_json_error(result, u'Invalid stream id') def test_deactivate_stream_backend_requires_realm_admin(self) -> None: user_profile = self.example_user('hamlet') self.login(user_profile.email) self.subscribe(user_profile, 'new_stream') stream_id = get_stream('new_stream', user_profile.realm).id result = self.client_delete('/json/streams/%d' % (stream_id,)) self.assert_json_error(result, 'Must be an organization administrator') def test_private_stream_live_updates(self) -> None: user_profile = self.example_user('hamlet') self.login(user_profile.email) do_change_is_admin(user_profile, True) self.make_stream('private_stream', invite_only=True) self.subscribe(user_profile, 'private_stream') self.subscribe(self.example_user("cordelia"), 'private_stream') events = [] # type: List[Mapping[str, Any]] with tornado_redirected_to_list(events): stream_id = get_stream('private_stream', user_profile.realm).id result = self.client_patch('/json/streams/%d' % (stream_id,), {'description': ujson.dumps('Test description')}) self.assert_json_success(result) # Should be just a description change event self.assert_length(events, 1) cordelia = self.example_user('cordelia') prospero = self.example_user('prospero') notified_user_ids = set(events[-1]['users']) self.assertIn(user_profile.id, notified_user_ids) self.assertIn(cordelia.id, notified_user_ids) self.assertNotIn(prospero.id, notified_user_ids) events = [] with tornado_redirected_to_list(events): stream_id = get_stream('private_stream', user_profile.realm).id result = self.client_patch('/json/streams/%d' % (stream_id,), {'new_name': ujson.dumps('whatever')}) self.assert_json_success(result) # Should be a name event and an email address event self.assert_length(events, 2) notified_user_ids = set(events[-1]['users']) self.assertIn(user_profile.id, notified_user_ids) self.assertIn(cordelia.id, notified_user_ids) self.assertNotIn(prospero.id, notified_user_ids) def test_rename_stream(self) -> None: user_profile = self.example_user('hamlet') email = user_profile.email self.login(email) realm = user_profile.realm stream = self.subscribe(user_profile, 'stream_name1') do_change_is_admin(user_profile, True) result = self.client_patch('/json/streams/%d' % (stream.id,), {'new_name': ujson.dumps('stream_name1')}) self.assert_json_error(result, "Stream already has that name!") result = self.client_patch('/json/streams/%d' % (stream.id,), {'new_name': ujson.dumps('Denmark')}) self.assert_json_error(result, "Stream name 'Denmark' is already taken.") result = self.client_patch('/json/streams/%d' % (stream.id,), {'new_name': ujson.dumps('denmark ')}) self.assert_json_error(result, "Stream name 'denmark' is already taken.") # Do a rename that is case-only--this should succeed. result = self.client_patch('/json/streams/%d' % (stream.id,), {'new_name': ujson.dumps('sTREAm_name1')}) self.assert_json_success(result) events = [] # type: List[Mapping[str, Any]] with tornado_redirected_to_list(events): stream_id = get_stream('stream_name1', user_profile.realm).id result = self.client_patch('/json/streams/%d' % (stream_id,), {'new_name': ujson.dumps('stream_name2')}) self.assert_json_success(result) event = events[1]['event'] self.assertEqual(event, dict( op='update', type='stream', property='name', value='stream_name2', stream_id=stream_id, name='sTREAm_name1' )) notified_user_ids = set(events[1]['users']) self.assertRaises(Stream.DoesNotExist, get_stream, 'stream_name1', realm) stream_name2_exists = get_stream('stream_name2', realm) self.assertTrue(stream_name2_exists) self.assertEqual(notified_user_ids, set(active_non_guest_user_ids(realm.id))) self.assertIn(user_profile.id, notified_user_ids) self.assertIn(self.example_user('prospero').id, notified_user_ids) self.assertNotIn(self.example_user('polonius').id, notified_user_ids) # Test case to handle unicode stream name change # *NOTE: Here Encoding is needed when Unicode string is passed as an argument* with tornado_redirected_to_list(events): stream_id = stream_name2_exists.id result = self.client_patch('/json/streams/%d' % (stream_id,), {'new_name': ujson.dumps(u'नया नाम'.encode('utf-8'))}) self.assert_json_success(result) # While querying, system can handle unicode strings. stream_name_uni_exists = get_stream(u'नया नाम', realm) self.assertTrue(stream_name_uni_exists) # Test case to handle changing of unicode stream name to newer name # NOTE: Unicode string being part of URL is handled cleanly # by client_patch call, encoding of URL is not needed. with tornado_redirected_to_list(events): stream_id = stream_name_uni_exists.id result = self.client_patch('/json/streams/%d' % (stream_id,), {'new_name': ujson.dumps(u'नाम में क्या रक्खा हे'.encode('utf-8'))}) self.assert_json_success(result) # While querying, system can handle unicode strings. self.assertRaises(Stream.DoesNotExist, get_stream, u'नया नाम', realm) stream_name_new_uni_exists = get_stream(u'नाम में क्या रक्खा हे', realm) self.assertTrue(stream_name_new_uni_exists) # Test case to change name from one language to other. with tornado_redirected_to_list(events): stream_id = stream_name_new_uni_exists.id result = self.client_patch('/json/streams/%d' % (stream_id,), {'new_name': ujson.dumps(u'français'.encode('utf-8'))}) self.assert_json_success(result) stream_name_fr_exists = get_stream(u'français', realm) self.assertTrue(stream_name_fr_exists) # Test case to change name to mixed language name. with tornado_redirected_to_list(events): stream_id = stream_name_fr_exists.id result = self.client_patch('/json/streams/%d' % (stream_id,), {'new_name': ujson.dumps(u'français name'.encode('utf-8'))}) self.assert_json_success(result) stream_name_mixed_exists = get_stream(u'français name', realm) self.assertTrue(stream_name_mixed_exists) # Test case for notified users in private streams. stream_private = self.make_stream('stream_private_name1', realm=user_profile.realm, invite_only=True) self.subscribe(self.example_user('cordelia'), 'stream_private_name1') del events[:] with tornado_redirected_to_list(events): stream_id = get_stream('stream_private_name1', realm).id result = self.client_patch('/json/streams/%d' % (stream_id,), {'new_name': ujson.dumps('stream_private_name2')}) self.assert_json_success(result) notified_user_ids = set(events[1]['users']) self.assertEqual(notified_user_ids, can_access_stream_user_ids(stream_private)) self.assertIn(self.example_user('cordelia').id, notified_user_ids) # An important corner case is that all organization admins are notified. self.assertIn(self.example_user('iago').id, notified_user_ids) # The current user, Hamlet was made an admin and thus should be notified too. self.assertIn(user_profile.id, notified_user_ids) self.assertNotIn(self.example_user('prospero').id, notified_user_ids) def test_rename_stream_requires_realm_admin(self) -> None: user_profile = self.example_user('hamlet') email = user_profile.email self.login(email) self.make_stream('stream_name1') stream_id = get_stream('stream_name1', user_profile.realm).id result = self.client_patch('/json/streams/%d' % (stream_id,), {'new_name': ujson.dumps('stream_name2')}) self.assert_json_error(result, 'Must be an organization administrator') def test_realm_admin_can_update_unsub_private_stream(self) -> None: iago = self.example_user('iago') self.login(iago.email) result = self.common_subscribe_to_streams(iago.email, ["private_stream"], dict(principals=ujson.dumps([self.example_email("hamlet")])), invite_only=True) self.assert_json_success(result) stream_id = get_stream('private_stream', iago.realm).id result = self.client_patch('/json/streams/%d' % (stream_id,), {'new_name': ujson.dumps('new_private_stream')}) self.assert_json_success(result) result = self.client_patch('/json/streams/%d' % (stream_id,), {'new_description': ujson.dumps('new description')}) self.assert_json_success(result) # But cannot change stream type. result = self.client_patch('/json/streams/%d' % (stream_id,), {'stream_name': ujson.dumps('private_stream'), 'is_private': ujson.dumps(True)}) self.assert_json_error(result, "Invalid stream id") def test_change_stream_description(self) -> None: user_profile = self.example_user('iago') email = user_profile.email self.login(email) realm = user_profile.realm self.subscribe(user_profile, 'stream_name1') events = [] # type: List[Mapping[str, Any]] with tornado_redirected_to_list(events): stream_id = get_stream('stream_name1', realm).id result = self.client_patch('/json/streams/%d' % (stream_id,), {'description': ujson.dumps('Test description')}) self.assert_json_success(result) event = events[0]['event'] self.assertEqual(event, dict( op='update', type='stream', property='description', value='Test description', stream_id=stream_id, name='stream_name1' )) notified_user_ids = set(events[0]['users']) stream = get_stream('stream_name1', realm) self.assertEqual(notified_user_ids, set(active_non_guest_user_ids(realm.id))) self.assertIn(user_profile.id, notified_user_ids) self.assertIn(self.example_user('prospero').id, notified_user_ids) self.assertNotIn(self.example_user('polonius').id, notified_user_ids) self.assertEqual('Test description', stream.description) result = self.client_patch('/json/streams/%d' % (stream_id,), {'description': ujson.dumps('a' * 1025)}) self.assert_json_error(result, "description is too long (limit: %s characters)" % (Stream.MAX_DESCRIPTION_LENGTH)) def test_change_stream_description_requires_realm_admin(self) -> None: user_profile = self.example_user('hamlet') email = user_profile.email self.login(email) self.subscribe(user_profile, 'stream_name1') do_change_is_admin(user_profile, False) stream_id = get_stream('stream_name1', user_profile.realm).id result = self.client_patch('/json/streams/%d' % (stream_id,), {'description': ujson.dumps('Test description')}) self.assert_json_error(result, 'Must be an organization administrator') def test_change_stream_announcement_only(self) -> None: user_profile = self.example_user('hamlet') self.login(user_profile.email) self.subscribe(user_profile, 'stream_name1') do_change_is_admin(user_profile, True) stream_id = get_stream('stream_name1', user_profile.realm).id result = self.client_patch('/json/streams/%d' % (stream_id,), {'is_announcement_only': ujson.dumps(True)}) self.assert_json_success(result) stream = get_stream('stream_name1', user_profile.realm) self.assertEqual(True, stream.is_announcement_only) def test_change_stream_announcement_only_requires_realm_admin(self) -> None: user_profile = self.example_user('hamlet') self.login(user_profile.email) self.subscribe(user_profile, 'stream_name1') do_change_is_admin(user_profile, False) stream_id = get_stream('stream_name1', user_profile.realm).id result = self.client_patch('/json/streams/%d' % (stream_id,), {'is_announcement_only': ujson.dumps(True)}) self.assert_json_error(result, 'Must be an organization administrator') def set_up_stream_for_deletion(self, stream_name: str, invite_only: bool=False, subscribed: bool=True) -> Stream: """ Create a stream for deletion by an administrator. """ user_profile = self.example_user('hamlet') email = user_profile.email self.login(email) stream = self.make_stream(stream_name, invite_only=invite_only) # For testing deleting streams you aren't on. if subscribed: self.subscribe(user_profile, stream_name) do_change_is_admin(user_profile, True) return stream def delete_stream(self, stream: Stream) -> None: """ Delete the stream and assess the result. """ active_name = stream.name realm = stream.realm stream_id = stream.id # Simulate that a stream by the same name has already been # deactivated, just to exercise our renaming logic: ensure_stream(realm, "!DEACTIVATED:" + active_name) events = [] # type: List[Mapping[str, Any]] with tornado_redirected_to_list(events): result = self.client_delete('/json/streams/' + str(stream_id)) self.assert_json_success(result) # We no longer send subscription events for stream deactivations. sub_events = [e for e in events if e['event']['type'] == 'subscription'] self.assertEqual(sub_events, []) stream_events = [e for e in events if e['event']['type'] == 'stream'] self.assertEqual(len(stream_events), 1) event = stream_events[0]['event'] self.assertEqual(event['op'], 'delete') self.assertEqual(event['streams'][0]['stream_id'], stream.id) with self.assertRaises(Stream.DoesNotExist): Stream.objects.get(realm=get_realm("zulip"), name=active_name) # A deleted stream's name is changed, is deactivated, is invite-only, # and has no subscribers. deactivated_stream_name = "!!DEACTIVATED:" + active_name deactivated_stream = get_stream(deactivated_stream_name, realm) self.assertTrue(deactivated_stream.deactivated) self.assertTrue(deactivated_stream.invite_only) self.assertEqual(deactivated_stream.name, deactivated_stream_name) subscribers = self.users_subscribed_to_stream( deactivated_stream_name, realm) self.assertEqual(subscribers, []) # It doesn't show up in the list of public streams anymore. result = self.client_get("/json/streams?include_subscribed=false") public_streams = [s["name"] for s in result.json()["streams"]] self.assertNotIn(active_name, public_streams) self.assertNotIn(deactivated_stream_name, public_streams) # Even if you could guess the new name, you can't subscribe to it. result = self.client_post( "/json/users/me/subscriptions", {"subscriptions": ujson.dumps([{"name": deactivated_stream_name}])}) self.assert_json_error( result, "Unable to access stream (%s)." % (deactivated_stream_name,)) def test_you_must_be_realm_admin(self) -> None: """ You must be on the realm to create a stream. """ user_profile = self.example_user('hamlet') self.login(user_profile.email) other_realm = Realm.objects.create(string_id='other') stream = self.make_stream('other_realm_stream', realm=other_realm) result = self.client_delete('/json/streams/' + str(stream.id)) self.assert_json_error(result, 'Must be an organization administrator') # Even becoming a realm admin doesn't help us for an out-of-realm # stream. do_change_is_admin(user_profile, True) result = self.client_delete('/json/streams/' + str(stream.id)) self.assert_json_error(result, 'Invalid stream id') def test_delete_public_stream(self) -> None: """ When an administrator deletes a public stream, that stream is not visible to users at all anymore. """ stream = self.set_up_stream_for_deletion("newstream") self.delete_stream(stream) def test_delete_private_stream(self) -> None: """ Administrators can delete private streams they are on. """ stream = self.set_up_stream_for_deletion("newstream", invite_only=True) self.delete_stream(stream) def test_delete_streams_youre_not_on(self) -> None: """ Administrators can delete public streams they aren't on, including private streams in their realm. """ pub_stream = self.set_up_stream_for_deletion( "pubstream", subscribed=False) self.delete_stream(pub_stream) priv_stream = self.set_up_stream_for_deletion( "privstream", subscribed=False, invite_only=True) self.delete_stream(priv_stream) def attempt_unsubscribe_of_principal(self, query_count: int, is_admin: bool=False, is_subbed: bool=True, invite_only: bool=False, other_user_subbed: bool=True, other_sub_users: Optional[List[UserProfile]]=None) -> HttpResponse: # Set up the main user, who is in most cases an admin. if is_admin: user_profile = self.example_user('iago') else: user_profile = self.example_user('hamlet') email = user_profile.email self.login(email) # Set up the stream. stream_name = u"hümbüǵ" self.make_stream(stream_name, invite_only=invite_only) # Set up the principal to be unsubscribed. other_user_profile = self.example_user('cordelia') other_email = other_user_profile.email # Subscribe the admin and/or principal as specified in the flags. if is_subbed: self.subscribe(user_profile, stream_name) if other_user_subbed: self.subscribe(other_user_profile, stream_name) if other_sub_users: for user in other_sub_users: self.subscribe(user, stream_name) with queries_captured() as queries: result = self.client_delete( "/json/users/me/subscriptions", {"subscriptions": ujson.dumps([stream_name]), "principals": ujson.dumps([other_email])}) self.assert_length(queries, query_count) # If the removal succeeded, then assert that Cordelia is no longer subscribed. if result.status_code not in [400]: subbed_users = self.users_subscribed_to_stream(stream_name, other_user_profile.realm) self.assertNotIn(other_user_profile, subbed_users) return result def test_cant_remove_others_from_stream(self) -> None: """ If you're not an admin, you can't remove other people from streams. """ result = self.attempt_unsubscribe_of_principal( query_count=3, is_admin=False, is_subbed=True, invite_only=False, other_user_subbed=True) self.assert_json_error( result, "This action requires administrative rights") def test_admin_remove_others_from_public_stream(self) -> None: """ If you're an admin, you can remove people from public streams, even those you aren't on. """ result = self.attempt_unsubscribe_of_principal( query_count=22, is_admin=True, is_subbed=True, invite_only=False, other_user_subbed=True) json = self.assert_json_success(result) self.assertEqual(len(json["removed"]), 1) self.assertEqual(len(json["not_subscribed"]), 0) def test_admin_remove_others_from_subbed_private_stream(self) -> None: """ If you're an admin, you can remove other people from private streams you are on. """ result = self.attempt_unsubscribe_of_principal( query_count=22, is_admin=True, is_subbed=True, invite_only=True, other_user_subbed=True) json = self.assert_json_success(result) self.assertEqual(len(json["removed"]), 1) self.assertEqual(len(json["not_subscribed"]), 0) def test_admin_remove_others_from_unsubbed_private_stream(self) -> None: """ If you're an admin, you can remove people from private streams you aren't on. """ result = self.attempt_unsubscribe_of_principal( query_count=22, is_admin=True, is_subbed=False, invite_only=True, other_user_subbed=True, other_sub_users=[self.example_user("othello")]) json = self.assert_json_success(result) self.assertEqual(len(json["removed"]), 1) self.assertEqual(len(json["not_subscribed"]), 0) def test_create_stream_by_admins_only_setting(self) -> None: """ When realm.create_stream_by_admins_only setting is active and the number of days since the user had joined is less than waiting period threshold, non admin users shouldn't be able to create new streams. """ user_profile = self.example_user('hamlet') email = user_profile.email self.login(email) do_set_realm_property(user_profile.realm, 'create_stream_by_admins_only', True) stream_name = ['adminsonlysetting'] result = self.common_subscribe_to_streams( email, stream_name ) self.assert_json_error(result, 'User cannot create streams.') def test_create_stream_by_waiting_period_threshold(self) -> None: """ Non admin users with account age greater or equal to waiting period threshold should be able to create new streams. """ user_profile = self.example_user('hamlet') user_profile.date_joined = timezone_now() user_profile.save() email = user_profile.email self.login(email) do_change_is_admin(user_profile, False) do_set_realm_property(user_profile.realm, 'waiting_period_threshold', 10) stream_name = ['waitingperiodtest'] result = self.common_subscribe_to_streams( email, stream_name ) self.assert_json_error(result, 'User cannot create streams.') do_set_realm_property(user_profile.realm, 'waiting_period_threshold', 0) result = self.common_subscribe_to_streams( email, stream_name ) self.assert_json_success(result) def test_remove_already_not_subbed(self) -> None: """ Trying to unsubscribe someone who already isn't subscribed to a stream fails gracefully. """ result = self.attempt_unsubscribe_of_principal( query_count=11, is_admin=True, is_subbed=False, invite_only=False, other_user_subbed=False) json = self.assert_json_success(result) self.assertEqual(len(json["removed"]), 0) self.assertEqual(len(json["not_subscribed"]), 1) def test_remove_invalid_user(self) -> None: """ Trying to unsubscribe an invalid user from a stream fails gracefully. """ user_profile = self.example_user('hamlet') admin_email = user_profile.email self.login(admin_email) do_change_is_admin(user_profile, True) stream_name = u"hümbüǵ" self.make_stream(stream_name) result = self.client_delete("/json/users/me/subscriptions", {"subscriptions": ujson.dumps([stream_name]), "principals": ujson.dumps(["baduser@zulip.com"])}) self.assert_json_error( result, "User not authorized to execute queries on behalf of 'baduser@zulip.com'", status_code=403) class DefaultStreamTest(ZulipTestCase): def get_default_stream_names(self, realm: Realm) -> Set[str]: streams = get_default_streams_for_realm(realm.id) stream_names = [s.name for s in streams] return set(stream_names) def get_default_stream_descriptions(self, realm: Realm) -> Set[str]: streams = get_default_streams_for_realm(realm.id) stream_descriptions = [s.description for s in streams] return set(stream_descriptions) def test_set_default_streams(self) -> None: realm = do_create_realm("testrealm", "Test Realm") stream_dict = { "apple": {"description": "A red fruit", "invite_only": False}, "banana": {"description": "A yellow fruit", "invite_only": False}, "Carrot Cake": {"description": "A delicious treat", "invite_only": False} } # type: Dict[str, Dict[str, Any]] expected_names = list(stream_dict.keys()) expected_names.append("announce") expected_descriptions = [i["description"] for i in stream_dict.values()] + [""] set_default_streams(realm, stream_dict) stream_names_set = self.get_default_stream_names(realm) stream_descriptions_set = self.get_default_stream_descriptions(realm) self.assertEqual(stream_names_set, set(expected_names)) self.assertEqual(stream_descriptions_set, set(expected_descriptions)) def test_set_default_streams_no_notifications_stream(self) -> None: realm = do_create_realm("testrealm", "Test Realm") realm.notifications_stream = None realm.save(update_fields=["notifications_stream"]) stream_dict = { "apple": {"description": "A red fruit", "invite_only": False}, "banana": {"description": "A yellow fruit", "invite_only": False}, "Carrot Cake": {"description": "A delicious treat", "invite_only": False} } # type: Dict[str, Dict[str, Any]] expected_names = list(stream_dict.keys()) expected_descriptions = [i["description"] for i in stream_dict.values()] set_default_streams(realm, stream_dict) stream_names_set = self.get_default_stream_names(realm) stream_descriptions_set = self.get_default_stream_descriptions(realm) self.assertEqual(stream_names_set, set(expected_names)) self.assertEqual(stream_descriptions_set, set(expected_descriptions)) def test_add_and_remove_default_stream(self) -> None: realm = get_realm("zulip") stream = ensure_stream(realm, "Added Stream") orig_stream_names = self.get_default_stream_names(realm) do_add_default_stream(stream) new_stream_names = self.get_default_stream_names(realm) added_stream_names = new_stream_names - orig_stream_names self.assertEqual(added_stream_names, set(['Added Stream'])) # idempotentcy--2nd call to add_default_stream should be a noop do_add_default_stream(stream) self.assertEqual(self.get_default_stream_names(realm), new_stream_names) # start removing do_remove_default_stream(stream) self.assertEqual(self.get_default_stream_names(realm), orig_stream_names) # idempotentcy--2nd call to remove_default_stream should be a noop do_remove_default_stream(stream) self.assertEqual(self.get_default_stream_names(realm), orig_stream_names) def test_api_calls(self) -> None: user_profile = self.example_user('hamlet') do_change_is_admin(user_profile, True) self.login(user_profile.email) stream_name = 'stream ADDED via api' ensure_stream(user_profile.realm, stream_name) result = self.client_post('/json/default_streams', dict(stream_name=stream_name)) self.assert_json_success(result) self.assertTrue(stream_name in self.get_default_stream_names(user_profile.realm)) # look for it self.subscribe(user_profile, stream_name) payload = dict( include_public='true', include_default='true', ) result = self.client_get('/json/streams', payload) self.assert_json_success(result) streams = result.json()['streams'] default_streams = { stream['name'] for stream in streams if stream['is_default'] } self.assertEqual(default_streams, {stream_name}) other_streams = { stream['name'] for stream in streams if not stream['is_default'] } self.assertTrue(len(other_streams) > 0) # and remove it result = self.client_delete('/json/default_streams', dict(stream_name=stream_name)) self.assert_json_success(result) self.assertFalse(stream_name in self.get_default_stream_names(user_profile.realm)) # Test admin can't add unsubscribed private stream stream_name = "private_stream" self.make_stream(stream_name, invite_only=True) self.subscribe(self.example_user('iago'), stream_name) result = self.client_post('/json/default_streams', dict(stream_name=stream_name)) self.assert_json_error(result, "Invalid stream name '%s'" % (stream_name)) self.subscribe(user_profile, stream_name) result = self.client_post('/json/default_streams', dict(stream_name=stream_name)) self.assert_json_success(result) self.assertTrue(stream_name in self.get_default_stream_names(user_profile.realm)) # Test admin can remove unsubscribed private stream self.unsubscribe(user_profile, stream_name) result = self.client_delete('/json/default_streams', dict(stream_name=stream_name)) self.assert_json_success(result) self.assertFalse(stream_name in self.get_default_stream_names(user_profile.realm)) class DefaultStreamGroupTest(ZulipTestCase): def test_create_update_and_remove_default_stream_group(self) -> None: realm = get_realm("zulip") # Test creating new default stream group default_stream_groups = get_default_stream_groups(realm) self.assert_length(default_stream_groups, 0) streams = [] for stream_name in ["stream1", "stream2", "stream3"]: stream = ensure_stream(realm, stream_name) streams.append(stream) def get_streams(group: DefaultStreamGroup) -> List[Stream]: return list(group.streams.all().order_by('name')) group_name = "group1" description = "This is group1" do_create_default_stream_group(realm, group_name, description, streams) default_stream_groups = get_default_stream_groups(realm) self.assert_length(default_stream_groups, 1) self.assertEqual(default_stream_groups[0].name, group_name) self.assertEqual(default_stream_groups[0].description, description) self.assertEqual(get_streams(default_stream_groups[0]), streams) # Test adding streams to existing default stream group group = lookup_default_stream_groups(["group1"], realm)[0] new_stream_names = ["stream4", "stream5"] new_streams = [] for new_stream_name in new_stream_names: new_stream = ensure_stream(realm, new_stream_name) new_streams.append(new_stream) streams.append(new_stream) do_add_streams_to_default_stream_group(realm, group, new_streams) default_stream_groups = get_default_stream_groups(realm) self.assert_length(default_stream_groups, 1) self.assertEqual(default_stream_groups[0].name, group_name) self.assertEqual(get_streams(default_stream_groups[0]), streams) # Test removing streams from existing default stream group do_remove_streams_from_default_stream_group(realm, group, new_streams) remaining_streams = streams[0:3] default_stream_groups = get_default_stream_groups(realm) self.assert_length(default_stream_groups, 1) self.assertEqual(default_stream_groups[0].name, group_name) self.assertEqual(get_streams(default_stream_groups[0]), remaining_streams) # Test changing default stream group description new_description = "group1 new description" do_change_default_stream_group_description(realm, group, new_description) default_stream_groups = get_default_stream_groups(realm) self.assertEqual(default_stream_groups[0].description, new_description) self.assert_length(default_stream_groups, 1) # Test changing default stream group name new_group_name = "new group1" do_change_default_stream_group_name(realm, group, new_group_name) default_stream_groups = get_default_stream_groups(realm) self.assert_length(default_stream_groups, 1) self.assertEqual(default_stream_groups[0].name, new_group_name) self.assertEqual(get_streams(default_stream_groups[0]), remaining_streams) # Test removing default stream group do_remove_default_stream_group(realm, group) default_stream_groups = get_default_stream_groups(realm) self.assert_length(default_stream_groups, 0) # Test creating a default stream group which contains a default stream do_add_default_stream(remaining_streams[0]) with self.assertRaisesRegex( JsonableError, "'stream1' is a default stream and cannot be added to 'new group1'"): do_create_default_stream_group(realm, new_group_name, "This is group1", remaining_streams) def test_api_calls(self) -> None: self.login(self.example_email("hamlet")) user_profile = self.example_user('hamlet') realm = user_profile.realm do_change_is_admin(user_profile, True) # Test creating new default stream group stream_names = ["stream1", "stream2", "stream3"] group_name = "group1" description = "This is group1" streams = [] default_stream_groups = get_default_stream_groups(realm) self.assert_length(default_stream_groups, 0) for stream_name in stream_names: stream = ensure_stream(realm, stream_name) streams.append(stream) result = self.client_post('/json/default_stream_groups/create', {"group_name": group_name, "description": description, "stream_names": ujson.dumps(stream_names)}) self.assert_json_success(result) default_stream_groups = get_default_stream_groups(realm) self.assert_length(default_stream_groups, 1) self.assertEqual(default_stream_groups[0].name, group_name) self.assertEqual(default_stream_groups[0].description, description) self.assertEqual(list(default_stream_groups[0].streams.all().order_by("id")), streams) # Try adding the same streams to the group. result = self.client_post('/json/default_stream_groups/create', {"group_name": group_name, "description": description, "stream_names": ujson.dumps(stream_names)}) self.assert_json_error(result, "Default stream group 'group1' already exists") # Test adding streams to existing default stream group group_id = default_stream_groups[0].id new_stream_names = ["stream4", "stream5"] new_streams = [] for new_stream_name in new_stream_names: new_stream = ensure_stream(realm, new_stream_name) new_streams.append(new_stream) streams.append(new_stream) result = self.client_patch("/json/default_stream_groups/{}/streams".format(group_id), {"stream_names": ujson.dumps(new_stream_names)}) self.assert_json_error(result, "Missing 'op' argument") result = self.client_patch("/json/default_stream_groups/{}/streams".format(group_id), {"op": "invalid", "stream_names": ujson.dumps(new_stream_names)}) self.assert_json_error(result, 'Invalid value for "op". Specify one of "add" or "remove".') result = self.client_patch("/json/default_stream_groups/12345/streams", {"op": "add", "stream_names": ujson.dumps(new_stream_names)}) self.assert_json_error(result, "Default stream group with id '12345' does not exist.") result = self.client_patch("/json/default_stream_groups/{}/streams".format(group_id), {"op": "add"}) self.assert_json_error(result, "Missing 'stream_names' argument") do_add_default_stream(new_streams[0]) result = self.client_patch("/json/default_stream_groups/{}/streams".format(group_id), {"op": "add", "stream_names": ujson.dumps(new_stream_names)}) self.assert_json_error(result, "'stream4' is a default stream and cannot be added to 'group1'") do_remove_default_stream(new_streams[0]) result = self.client_patch("/json/default_stream_groups/{}/streams".format(group_id), {"op": "add", "stream_names": ujson.dumps(new_stream_names)}) self.assert_json_success(result) default_stream_groups = get_default_stream_groups(realm) self.assert_length(default_stream_groups, 1) self.assertEqual(default_stream_groups[0].name, group_name) self.assertEqual(list(default_stream_groups[0].streams.all().order_by('name')), streams) result = self.client_patch("/json/default_stream_groups/{}/streams".format(group_id), {"op": "add", "stream_names": ujson.dumps(new_stream_names)}) self.assert_json_error(result, "Stream 'stream4' is already present in default stream group 'group1'") # Test removing streams from default stream group result = self.client_patch("/json/default_stream_groups/12345/streams", {"op": "remove", "stream_names": ujson.dumps(new_stream_names)}) self.assert_json_error(result, "Default stream group with id '12345' does not exist.") result = self.client_patch("/json/default_stream_groups/{}/streams".format(group_id), {"op": "remove", "stream_names": ujson.dumps(["random stream name"])}) self.assert_json_error(result, "Invalid stream name 'random stream name'") streams.remove(new_streams[0]) result = self.client_patch("/json/default_stream_groups/{}/streams".format(group_id), {"op": "remove", "stream_names": ujson.dumps([new_stream_names[0]])}) self.assert_json_success(result) default_stream_groups = get_default_stream_groups(realm) self.assert_length(default_stream_groups, 1) self.assertEqual(default_stream_groups[0].name, group_name) self.assertEqual(list(default_stream_groups[0].streams.all().order_by('name')), streams) result = self.client_patch("/json/default_stream_groups/{}/streams".format(group_id), {"op": "remove", "stream_names": ujson.dumps(new_stream_names)}) self.assert_json_error(result, "Stream 'stream4' is not present in default stream group 'group1'") # Test changing description of default stream group new_description = "new group1 description" result = self.client_patch("/json/default_stream_groups/{}".format(group_id), {"group_name": group_name, "op": "change"}) self.assert_json_error(result, 'You must pass "new_description" or "new_group_name".') result = self.client_patch("/json/default_stream_groups/12345", {"op": "change", "new_description": ujson.dumps(new_description)}) self.assert_json_error(result, "Default stream group with id '12345' does not exist.") result = self.client_patch("/json/default_stream_groups/{}".format(group_id), {"group_name": group_name, "op": "change", "new_description": ujson.dumps(new_description)}) self.assert_json_success(result) default_stream_groups = get_default_stream_groups(realm) self.assert_length(default_stream_groups, 1) self.assertEqual(default_stream_groups[0].name, group_name) self.assertEqual(default_stream_groups[0].description, new_description) # Test changing name of default stream group new_group_name = "new group1" do_create_default_stream_group(realm, "group2", "", []) result = self.client_patch("/json/default_stream_groups/{}".format(group_id), {"op": "change", "new_group_name": ujson.dumps("group2")}) self.assert_json_error(result, "Default stream group 'group2' already exists") new_group = lookup_default_stream_groups(["group2"], realm)[0] do_remove_default_stream_group(realm, new_group) result = self.client_patch("/json/default_stream_groups/{}".format(group_id), {"op": "change", "new_group_name": ujson.dumps(group_name)}) self.assert_json_error(result, "This default stream group is already named 'group1'") result = self.client_patch("/json/default_stream_groups/{}".format(group_id), {"op": "change", "new_group_name": ujson.dumps(new_group_name)}) self.assert_json_success(result) default_stream_groups = get_default_stream_groups(realm) self.assert_length(default_stream_groups, 1) self.assertEqual(default_stream_groups[0].name, new_group_name) self.assertEqual(default_stream_groups[0].description, new_description) # Test deleting a default stream group result = self.client_delete('/json/default_stream_groups/{}'.format(group_id)) self.assert_json_success(result) default_stream_groups = get_default_stream_groups(realm) self.assert_length(default_stream_groups, 0) result = self.client_delete('/json/default_stream_groups/{}'.format(group_id)) self.assert_json_error(result, "Default stream group with id '{}' does not exist.".format(group_id)) def test_invalid_default_stream_group_name(self) -> None: self.login(self.example_email("iago")) user_profile = self.example_user('iago') realm = user_profile.realm stream_names = ["stream1", "stream2", "stream3"] description = "This is group1" streams = [] for stream_name in stream_names: stream = ensure_stream(realm, stream_name) streams.append(stream) result = self.client_post('/json/default_stream_groups/create', {"group_name": "", "description": description, "stream_names": ujson.dumps(stream_names)}) self.assert_json_error(result, "Invalid default stream group name ''") result = self.client_post('/json/default_stream_groups/create', {"group_name": 'x'*100, "description": description, "stream_names": ujson.dumps(stream_names)}) self.assert_json_error(result, "Default stream group name too long (limit: {} characters)" .format((DefaultStreamGroup.MAX_NAME_LENGTH))) result = self.client_post('/json/default_stream_groups/create', {"group_name": "abc\000", "description": description, "stream_names": ujson.dumps(stream_names)}) self.assert_json_error(result, "Default stream group name 'abc\000' contains NULL (0x00) characters.") # Also test that lookup_default_stream_groups raises an # error if we pass it a bad name. This function is used # during registration, but it's a bit heavy to do a full # test of that. with self.assertRaisesRegex(JsonableError, 'Invalid default stream group invalid-name'): lookup_default_stream_groups(['invalid-name'], realm) class SubscriptionPropertiesTest(ZulipTestCase): def test_set_stream_color(self) -> None: """ A POST request to /api/v1/users/me/subscriptions/properties with stream_id and color data sets the stream color, and for that stream only. """ test_user = self.example_user('hamlet') test_email = test_user.email test_realm = test_user.realm self.login(test_email) old_subs, _ = gather_subscriptions(test_user) sub = old_subs[0] stream_id = sub['stream_id'] new_color = "#ffffff" # TODO: ensure that this is different from old_color result = self.api_post(test_email, "/api/v1/users/me/subscriptions/properties", {"subscription_data": ujson.dumps([{"property": "color", "stream_id": stream_id, "value": "#ffffff"}])}) self.assert_json_success(result) new_subs = gather_subscriptions(get_user(test_email, test_realm))[0] found_sub = None for sub in new_subs: if sub['stream_id'] == stream_id: found_sub = sub break assert(found_sub is not None) self.assertEqual(found_sub['color'], new_color) new_subs.remove(found_sub) for sub in old_subs: if sub['stream_id'] == stream_id: found_sub = sub break old_subs.remove(found_sub) self.assertEqual(old_subs, new_subs) def test_set_color_missing_stream_id(self) -> None: """ Updating the color property requires a `stream_id` key. """ test_user = self.example_user('hamlet') test_email = test_user.email self.login(test_email) result = self.api_post(test_email, "/api/v1/users/me/subscriptions/properties", {"subscription_data": ujson.dumps([{"property": "color", "value": "#ffffff"}])}) self.assert_json_error( result, "stream_id key is missing from subscription_data[0]") def test_set_color_unsubscribed_stream_id(self) -> None: """ Updating the color property requires a subscribed stream. """ test_email = self.example_email("hamlet") self.login(test_email) test_realm = get_realm("zulip") subscribed, unsubscribed, never_subscribed = gather_subscriptions_helper( get_user(test_email, test_realm)) not_subbed = unsubscribed + never_subscribed result = self.api_post(test_email, "/api/v1/users/me/subscriptions/properties", {"subscription_data": ujson.dumps([{"property": "color", "stream_id": not_subbed[0]["stream_id"], "value": "#ffffff"}])}) self.assert_json_error( result, "Not subscribed to stream id %d" % (not_subbed[0]["stream_id"],)) def test_set_color_missing_color(self) -> None: """ Updating the color property requires a color. """ test_user = self.example_user('hamlet') test_email = test_user.email self.login(test_email) subs = gather_subscriptions(test_user)[0] result = self.api_post(test_email, "/api/v1/users/me/subscriptions/properties", {"subscription_data": ujson.dumps([{"property": "color", "stream_id": subs[0]["stream_id"]}])}) self.assert_json_error( result, "value key is missing from subscription_data[0]") def test_set_pin_to_top(self) -> None: """ A POST request to /api/v1/users/me/subscriptions/properties with stream_id and pin_to_top data pins the stream. """ user_profile = self.example_user('hamlet') test_email = user_profile.email self.login(test_email) old_subs, _ = gather_subscriptions(user_profile) sub = old_subs[0] stream_id = sub['stream_id'] new_pin_to_top = not sub['pin_to_top'] result = self.api_post(test_email, "/api/v1/users/me/subscriptions/properties", {"subscription_data": ujson.dumps([{"property": "pin_to_top", "stream_id": stream_id, "value": new_pin_to_top}])}) self.assert_json_success(result) updated_sub = get_subscription(sub['name'], user_profile) self.assertIsNotNone(updated_sub) self.assertEqual(updated_sub.pin_to_top, new_pin_to_top) def test_set_subscription_property_incorrect(self) -> None: """ Trying to set a property incorrectly returns a JSON error. """ test_user = self.example_user('hamlet') test_email = test_user.email self.login(test_email) subs = gather_subscriptions(test_user)[0] property_name = "in_home_view" result = self.api_post(test_email, "/api/v1/users/me/subscriptions/properties", {"subscription_data": ujson.dumps([{"property": property_name, "value": "bad", "stream_id": subs[0]["stream_id"]}])}) self.assert_json_error(result, '%s is not a boolean' % (property_name,)) property_name = "desktop_notifications" result = self.api_post(test_email, "/api/v1/users/me/subscriptions/properties", {"subscription_data": ujson.dumps([{"property": property_name, "value": "bad", "stream_id": subs[0]["stream_id"]}])}) self.assert_json_error(result, '%s is not a boolean' % (property_name,)) property_name = "audible_notifications" result = self.api_post(test_email, "/api/v1/users/me/subscriptions/properties", {"subscription_data": ujson.dumps([{"property": property_name, "value": "bad", "stream_id": subs[0]["stream_id"]}])}) self.assert_json_error(result, '%s is not a boolean' % (property_name,)) property_name = "push_notifications" result = self.api_post(test_email, "/api/v1/users/me/subscriptions/properties", {"subscription_data": ujson.dumps([{"property": property_name, "value": "bad", "stream_id": subs[0]["stream_id"]}])}) self.assert_json_error(result, '%s is not a boolean' % (property_name,)) property_name = "email_notifications" result = self.api_post(test_email, "/api/v1/users/me/subscriptions/properties", {"subscription_data": ujson.dumps([{"property": property_name, "value": "bad", "stream_id": subs[0]["stream_id"]}])}) self.assert_json_error(result, '%s is not a boolean' % (property_name,)) property_name = "color" result = self.api_post(test_email, "/api/v1/users/me/subscriptions/properties", {"subscription_data": ujson.dumps([{"property": property_name, "value": False, "stream_id": subs[0]["stream_id"]}])}) self.assert_json_error(result, '%s is not a string' % (property_name,)) def test_json_subscription_property_invalid_stream(self) -> None: test_email = self.example_email("hamlet") self.login(test_email) stream_id = 1000 result = self.api_post(test_email, "/api/v1/users/me/subscriptions/properties", {"subscription_data": ujson.dumps([{"property": "in_home_view", "stream_id": stream_id, "value": False}])}) self.assert_json_error(result, "Invalid stream id") def test_set_invalid_property(self) -> None: """ Trying to set an invalid property returns a JSON error. """ test_user = self.example_user('hamlet') test_email = test_user.email self.login(test_email) subs = gather_subscriptions(test_user)[0] result = self.api_post(test_email, "/api/v1/users/me/subscriptions/properties", {"subscription_data": ujson.dumps([{"property": "bad", "value": "bad", "stream_id": subs[0]["stream_id"]}])}) self.assert_json_error(result, "Unknown subscription property: bad") class SubscriptionRestApiTest(ZulipTestCase): def test_basic_add_delete(self) -> None: email = self.example_email('hamlet') realm = self.example_user('hamlet').realm self.login(email) # add request = { 'add': ujson.dumps([{'name': 'my_test_stream_1'}]) } result = self.api_patch(email, "/api/v1/users/me/subscriptions", request) self.assert_json_success(result) streams = self.get_streams(email, realm) self.assertTrue('my_test_stream_1' in streams) # now delete the same stream request = { 'delete': ujson.dumps(['my_test_stream_1']) } result = self.api_patch(email, "/api/v1/users/me/subscriptions", request) self.assert_json_success(result) streams = self.get_streams(email, realm) self.assertTrue('my_test_stream_1' not in streams) def test_api_valid_property(self) -> None: """ Trying to set valid json returns success message. """ test_user = self.example_user('hamlet') test_email = test_user.email self.login(test_email) subs = gather_subscriptions(test_user)[0] result = self.api_patch(test_email, "/api/v1/users/me/subscriptions/%d" % subs[0]["stream_id"], {'property': 'color', 'value': '#c2c2c2'}) self.assert_json_success(result) def test_api_invalid_property(self) -> None: """ Trying to set an invalid property returns a JSON error. """ test_user = self.example_user('hamlet') test_email = test_user.email self.login(test_email) subs = gather_subscriptions(test_user)[0] result = self.api_patch(test_email, "/api/v1/users/me/subscriptions/%d" % subs[0]["stream_id"], {'property': 'invalid', 'value': 'somevalue'}) self.assert_json_error(result, "Unknown subscription property: invalid") def test_api_invalid_stream_id(self) -> None: """ Trying to set an invalid stream id returns a JSON error. """ test_email = self.example_email("hamlet") self.login(test_email) result = self.api_patch(test_email, "/api/v1/users/me/subscriptions/121", {'property': 'in_home_view', 'value': 'somevalue'}) self.assert_json_error(result, "Invalid stream id") def test_bad_add_parameters(self) -> None: email = self.example_email('hamlet') self.login(email) def check_for_error(val: Any, expected_message: str) -> None: request = { 'add': ujson.dumps(val) } result = self.api_patch(email, "/api/v1/users/me/subscriptions", request) self.assert_json_error(result, expected_message) check_for_error(['foo'], 'add[0] is not a dict') check_for_error([{'bogus': 'foo'}], 'name key is missing from add[0]') check_for_error([{'name': {}}], 'add[0]["name"] is not a string') def test_bad_principals(self) -> None: email = self.example_email('hamlet') self.login(email) request = { 'add': ujson.dumps([{'name': 'my_new_stream'}]), 'principals': ujson.dumps([{}]), } result = self.api_patch(email, "/api/v1/users/me/subscriptions", request) self.assert_json_error(result, 'principals[0] is not a string') def test_bad_delete_parameters(self) -> None: email = self.example_email('hamlet') self.login(email) request = { 'delete': ujson.dumps([{'name': 'my_test_stream_1'}]) } result = self.api_patch(email, "/api/v1/users/me/subscriptions", request) self.assert_json_error(result, "delete[0] is not a string") def test_add_or_delete_not_specified(self) -> None: email = self.example_email('hamlet') self.login(email) result = self.api_patch(email, "/api/v1/users/me/subscriptions", {}) self.assert_json_error(result, 'Nothing to do. Specify at least one of "add" or "delete".') def test_patch_enforces_valid_stream_name_check(self) -> None: """ Only way to force an error is with a empty string. """ email = self.example_email('hamlet') self.login(email) invalid_stream_name = "" request = { 'delete': ujson.dumps([invalid_stream_name]) } result = self.api_patch(email, "/api/v1/users/me/subscriptions", request) self.assert_json_error(result, "Invalid stream name '%s'" % (invalid_stream_name,)) def test_stream_name_too_long(self) -> None: email = self.example_email('hamlet') self.login(email) long_stream_name = "a" * 61 request = { 'delete': ujson.dumps([long_stream_name]) } result = self.api_patch(email, "/api/v1/users/me/subscriptions", request) self.assert_json_error(result, "Stream name too long (limit: 60 characters).") def test_stream_name_contains_null(self) -> None: email = self.example_email('hamlet') self.login(email) stream_name = "abc\000" request = { 'delete': ujson.dumps([stream_name]) } result = self.api_patch(email, "/api/v1/users/me/subscriptions", request) self.assert_json_error(result, "Stream name '%s' contains NULL (0x00) characters." % (stream_name)) def test_compose_views_rollback(self) -> None: ''' The compose_views function() is used under the hood by update_subscriptions_backend. It's a pretty simple method in terms of control flow, but it uses a Django rollback, which may make it brittle code when we upgrade Django. We test the functions's rollback logic here with a simple scenario to avoid false positives related to subscription complications. ''' user_profile = self.example_user('hamlet') user_profile.full_name = 'Hamlet' user_profile.save() def method1(req: HttpRequest, user_profile: UserProfile) -> HttpResponse: user_profile.full_name = 'Should not be committed' user_profile.save() return json_success() def method2(req: HttpRequest, user_profile: UserProfile) -> HttpResponse: return json_error('random failure') with self.assertRaises(JsonableError): compose_views(None, user_profile, [(method1, {}), (method2, {})]) user_profile = self.example_user('hamlet') self.assertEqual(user_profile.full_name, 'Hamlet') class SubscriptionAPITest(ZulipTestCase): def setUp(self) -> None: """ All tests will be logged in as hamlet. Also save various useful values as attributes that tests can access. """ self.user_profile = self.example_user('hamlet') self.test_email = self.user_profile.email self.test_user = self.user_profile self.login(self.test_email) self.test_realm = self.user_profile.realm self.streams = self.get_streams(self.test_email, self.test_realm) def make_random_stream_names(self, existing_stream_names: List[str]) -> List[str]: """ Helper function to make up random stream names. It takes existing_stream_names and randomly appends a digit to the end of each, but avoids names that appear in the list names_to_avoid. """ random_streams = [] all_stream_names = [stream.name for stream in Stream.objects.filter(realm=self.test_realm)] for stream in existing_stream_names: random_stream = stream + str(random.randint(0, 9)) if random_stream not in all_stream_names: random_streams.append(random_stream) return random_streams def test_successful_subscriptions_list(self) -> None: """ Calling /api/v1/users/me/subscriptions should successfully return your subscriptions. """ email = self.test_email result = self.api_get(email, "/api/v1/users/me/subscriptions") self.assert_json_success(result) json = result.json() self.assertIn("subscriptions", json) for stream in json['subscriptions']: self.assertIsInstance(stream['name'], str) self.assertIsInstance(stream['color'], str) self.assertIsInstance(stream['invite_only'], bool) # check that the stream name corresponds to an actual # stream; will throw Stream.DoesNotExist if it doesn't get_stream(stream['name'], self.test_realm) list_streams = [stream['name'] for stream in json["subscriptions"]] # also check that this matches the list of your subscriptions self.assertEqual(sorted(list_streams), sorted(self.streams)) def helper_check_subs_before_and_after_add(self, subscriptions: List[str], other_params: Dict[str, Any], subscribed: List[str], already_subscribed: List[str], email: str, new_subs: List[str], realm: Realm, invite_only: bool=False) -> None: """ Check result of adding subscriptions. You can add subscriptions for yourself or possibly many principals, which is why e-mails map to subscriptions in the result. The result json is of the form {"msg": "", "result": "success", "already_subscribed": {self.example_email("iago"): ["Venice", "Verona"]}, "subscribed": {self.example_email("iago"): ["Venice8"]}} """ result = self.common_subscribe_to_streams(self.test_email, subscriptions, other_params, invite_only=invite_only) self.assert_json_success(result) json = result.json() self.assertEqual(sorted(subscribed), sorted(json["subscribed"][email])) self.assertEqual(sorted(already_subscribed), sorted(json["already_subscribed"][email])) new_streams = self.get_streams(email, realm) self.assertEqual(sorted(new_streams), sorted(new_subs)) def test_successful_subscriptions_add(self) -> None: """ Calling POST /json/users/me/subscriptions should successfully add streams, and should determine which are new subscriptions vs which were already subscribed. We add 2 new streams to the list of subscriptions and confirm the right number of events are generated. """ self.assertNotEqual(len(self.streams), 0) # necessary for full test coverage add_streams = [u"Verona2", u"Denmark5"] self.assertNotEqual(len(add_streams), 0) # necessary for full test coverage events = [] # type: List[Mapping[str, Any]] with tornado_redirected_to_list(events): self.helper_check_subs_before_and_after_add(self.streams + add_streams, {}, add_streams, self.streams, self.test_email, self.streams + add_streams, self.test_realm) self.assert_length(events, 8) def test_successful_subscriptions_add_with_announce(self) -> None: """ Calling POST /json/users/me/subscriptions should successfully add streams, and should determine which are new subscriptions vs which were already subscribed. We add 2 new streams to the list of subscriptions and confirm the right number of events are generated. """ self.assertNotEqual(len(self.streams), 0) add_streams = [u"Verona2", u"Denmark5"] self.assertNotEqual(len(add_streams), 0) events = [] # type: List[Mapping[str, Any]] other_params = { 'announce': 'true', } notifications_stream = get_stream(self.streams[0], self.test_realm) self.test_realm.notifications_stream_id = notifications_stream.id self.test_realm.save() # Delete the UserProfile from the cache so the realm change will be # picked up cache.cache_delete(cache.user_profile_by_email_cache_key(self.test_email)) with tornado_redirected_to_list(events): self.helper_check_subs_before_and_after_add(self.streams + add_streams, other_params, add_streams, self.streams, self.test_email, self.streams + add_streams, self.test_realm) self.assertEqual(len(events), 9) def test_successful_subscriptions_notifies_pm(self) -> None: """ Calling POST /json/users/me/subscriptions should notify when a new stream is created. """ invitee = self.example_email("iago") current_stream = self.get_streams(invitee, self.test_realm)[0] invite_streams = self.make_random_stream_names([current_stream])[:1] result = self.common_subscribe_to_streams( invitee, invite_streams, extra_post_data={ 'announce': 'true', 'principals': '["%s"]' % (self.user_profile.email,) }, ) self.assert_json_success(result) def test_successful_subscriptions_notifies_stream(self) -> None: """ Calling POST /json/users/me/subscriptions should notify when a new stream is created. """ invitee = self.example_email("iago") invitee_full_name = 'Iago' current_stream = self.get_streams(invitee, self.test_realm)[0] invite_streams = self.make_random_stream_names([current_stream])[:1] notifications_stream = get_stream(current_stream, self.test_realm) self.test_realm.notifications_stream_id = notifications_stream.id self.test_realm.save() # Delete the UserProfile from the cache so the realm change will be # picked up cache.cache_delete(cache.user_profile_by_email_cache_key(invitee)) result = self.common_subscribe_to_streams( invitee, invite_streams, extra_post_data=dict( announce='true', principals='["%s"]' % (self.user_profile.email,) ), ) self.assert_json_success(result) msg = self.get_second_to_last_message() self.assertEqual(msg.recipient.type, Recipient.STREAM) self.assertEqual(msg.sender_id, self.notification_bot().id) expected_msg = "%s just created a new stream #**%s**." % (invitee_full_name, invite_streams[0]) self.assertEqual(msg.content, expected_msg) def test_successful_cross_realm_notification(self) -> None: """ Calling POST /json/users/me/subscriptions in a new realm should notify with a proper new stream link """ realm = do_create_realm("testrealm", "Test Realm") notifications_stream = Stream.objects.get(name='announce', realm=realm) realm.notifications_stream = notifications_stream realm.save() invite_streams = ["cross_stream"] user = self.example_user('AARON') user.realm = realm user.save() # Delete the UserProfile from the cache so the realm change will be # picked up cache.cache_delete(cache.user_profile_by_email_cache_key(user.email)) result = self.common_subscribe_to_streams( user.email, invite_streams, extra_post_data=dict( announce='true' ), subdomain="testrealm", ) self.assert_json_success(result) msg = self.get_second_to_last_message() self.assertEqual(msg.recipient.type, Recipient.STREAM) self.assertEqual(msg.sender_id, self.notification_bot().id) stream_id = Stream.objects.latest('id').id expected_rendered_msg = '<p>%s just created a new stream <a class="stream" data-stream-id="%d" href="/#narrow/stream/%s-%s">#%s</a>.</p>' % ( user.full_name, stream_id, stream_id, invite_streams[0], invite_streams[0]) self.assertEqual(msg.rendered_content, expected_rendered_msg) def test_successful_subscriptions_notifies_with_escaping(self) -> None: """ Calling POST /json/users/me/subscriptions should notify when a new stream is created. """ invitee = self.example_email("iago") invitee_full_name = 'Iago' current_stream = self.get_streams(invitee, self.test_realm)[0] notifications_stream = get_stream(current_stream, self.test_realm) self.test_realm.notifications_stream_id = notifications_stream.id self.test_realm.save() invite_streams = ['strange ) \\ test'] result = self.common_subscribe_to_streams( invitee, invite_streams, extra_post_data={ 'announce': 'true', 'principals': '["%s"]' % (self.user_profile.email,) }, ) self.assert_json_success(result) msg = self.get_second_to_last_message() self.assertEqual(msg.sender_id, self.notification_bot().id) expected_msg = "%s just created a new stream #**%s**." % (invitee_full_name, invite_streams[0]) self.assertEqual(msg.content, expected_msg) def test_non_ascii_stream_subscription(self) -> None: """ Subscribing to a stream name with non-ASCII characters succeeds. """ self.helper_check_subs_before_and_after_add(self.streams + [u"hümbüǵ"], {}, [u"hümbüǵ"], self.streams, self.test_email, self.streams + [u"hümbüǵ"], self.test_realm) def test_subscriptions_add_too_long(self) -> None: """ Calling POST /json/users/me/subscriptions on a stream whose name is >60 characters should return a JSON error. """ # character limit is 60 characters long_stream_name = "a" * 61 result = self.common_subscribe_to_streams(self.test_email, [long_stream_name]) self.assert_json_error(result, "Stream name too long (limit: 60 characters).") def test_subscriptions_add_stream_with_null(self) -> None: """ Calling POST /json/users/me/subscriptions on a stream whose name contains null characters should return a JSON error. """ stream_name = "abc\000" result = self.common_subscribe_to_streams(self.test_email, [stream_name]) self.assert_json_error(result, "Stream name '%s' contains NULL (0x00) characters." % (stream_name)) def test_user_settings_for_adding_streams(self) -> None: with mock.patch('zerver.models.UserProfile.can_create_streams', return_value=False): result = self.common_subscribe_to_streams(self.test_email, ['stream1']) self.assert_json_error(result, 'User cannot create streams.') with mock.patch('zerver.models.UserProfile.can_create_streams', return_value=True): result = self.common_subscribe_to_streams(self.test_email, ['stream2']) self.assert_json_success(result) # User should still be able to subscribe to an existing stream with mock.patch('zerver.models.UserProfile.can_create_streams', return_value=False): result = self.common_subscribe_to_streams(self.test_email, ['stream2']) self.assert_json_success(result) def test_can_create_streams(self) -> None: othello = self.example_user('othello') othello.is_realm_admin = True self.assertTrue(othello.can_create_streams()) othello.is_realm_admin = False othello.realm.create_stream_by_admins_only = True self.assertFalse(othello.can_create_streams()) othello.realm.create_stream_by_admins_only = False othello.is_guest = True self.assertFalse(othello.can_create_streams()) othello.is_guest = False othello.realm.waiting_period_threshold = 1000 othello.date_joined = timezone_now() - timedelta(days=(othello.realm.waiting_period_threshold - 1)) self.assertFalse(othello.can_create_streams()) othello.date_joined = timezone_now() - timedelta(days=(othello.realm.waiting_period_threshold + 1)) self.assertTrue(othello.can_create_streams()) def test_user_settings_for_subscribing_other_users(self) -> None: """ You can't subscribe other people to streams if you are a guest or your waiting period is not over. """ invitee_email = self.example_email("cordelia") with mock.patch('zerver.models.UserProfile.can_subscribe_other_users', return_value=False): result = self.common_subscribe_to_streams(self.test_email, ['stream1'], {"principals": ujson.dumps([invitee_email])}) self.assert_json_error(result, "Your account is too new to modify other users' subscriptions.") with mock.patch('zerver.models.UserProfile.can_subscribe_other_users', return_value=True): result = self.common_subscribe_to_streams(self.test_email, ['stream2'], {"principals": ujson.dumps([invitee_email])}) self.assert_json_success(result) def test_can_subscribe_other_users(self) -> None: """ You can't subscribe other people to streams if you are a guest or your waiting period is not over. """ othello = self.example_user('othello') othello.is_realm_admin = True self.assertTrue(othello.can_subscribe_other_users()) othello.is_realm_admin = False othello.is_guest = True self.assertFalse(othello.can_subscribe_other_users()) othello.is_guest = False othello.realm.waiting_period_threshold = 1000 othello.date_joined = timezone_now() - timedelta(days=(othello.realm.waiting_period_threshold - 1)) self.assertFalse(othello.can_subscribe_other_users()) othello.date_joined = timezone_now() - timedelta(days=(othello.realm.waiting_period_threshold + 1)) self.assertTrue(othello.can_subscribe_other_users()) def test_subscriptions_add_invalid_stream(self) -> None: """ Calling POST /json/users/me/subscriptions on a stream whose name is invalid (as defined by valid_stream_name in zerver/views.py) should return a JSON error. """ # currently, the only invalid name is the empty string invalid_stream_name = "" result = self.common_subscribe_to_streams(self.test_email, [invalid_stream_name]) self.assert_json_error(result, "Invalid stream name '%s'" % (invalid_stream_name,)) def assert_adding_subscriptions_for_principal(self, invitee_email: str, invitee_realm: Realm, streams: List[str], invite_only: bool=False) -> None: """ Calling POST /json/users/me/subscriptions on behalf of another principal (for whom you have permission to add subscriptions) should successfully add those subscriptions and send a message to the subscribee notifying them. """ other_profile = get_user(invitee_email, invitee_realm) current_streams = self.get_streams(invitee_email, invitee_realm) self.assertIsInstance(other_profile, UserProfile) self.assertNotEqual(len(current_streams), 0) # necessary for full test coverage self.assertNotEqual(len(streams), 0) # necessary for full test coverage streams_to_sub = streams[:1] # just add one, to make the message easier to check streams_to_sub.extend(current_streams) self.helper_check_subs_before_and_after_add(streams_to_sub, {"principals": ujson.dumps([invitee_email])}, streams[:1], current_streams, invitee_email, streams_to_sub, invitee_realm, invite_only=invite_only) # verify that a welcome message was sent to the stream msg = self.get_last_message() self.assertEqual(msg.recipient.type, msg.recipient.STREAM) self.assertEqual(msg.topic_name(), u'hello') self.assertEqual(msg.sender.email, settings.WELCOME_BOT) self.assertIn('Welcome to #**', msg.content) def test_multi_user_subscription(self) -> None: user1 = self.example_user("cordelia") user2 = self.example_user("iago") realm = get_realm("zulip") streams_to_sub = ['multi_user_stream'] events = [] # type: List[Mapping[str, Any]] flush_per_request_caches() with tornado_redirected_to_list(events): with queries_captured() as queries: self.common_subscribe_to_streams( self.test_email, streams_to_sub, dict(principals=ujson.dumps([user1.email, user2.email])), ) self.assert_length(queries, 43) self.assert_length(events, 7) for ev in [x for x in events if x['event']['type'] not in ('message', 'stream')]: if isinstance(ev['event']['subscriptions'][0], dict): self.assertEqual(ev['event']['op'], 'add') self.assertEqual( set(ev['event']['subscriptions'][0]['subscribers']), set([user1.id, user2.id]) ) else: # Check "peer_add" events for streams users were # never subscribed to, in order for the neversubscribed # structure to stay up-to-date. self.assertEqual(ev['event']['op'], 'peer_add') stream = get_stream('multi_user_stream', realm) self.assertEqual(num_subscribers_for_stream_id(stream.id), 2) # Now add ourselves events = [] with tornado_redirected_to_list(events): with queries_captured() as queries: self.common_subscribe_to_streams( self.test_email, streams_to_sub, dict(principals=ujson.dumps([self.test_email])), ) self.assert_length(queries, 16) self.assert_length(events, 2) add_event, add_peer_event = events self.assertEqual(add_event['event']['type'], 'subscription') self.assertEqual(add_event['event']['op'], 'add') self.assertEqual(add_event['users'], [get_user(self.test_email, self.test_realm).id]) self.assertEqual( set(add_event['event']['subscriptions'][0]['subscribers']), set([user1.id, user2.id, self.test_user.id]) ) self.assertNotIn(self.example_user('polonius').id, add_peer_event['users']) self.assertEqual(len(add_peer_event['users']), 17) self.assertEqual(add_peer_event['event']['type'], 'subscription') self.assertEqual(add_peer_event['event']['op'], 'peer_add') self.assertEqual(add_peer_event['event']['user_id'], self.user_profile.id) stream = get_stream('multi_user_stream', realm) self.assertEqual(num_subscribers_for_stream_id(stream.id), 3) # Finally, add othello. events = [] user_profile = self.example_user('othello') email3 = user_profile.email user3 = user_profile realm3 = user_profile.realm stream = get_stream('multi_user_stream', realm) with tornado_redirected_to_list(events): bulk_add_subscriptions([stream], [user_profile]) self.assert_length(events, 2) add_event, add_peer_event = events self.assertEqual(add_event['event']['type'], 'subscription') self.assertEqual(add_event['event']['op'], 'add') self.assertEqual(add_event['users'], [get_user(email3, realm3).id]) self.assertEqual( set(add_event['event']['subscriptions'][0]['subscribers']), set([user1.id, user2.id, user3.id, self.test_user.id]) ) # We don't send a peer_add event to othello self.assertNotIn(user_profile.id, add_peer_event['users']) self.assertNotIn(self.example_user('polonius').id, add_peer_event['users']) self.assertEqual(len(add_peer_event['users']), 17) self.assertEqual(add_peer_event['event']['type'], 'subscription') self.assertEqual(add_peer_event['event']['op'], 'peer_add') self.assertEqual(add_peer_event['event']['user_id'], user_profile.id) def test_private_stream_subscription(self) -> None: realm = get_realm("zulip") # Create a private stream with Hamlet subscribed stream_name = "private" stream = ensure_stream(realm, stream_name, invite_only=True) existing_user_profile = self.example_user('hamlet') bulk_add_subscriptions([stream], [existing_user_profile]) # Now subscribe Cordelia to the stream, capturing events user_profile = self.example_user('cordelia') events = [] # type: List[Mapping[str, Any]] with tornado_redirected_to_list(events): bulk_add_subscriptions([stream], [user_profile]) self.assert_length(events, 3) create_event, add_event, add_peer_event = events self.assertEqual(create_event['event']['type'], 'stream') self.assertEqual(create_event['event']['op'], 'create') self.assertEqual(create_event['users'], [user_profile.id]) self.assertEqual(create_event['event']['streams'][0]['name'], stream_name) self.assertEqual(add_event['event']['type'], 'subscription') self.assertEqual(add_event['event']['op'], 'add') self.assertEqual(add_event['users'], [user_profile.id]) self.assertEqual( set(add_event['event']['subscriptions'][0]['subscribers']), set([user_profile.id, existing_user_profile.id]) ) # We don't send a peer_add event to othello, but we do send peer_add event to # all realm admins. self.assertNotIn(user_profile.id, add_peer_event['users']) self.assertEqual(len(add_peer_event['users']), 2) self.assertEqual(add_peer_event['event']['type'], 'subscription') self.assertEqual(add_peer_event['event']['op'], 'peer_add') self.assertEqual(add_peer_event['event']['user_id'], user_profile.id) # Do not send stream creation event to realm admin users # even if realm admin is subscribed to stream cause realm admin already get # private stream creation event on stream creation. new_stream = ensure_stream(realm, "private stream", invite_only=True) events = [] with tornado_redirected_to_list(events): bulk_add_subscriptions([new_stream], [self.example_user("iago")]) self.assert_length(events, 2) create_event, add_event = events self.assertEqual(create_event['event']['type'], 'stream') self.assertEqual(create_event['event']['op'], 'create') self.assertEqual(create_event['users'], []) self.assertEqual(add_event['event']['type'], 'subscription') self.assertEqual(add_event['event']['op'], 'add') self.assertEqual(add_event['users'], [self.example_user("iago").id]) def test_guest_user_subscribe(self) -> None: """Guest users cannot subscribe themselves to anything""" guest_user = self.example_user("polonius") guest_email = guest_user.email result = self.common_subscribe_to_streams(guest_email, ["Denmark"]) self.assert_json_error(result, "Not allowed for guest users") # Verify the internal checks also block guest users. stream = get_stream("Denmark", guest_user.realm) self.assertEqual(filter_stream_authorization(guest_user, [stream]), ([], [stream])) # Test UserProfile.can_create_streams for guest users. streams_raw = [{ 'invite_only': False, 'history_public_to_subscribers': None, 'name': 'new_stream', 'is_announcement_only': False }] with self.assertRaisesRegex(JsonableError, "User cannot create streams."): list_to_streams(streams_raw, guest_user) stream = self.make_stream('private_stream', invite_only=True) result = self.common_subscribe_to_streams(guest_email, ["private_stream"]) self.assert_json_error(result, "Not allowed for guest users") self.assertEqual(filter_stream_authorization(guest_user, [stream]), ([], [stream])) def test_users_getting_add_peer_event(self) -> None: """ Check users getting add_peer_event is correct """ streams_to_sub = ['multi_user_stream'] orig_emails_to_subscribe = [self.test_email, self.example_email("othello")] self.common_subscribe_to_streams( self.test_email, streams_to_sub, dict(principals=ujson.dumps(orig_emails_to_subscribe))) new_emails_to_subscribe = [self.example_email("iago"), self.example_email("cordelia")] events = [] # type: List[Mapping[str, Any]] with tornado_redirected_to_list(events): self.common_subscribe_to_streams( self.test_email, streams_to_sub, dict(principals=ujson.dumps(new_emails_to_subscribe)), ) add_peer_events = [events[2], events[3]] for add_peer_event in add_peer_events: self.assertEqual(add_peer_event['event']['type'], 'subscription') self.assertEqual(add_peer_event['event']['op'], 'peer_add') event_sent_to_ids = add_peer_event['users'] sent_emails = [ get_user_profile_by_id(user_id).email for user_id in event_sent_to_ids] for email in new_emails_to_subscribe: # Make sure new users subscribed to stream is not in # peer_add event recipient list self.assertNotIn(email, sent_emails) for old_user in orig_emails_to_subscribe: # Check non new users are in peer_add event recipient list. self.assertIn(old_user, sent_emails) def test_users_getting_remove_peer_event(self) -> None: """ Check users getting add_peer_event is correct """ user1 = self.example_user("othello") user2 = self.example_user("cordelia") user3 = self.example_user("hamlet") user4 = self.example_user("iago") user5 = self.example_user("AARON") stream1 = self.make_stream('stream1') stream2 = self.make_stream('stream2') private = self.make_stream('private_stream', invite_only=True) self.subscribe(user1, 'stream1') self.subscribe(user2, 'stream1') self.subscribe(user3, 'stream1') self.subscribe(user2, 'stream2') self.subscribe(user1, 'private_stream') self.subscribe(user2, 'private_stream') self.subscribe(user3, 'private_stream') events = [] # type: List[Mapping[str, Any]] with tornado_redirected_to_list(events): bulk_remove_subscriptions( [user1, user2], [stream1, stream2, private], get_client("website") ) peer_events = [e for e in events if e['event'].get('op') == 'peer_remove'] notifications = set() for event in peer_events: for user_id in event['users']: for stream_name in event['event']['subscriptions']: removed_user_id = event['event']['user_id'] notifications.add((user_id, removed_user_id, stream_name)) # POSITIVE CASES FIRST self.assertIn((user3.id, user1.id, 'stream1'), notifications) self.assertIn((user4.id, user1.id, 'stream1'), notifications) self.assertIn((user3.id, user2.id, 'stream1'), notifications) self.assertIn((user4.id, user2.id, 'stream1'), notifications) self.assertIn((user1.id, user2.id, 'stream2'), notifications) self.assertIn((user3.id, user2.id, 'stream2'), notifications) self.assertIn((user4.id, user2.id, 'stream2'), notifications) self.assertIn((user3.id, user1.id, 'private_stream'), notifications) self.assertIn((user3.id, user2.id, 'private_stream'), notifications) self.assertIn((user4.id, user1.id, 'private_stream'), notifications) self.assertIn((user4.id, user2.id, 'private_stream'), notifications) # NEGATIVE # don't be notified if you are being removed yourself self.assertNotIn((user1.id, user1.id, 'stream1'), notifications) # don't send false notifications for folks that weren't actually # subscribed int he first place self.assertNotIn((user3.id, user1.id, 'stream2'), notifications) # don't send notifications for random people self.assertNotIn((user3.id, user4.id, 'stream2'), notifications) # don't send notifications to unsubscribed non realm admin users for private streams self.assertNotIn((user5.id, user1.id, 'private_stream'), notifications) def test_bulk_subscribe_MIT(self) -> None: mit_user = self.mit_user('starnine') realm = get_realm("zephyr") stream_names = ["stream_%s" % i for i in range(40)] streams = [ self.make_stream(stream_name, realm=realm) for stream_name in stream_names] for stream in streams: stream.is_in_zephyr_realm = True stream.save() events = [] # type: List[Mapping[str, Any]] with tornado_redirected_to_list(events): with queries_captured() as queries: self.common_subscribe_to_streams( mit_user.email, stream_names, dict(principals=ujson.dumps([mit_user.email])), subdomain="zephyr", ) # Make sure Zephyr mirroring realms such as MIT do not get # any tornado subscription events self.assert_length(events, 0) self.assert_length(queries, 9) events = [] with tornado_redirected_to_list(events): bulk_remove_subscriptions( users=[mit_user], streams=streams, acting_client=get_client('website'), ) self.assert_length(events, 0) def test_bulk_subscribe_many(self) -> None: # Create a whole bunch of streams streams = ["stream_%s" % i for i in range(20)] for stream_name in streams: self.make_stream(stream_name) with queries_captured() as queries: self.common_subscribe_to_streams( self.test_email, streams, dict(principals=ujson.dumps([self.test_email])), ) # Make sure we don't make O(streams) queries self.assert_length(queries, 21) def test_subscriptions_add_for_principal(self) -> None: """ You can subscribe other people to streams. """ invitee_email = self.example_email("iago") invitee_realm = get_realm('zulip') current_streams = self.get_streams(invitee_email, invitee_realm) invite_streams = self.make_random_stream_names(current_streams) self.assert_adding_subscriptions_for_principal(invitee_email, invitee_realm, invite_streams) def test_subscriptions_add_for_principal_deactivated(self) -> None: """ You can't subscribe deactivated people to streams. """ target_profile = self.example_user("cordelia") result = self.common_subscribe_to_streams(self.test_email, "Verona", {"principals": ujson.dumps([target_profile.email])}) self.assert_json_success(result) do_deactivate_user(target_profile) result = self.common_subscribe_to_streams(self.test_email, "Denmark", {"principals": ujson.dumps([target_profile.email])}) self.assert_json_error(result, "User not authorized to execute queries on behalf of 'cordelia@zulip.com'", status_code=403) def test_subscriptions_add_for_principal_invite_only(self) -> None: """ You can subscribe other people to invite only streams. """ invitee_email = self.example_email("iago") invitee_realm = get_realm('zulip') current_streams = self.get_streams(invitee_email, invitee_realm) invite_streams = self.make_random_stream_names(current_streams) self.assert_adding_subscriptions_for_principal(invitee_email, invitee_realm, invite_streams, invite_only=True) def test_non_ascii_subscription_for_principal(self) -> None: """ You can subscribe other people to streams even if they containing non-ASCII characters. """ self.assert_adding_subscriptions_for_principal(self.example_email("iago"), get_realm('zulip'), [u"hümbüǵ"]) def test_subscription_add_invalid_principal(self) -> None: """ Calling subscribe on behalf of a principal that does not exist should return a JSON error. """ invalid_principal = "rosencrantz-and-guildenstern@zulip.com" invalid_principal_realm = get_realm("zulip") # verify that invalid_principal actually doesn't exist with self.assertRaises(UserProfile.DoesNotExist): get_user(invalid_principal, invalid_principal_realm) result = self.common_subscribe_to_streams(self.test_email, self.streams, {"principals": ujson.dumps([invalid_principal])}) self.assert_json_error(result, "User not authorized to execute queries on behalf of '%s'" % (invalid_principal,), status_code=403) def test_subscription_add_principal_other_realm(self) -> None: """ Calling subscribe on behalf of a principal in another realm should return a JSON error. """ profile = self.mit_user('starnine') principal = profile.email # verify that principal exists (thus, the reason for the error is the cross-realming) self.assertIsInstance(profile, UserProfile) result = self.common_subscribe_to_streams(self.test_email, self.streams, {"principals": ujson.dumps([principal])}) self.assert_json_error(result, "User not authorized to execute queries on behalf of '%s'" % (principal,), status_code=403) def helper_check_subs_before_and_after_remove(self, subscriptions: List[str], json_dict: Dict[str, Any], email: str, new_subs: List[str], realm: Realm) -> None: """ Check result of removing subscriptions. Unlike adding subscriptions, you can only remove subscriptions for yourself, so the result format is different. {"msg": "", "removed": ["Denmark", "Scotland", "Verona"], "not_subscribed": ["Rome"], "result": "success"} """ result = self.client_delete("/json/users/me/subscriptions", {"subscriptions": ujson.dumps(subscriptions)}) self.assert_json_success(result) json = result.json() for key, val in json_dict.items(): self.assertEqual(sorted(val), sorted(json[key])) # we don't care about the order of the items new_streams = self.get_streams(email, realm) self.assertEqual(sorted(new_streams), sorted(new_subs)) def test_successful_subscriptions_remove(self) -> None: """ Calling DELETE /json/users/me/subscriptions should successfully remove streams, and should determine which were removed vs which weren't subscribed to. We cannot randomly generate stream names because the remove code verifies whether streams exist. """ self.assertGreaterEqual(len(self.streams), 2) streams_to_remove = self.streams[1:] not_subbed = [] for stream in Stream.objects.all(): if stream.name not in self.streams: not_subbed.append(stream.name) random.shuffle(not_subbed) self.assertNotEqual(len(not_subbed), 0) # necessary for full test coverage try_to_remove = not_subbed[:3] # attempt to remove up to 3 streams not already subbed to streams_to_remove.extend(try_to_remove) self.helper_check_subs_before_and_after_remove(streams_to_remove, {"removed": self.streams[1:], "not_subscribed": try_to_remove}, self.test_email, [self.streams[0]], self.test_realm) def test_subscriptions_remove_fake_stream(self) -> None: """ Calling DELETE /json/users/me/subscriptions on a stream that doesn't exist should return a JSON error. """ random_streams = self.make_random_stream_names(self.streams) self.assertNotEqual(len(random_streams), 0) # necessary for full test coverage streams_to_remove = random_streams[:1] # pick only one fake stream, to make checking the error message easy result = self.client_delete("/json/users/me/subscriptions", {"subscriptions": ujson.dumps(streams_to_remove)}) self.assert_json_error(result, "Stream(s) (%s) do not exist" % (random_streams[0],)) def helper_subscriptions_exists(self, stream: str, expect_success: bool, subscribed: bool) -> None: """ Call /json/subscriptions/exists on a stream and expect a certain result. """ result = self.client_post("/json/subscriptions/exists", {"stream": stream}) json = result.json() if expect_success: self.assert_json_success(result) else: self.assertEqual(result.status_code, 404) if subscribed: self.assertIn("subscribed", json) self.assertEqual(json["subscribed"], subscribed) def test_successful_subscriptions_exists_subbed(self) -> None: """ Calling /json/subscriptions/exist on a stream to which you are subbed should return that it exists and that you are subbed. """ self.assertNotEqual(len(self.streams), 0) # necessary for full test coverage self.helper_subscriptions_exists(self.streams[0], True, True) def test_successful_subscriptions_exists_not_subbed(self) -> None: """ Calling /json/subscriptions/exist on a stream to which you are not subbed should return that it exists and that you are not subbed. """ all_stream_names = [stream.name for stream in Stream.objects.filter(realm=self.test_realm)] streams_not_subbed = list(set(all_stream_names) - set(self.streams)) self.assertNotEqual(len(streams_not_subbed), 0) # necessary for full test coverage self.helper_subscriptions_exists(streams_not_subbed[0], True, False) def test_subscriptions_does_not_exist(self) -> None: """ Calling /json/subscriptions/exist on a stream that doesn't exist should return that it doesn't exist. """ random_streams = self.make_random_stream_names(self.streams) self.assertNotEqual(len(random_streams), 0) # necessary for full test coverage self.helper_subscriptions_exists(random_streams[0], False, False) def test_subscriptions_exist_invalid_name(self) -> None: """ Calling /json/subscriptions/exist on a stream whose name is invalid (as defined by valid_stream_name in zerver/views.py) should return a JSON error. """ # currently, the only invalid stream name is the empty string invalid_stream_name = "" result = self.client_post("/json/subscriptions/exists", {"stream": invalid_stream_name}) self.assert_json_error(result, "Invalid stream name ''") def test_existing_subscriptions_autosubscription(self) -> None: """ Call /json/subscriptions/exist on an existing stream and autosubscribe to it. """ stream_name = "new_public_stream" result = self.common_subscribe_to_streams(self.example_email("cordelia"), [stream_name], invite_only=False) result = self.client_post("/json/subscriptions/exists", {"stream": stream_name, "autosubscribe": "false"}) self.assert_json_success(result) self.assertIn("subscribed", result.json()) self.assertFalse(result.json()["subscribed"]) result = self.client_post("/json/subscriptions/exists", {"stream": stream_name, "autosubscribe": "true"}) self.assert_json_success(result) self.assertIn("subscribed", result.json()) self.assertTrue(result.json()["subscribed"]) def test_existing_subscriptions_autosubscription_private_stream(self) -> None: """Call /json/subscriptions/exist on an existing private stream with autosubscribe should fail. """ stream_name = "Saxony" result = self.common_subscribe_to_streams(self.example_email("cordelia"), [stream_name], invite_only=True) stream = get_stream(stream_name, self.test_realm) result = self.client_post("/json/subscriptions/exists", {"stream": stream_name, "autosubscribe": "true"}) # We can't see invite-only streams here self.assert_json_error(result, "Invalid stream name 'Saxony'", status_code=404) # Importantly, we are not now subscribed self.assertEqual(num_subscribers_for_stream_id(stream.id), 1) # A user who is subscribed still sees the stream exists self.login(self.example_email("cordelia")) result = self.client_post("/json/subscriptions/exists", {"stream": stream_name, "autosubscribe": "false"}) self.assert_json_success(result) self.assertIn("subscribed", result.json()) self.assertTrue(result.json()["subscribed"]) def get_subscription(self, user_profile: UserProfile, stream_name: str) -> Subscription: stream = get_stream(stream_name, self.test_realm) return Subscription.objects.get( user_profile=user_profile, recipient__type=Recipient.STREAM, recipient__type_id=stream.id, ) def test_subscriptions_add_notification_default_true(self) -> None: """ When creating a subscription, the desktop, push, and audible notification settings for that stream are derived from the global notification settings. """ user_profile = self.example_user('iago') invitee_email = user_profile.email invitee_realm = user_profile.realm user_profile.enable_stream_desktop_notifications = True user_profile.enable_stream_push_notifications = True user_profile.enable_stream_sounds = True user_profile.enable_stream_email_notifications = True user_profile.save() current_stream = self.get_streams(invitee_email, invitee_realm)[0] invite_streams = self.make_random_stream_names([current_stream]) self.assert_adding_subscriptions_for_principal(invitee_email, invitee_realm, invite_streams) subscription = self.get_subscription(user_profile, invite_streams[0]) with mock.patch('zerver.models.Recipient.__str__', return_value='recip'): self.assertEqual(str(subscription), u'<Subscription: ' '<UserProfile: %s <Realm: zulip 1>> -> recip>' % (self.example_email('iago'),)) self.assertTrue(subscription.desktop_notifications) self.assertTrue(subscription.push_notifications) self.assertTrue(subscription.audible_notifications) self.assertTrue(subscription.email_notifications) def test_subscriptions_add_notification_default_false(self) -> None: """ When creating a subscription, the desktop, push, and audible notification settings for that stream are derived from the global notification settings. """ user_profile = self.example_user('iago') invitee_email = user_profile.email invitee_realm = user_profile.realm user_profile.enable_stream_desktop_notifications = False user_profile.enable_stream_push_notifications = False user_profile.enable_stream_sounds = False user_profile.save() current_stream = self.get_streams(invitee_email, invitee_realm)[0] invite_streams = self.make_random_stream_names([current_stream]) self.assert_adding_subscriptions_for_principal(invitee_email, invitee_realm, invite_streams) subscription = self.get_subscription(user_profile, invite_streams[0]) self.assertFalse(subscription.desktop_notifications) self.assertFalse(subscription.push_notifications) self.assertFalse(subscription.audible_notifications) def test_mark_messages_as_unread_on_unsubscribe(self) -> None: realm = get_realm("zulip") user = self.example_user("iago") random_user = self.example_user("hamlet") stream1 = ensure_stream(realm, "stream1", invite_only=False) stream2 = ensure_stream(realm, "stream2", invite_only=False) private = ensure_stream(realm, "private_stream", invite_only=True) self.subscribe(user, "stream1") self.subscribe(user, "stream2") self.subscribe(user, "private_stream") self.subscribe(random_user, "stream1") self.subscribe(random_user, "stream2") self.subscribe(random_user, "private_stream") self.send_stream_message(random_user.email, "stream1", "test", "test") self.send_stream_message(random_user.email, "stream2", "test", "test") self.send_stream_message(random_user.email, "private_stream", "test", "test") def get_unread_stream_data() -> List[Dict[str, Any]]: raw_unread_data = get_raw_unread_data(user) aggregated_data = aggregate_unread_data(raw_unread_data) return aggregated_data['streams'] result = get_unread_stream_data() self.assert_length(result, 3) self.assertEqual(result[0]['stream_id'], stream1.id) self.assertEqual(result[1]['stream_id'], stream2.id) self.assertEqual(result[2]['stream_id'], private.id) # Unsubscribing should mark all the messages in stream2 as read self.unsubscribe(user, "stream2") self.unsubscribe(user, "private_stream") self.subscribe(user, "stream2") self.subscribe(user, "private_stream") result = get_unread_stream_data() self.assert_length(result, 1) self.assertEqual(result[0]['stream_id'], stream1.id) def test_gather_subscriptions_excludes_deactivated_streams(self) -> None: """ Check that gather_subscriptions_helper does not include deactivated streams in its results. """ realm = get_realm("zulip") admin_user = self.example_user("iago") non_admin_user = self.example_user("cordelia") self.login(admin_user.email) for stream_name in ["stream1", "stream2", "stream3", ]: self.make_stream(stream_name, realm=realm, invite_only=False) self.subscribe(admin_user, stream_name) self.subscribe(non_admin_user, stream_name) self.subscribe(self.example_user("othello"), stream_name) def delete_stream(stream_name: str) -> None: stream_id = get_stream(stream_name, realm).id result = self.client_delete('/json/streams/%d' % (stream_id,)) self.assert_json_success(result) # Deleted/deactivated stream should not be returned in the helper results admin_before_delete = gather_subscriptions_helper(admin_user) non_admin_before_delete = gather_subscriptions_helper(non_admin_user) # Delete our stream delete_stream("stream1") # Get subs after delete admin_after_delete = gather_subscriptions_helper(admin_user) non_admin_after_delete = gather_subscriptions_helper(non_admin_user) # Compare results - should be 1 stream less self.assertTrue( len(admin_before_delete[0]) == len(admin_after_delete[0]) + 1, 'Expected exactly 1 less stream from gather_subscriptions_helper') self.assertTrue( len(non_admin_before_delete[0]) == len(non_admin_after_delete[0]) + 1, 'Expected exactly 1 less stream from gather_subscriptions_helper') def test_validate_user_access_to_subscribers_helper(self) -> None: """ Ensure the validate_user_access_to_subscribers_helper is properly raising ValidationError on missing user, user not-in-realm. """ user_profile = self.example_user('othello') realm_name = 'no_othello_allowed' realm = do_create_realm(realm_name, 'Everyone but Othello is allowed') stream_dict = { 'name': 'publicstream', 'description': 'Public stream with public history', 'realm_id': realm.id } # For this test to work, othello can't be in the no_othello_here realm self.assertNotEqual(user_profile.realm.id, realm.id, 'Expected othello user to not be in this realm.') # This should result in missing user with self.assertRaises(ValidationError): validate_user_access_to_subscribers_helper(None, stream_dict, lambda: True) # This should result in user not in realm with self.assertRaises(ValidationError): validate_user_access_to_subscribers_helper(user_profile, stream_dict, lambda: True) def test_subscriptions_query_count(self) -> None: """ Test database query count when creating stream with api/v1/users/me/subscriptions. """ user1 = self.example_user("cordelia") user2 = self.example_user("iago") new_streams = [ 'query_count_stream_1', 'query_count_stream_2', 'query_count_stream_3' ] # Test creating a public stream when realm does not have a notification stream. with queries_captured() as queries: self.common_subscribe_to_streams( self.test_email, [new_streams[0]], dict(principals=ujson.dumps([user1.email, user2.email])), ) self.assert_length(queries, 43) # Test creating private stream. with queries_captured() as queries: self.common_subscribe_to_streams( self.test_email, [new_streams[1]], dict(principals=ujson.dumps([user1.email, user2.email])), invite_only=True, ) self.assert_length(queries, 38) # Test creating a public stream with announce when realm has a notification stream. notifications_stream = get_stream(self.streams[0], self.test_realm) self.test_realm.notifications_stream_id = notifications_stream.id self.test_realm.save() with queries_captured() as queries: self.common_subscribe_to_streams( self.test_email, [new_streams[2]], dict( announce='true', principals=ujson.dumps([user1.email, user2.email]) ) ) self.assert_length(queries, 52) class GetPublicStreamsTest(ZulipTestCase): def test_public_streams_api(self) -> None: """ Ensure that the query we use to get public streams successfully returns a list of streams """ email = self.example_email('hamlet') realm = get_realm('zulip') self.login(email) # Check it correctly lists the user's subs with include_public=false result = self.api_get(email, "/api/v1/streams?include_public=false") result2 = self.api_get(email, "/api/v1/users/me/subscriptions") self.assert_json_success(result) json = result.json() self.assertIn("streams", json) self.assertIsInstance(json["streams"], list) self.assert_json_success(result2) json2 = ujson.loads(result2.content) self.assertEqual(sorted([s["name"] for s in json["streams"]]), sorted([s["name"] for s in json2["subscriptions"]])) # Check it correctly lists all public streams with include_subscribed=false result = self.api_get(email, "/api/v1/streams?include_public=true&include_subscribed=false") self.assert_json_success(result) json = result.json() all_streams = [stream.name for stream in Stream.objects.filter(realm=realm)] self.assertEqual(sorted(s["name"] for s in json["streams"]), sorted(all_streams)) # Check non-superuser can't use include_all_active result = self.api_get(email, "/api/v1/streams?include_all_active=true") self.assertEqual(result.status_code, 400) class StreamIdTest(ZulipTestCase): def setUp(self) -> None: self.user_profile = self.example_user('hamlet') self.email = self.user_profile.email self.login(self.email) def test_get_stream_id(self) -> None: stream = gather_subscriptions(self.user_profile)[0][0] result = self.client_get("/json/get_stream_id?stream=%s" % (stream['name'],)) self.assert_json_success(result) self.assertEqual(result.json()['stream_id'], stream['stream_id']) def test_get_stream_id_wrong_name(self) -> None: result = self.client_get("/json/get_stream_id?stream=wrongname") self.assert_json_error(result, u"Invalid stream name 'wrongname'") class InviteOnlyStreamTest(ZulipTestCase): def test_must_be_subbed_to_send(self) -> None: """ If you try to send a message to an invite-only stream to which you aren't subscribed, you'll get a 400. """ self.login(self.example_email("hamlet")) # Create Saxony as an invite-only stream. self.assert_json_success( self.common_subscribe_to_streams(self.example_email("hamlet"), ["Saxony"], invite_only=True)) email = self.example_email("cordelia") with self.assertRaises(JsonableError): self.send_stream_message(email, "Saxony") def test_list_respects_invite_only_bit(self) -> None: """ Make sure that /api/v1/users/me/subscriptions properly returns the invite-only bit for streams that are invite-only """ email = self.example_email('hamlet') self.login(email) result1 = self.common_subscribe_to_streams(email, ["Saxony"], invite_only=True) self.assert_json_success(result1) result2 = self.common_subscribe_to_streams(email, ["Normandy"], invite_only=False) self.assert_json_success(result2) result = self.api_get(email, "/api/v1/users/me/subscriptions") self.assert_json_success(result) self.assertIn("subscriptions", result.json()) for sub in result.json()["subscriptions"]: if sub['name'] == "Normandy": self.assertEqual(sub['invite_only'], False, "Normandy was mistakenly marked private") if sub['name'] == "Saxony": self.assertEqual(sub['invite_only'], True, "Saxony was not properly marked private") @slow("lots of queries") def test_inviteonly(self) -> None: # Creating an invite-only stream is allowed user_profile = self.example_user('hamlet') email = user_profile.email stream_name = "Saxony" result = self.common_subscribe_to_streams(email, [stream_name], invite_only=True) self.assert_json_success(result) json = result.json() self.assertEqual(json["subscribed"], {email: [stream_name]}) self.assertEqual(json["already_subscribed"], {}) # Subscribing oneself to an invite-only stream is not allowed user_profile = self.example_user('othello') email = user_profile.email self.login(email) result = self.common_subscribe_to_streams(email, [stream_name]) self.assert_json_error(result, 'Unable to access stream (Saxony).') # authorization_errors_fatal=False works user_profile = self.example_user('othello') email = user_profile.email self.login(email) result = self.common_subscribe_to_streams(email, [stream_name], extra_post_data={'authorization_errors_fatal': ujson.dumps(False)}) self.assert_json_success(result) json = result.json() self.assertEqual(json["unauthorized"], [stream_name]) self.assertEqual(json["subscribed"], {}) self.assertEqual(json["already_subscribed"], {}) # Inviting another user to an invite-only stream is allowed user_profile = self.example_user('hamlet') email = user_profile.email self.login(email) result = self.common_subscribe_to_streams( email, [stream_name], extra_post_data={'principals': ujson.dumps([self.example_email("othello")])}) self.assert_json_success(result) json = result.json() self.assertEqual(json["subscribed"], {self.example_email("othello"): [stream_name]}) self.assertEqual(json["already_subscribed"], {}) # Make sure both users are subscribed to this stream stream_id = get_stream(stream_name, user_profile.realm).id result = self.api_get(email, "/api/v1/streams/%d/members" % (stream_id,)) self.assert_json_success(result) json = result.json() self.assertTrue(self.example_email("othello") in json['subscribers']) self.assertTrue(self.example_email('hamlet') in json['subscribers']) class GetSubscribersTest(ZulipTestCase): def setUp(self) -> None: self.user_profile = self.example_user('hamlet') self.email = self.user_profile.email self.login(self.email) def assert_user_got_subscription_notification(self, expected_msg: str) -> None: # verify that the user was sent a message informing them about the subscription msg = self.get_last_message() self.assertEqual(msg.recipient.type, msg.recipient.PERSONAL) self.assertEqual(msg.sender_id, self.notification_bot().id) def non_ws(s: str) -> str: return s.replace('\n', '').replace(' ', '') self.assertEqual(non_ws(msg.content), non_ws(expected_msg)) def check_well_formed_result(self, result: Dict[str, Any], stream_name: str, realm: Realm) -> None: """ A successful call to get_subscribers returns the list of subscribers in the form: {"msg": "", "result": "success", "subscribers": [self.example_email("hamlet"), self.example_email("prospero")]} """ self.assertIn("subscribers", result) self.assertIsInstance(result["subscribers"], list) true_subscribers = [user_profile.email for user_profile in self.users_subscribed_to_stream( stream_name, realm)] self.assertEqual(sorted(result["subscribers"]), sorted(true_subscribers)) def make_subscriber_request(self, stream_id: int, email: Optional[str]=None) -> HttpResponse: if email is None: email = self.email return self.api_get(email, "/api/v1/streams/%d/members" % (stream_id,)) def make_successful_subscriber_request(self, stream_name: str) -> None: stream_id = get_stream(stream_name, self.user_profile.realm).id result = self.make_subscriber_request(stream_id) self.assert_json_success(result) self.check_well_formed_result(result.json(), stream_name, self.user_profile.realm) def test_subscriber(self) -> None: """ get_subscribers returns the list of subscribers. """ stream_name = gather_subscriptions(self.user_profile)[0][0]['name'] self.make_successful_subscriber_request(stream_name) @slow("common_subscribe_to_streams is slow") def test_gather_subscriptions(self) -> None: """ gather_subscriptions returns correct results with only 3 queries (We also use this test to verify subscription notifications to folks who get subscribed to streams.) """ streams = ["stream_%s" % i for i in range(10)] for stream_name in streams: self.make_stream(stream_name) users_to_subscribe = [self.email, self.example_email("othello"), self.example_email("cordelia")] ret = self.common_subscribe_to_streams( self.email, streams, dict(principals=ujson.dumps(users_to_subscribe))) self.assert_json_success(ret) msg = ''' Hi there! @**King Hamlet** just subscribed you to the following streams: * #**stream_0** * #**stream_1** * #**stream_2** * #**stream_3** * #**stream_4** * #**stream_5** * #**stream_6** * #**stream_7** * #**stream_8** * #**stream_9** ''' self.assert_user_got_subscription_notification(msg) # Subscribe ourself first. ret = self.common_subscribe_to_streams( self.email, ["stream_invite_only_1"], dict(principals=ujson.dumps([self.email])), invite_only=True) self.assert_json_success(ret) # Now add in other users, and this should trigger messages # to notify the user. ret = self.common_subscribe_to_streams( self.email, ["stream_invite_only_1"], dict(principals=ujson.dumps(users_to_subscribe)), invite_only=True) self.assert_json_success(ret) msg = ''' Hi there! @**King Hamlet** just subscribed you to the stream #**stream_invite_only_1**. ''' self.assert_user_got_subscription_notification(msg) with queries_captured() as queries: subscriptions = gather_subscriptions(self.user_profile) self.assertTrue(len(subscriptions[0]) >= 11) for sub in subscriptions[0]: if not sub["name"].startswith("stream_"): continue self.assertTrue(len(sub["subscribers"]) == len(users_to_subscribe)) self.assert_length(queries, 7) @slow("common_subscribe_to_streams is slow") def test_never_subscribed_streams(self) -> None: """ Check never_subscribed streams are fetched correctly and not include invite_only streams. """ realm = get_realm("zulip") users_to_subscribe = [ self.example_email("othello"), self.example_email("cordelia"), ] public_streams = [ 'test_stream_public_1', 'test_stream_public_2', 'test_stream_public_3', 'test_stream_public_4', 'test_stream_public_5', ] private_streams = [ 'test_stream_invite_only_1', 'test_stream_invite_only_2', ] def create_public_streams() -> None: for stream_name in public_streams: self.make_stream(stream_name, realm=realm) ret = self.common_subscribe_to_streams( self.email, public_streams, dict(principals=ujson.dumps(users_to_subscribe)) ) self.assert_json_success(ret) create_public_streams() def create_private_streams() -> None: ret = self.common_subscribe_to_streams( self.email, private_streams, dict(principals=ujson.dumps(users_to_subscribe)), invite_only=True ) self.assert_json_success(ret) create_private_streams() def get_never_subscribed() -> List[Dict[str, Any]]: with queries_captured() as queries: sub_data = gather_subscriptions_helper(self.user_profile) never_subscribed = sub_data[2] self.assert_length(queries, 6) # Ignore old streams. never_subscribed = [ dct for dct in never_subscribed if dct['name'].startswith('test_') ] return never_subscribed never_subscribed = get_never_subscribed() # Invite only stream should not be there in never_subscribed streams self.assertEqual(len(never_subscribed), len(public_streams)) for stream_dict in never_subscribed: name = stream_dict['name'] self.assertFalse('invite_only' in name) self.assertTrue(len(stream_dict["subscribers"]) == len(users_to_subscribe)) # Send private stream subscribers to all realm admins. def test_admin_case() -> None: self.user_profile.is_realm_admin = True # Test realm admins can get never subscribed private stream's subscribers. never_subscribed = get_never_subscribed() self.assertEqual( len(never_subscribed), len(public_streams) + len(private_streams) ) for stream_dict in never_subscribed: self.assertTrue(len(stream_dict["subscribers"]) == len(users_to_subscribe)) test_admin_case() def test_gather_subscribed_streams_for_guest_user(self) -> None: guest_user = self.example_user("polonius") stream_name_sub = "public_stream_1" self.make_stream(stream_name_sub, realm=get_realm("zulip")) self.subscribe(guest_user, stream_name_sub) stream_name_unsub = "public_stream_2" self.make_stream(stream_name_unsub, realm=get_realm("zulip")) self.subscribe(guest_user, stream_name_unsub) self.unsubscribe(guest_user, stream_name_unsub) stream_name_never_sub = "public_stream_3" self.make_stream(stream_name_never_sub, realm=get_realm("zulip")) normal_user = self.example_user("aaron") self.subscribe(normal_user, stream_name_sub) self.subscribe(normal_user, stream_name_unsub) self.subscribe(normal_user, stream_name_unsub) subs, unsubs, neversubs = gather_subscriptions_helper(guest_user) # Guest users get info about subscribed public stream's subscribers expected_stream_exists = False for sub in subs: if sub["name"] == stream_name_sub: expected_stream_exists = True self.assertEqual(len(sub["subscribers"]), 2) self.assertTrue(expected_stream_exists) # Guest users don't get info about unsubscribed public stream's subscribers expected_stream_exists = False for unsub in unsubs: if unsub["name"] == stream_name_unsub: expected_stream_exists = True self.assertNotIn("subscribers", unsub) self.assertTrue(expected_stream_exists) # Guest user don't get data about never subscribed public stream's data self.assertEqual(len(neversubs), 0) def test_previously_subscribed_private_streams(self) -> None: admin_user = self.example_user("iago") non_admin_user = self.example_user("cordelia") stream_name = "private_stream" self.make_stream(stream_name, realm=get_realm("zulip"), invite_only=True) self.subscribe(admin_user, stream_name) self.subscribe(non_admin_user, stream_name) self.subscribe(self.example_user("othello"), stream_name) self.unsubscribe(admin_user, stream_name) self.unsubscribe(non_admin_user, stream_name) # Test admin user gets previously subscribed private stream's subscribers. sub_data = gather_subscriptions_helper(admin_user) unsubscribed_streams = sub_data[1] self.assertEqual(len(unsubscribed_streams), 1) self.assertEqual(len(unsubscribed_streams[0]["subscribers"]), 1) # Test non admin users cannot get previously subscribed private stream's subscribers. sub_data = gather_subscriptions_helper(non_admin_user) unsubscribed_streams = sub_data[1] self.assertEqual(len(unsubscribed_streams), 1) self.assertFalse('subscribers' in unsubscribed_streams[0]) def test_gather_subscriptions_mit(self) -> None: """ gather_subscriptions returns correct results with only 3 queries """ # Subscribe only ourself because invites are disabled on mit.edu mit_user_profile = self.mit_user('starnine') email = mit_user_profile.email users_to_subscribe = [email, self.mit_email("espuser")] for email in users_to_subscribe: stream = self.subscribe(get_user(email, mit_user_profile.realm), "mit_stream") self.assertTrue(stream.is_in_zephyr_realm) ret = self.common_subscribe_to_streams( email, ["mit_invite_only"], dict(principals=ujson.dumps(users_to_subscribe)), invite_only=True, subdomain="zephyr") self.assert_json_success(ret) with queries_captured() as queries: subscriptions = gather_subscriptions(mit_user_profile) self.assertTrue(len(subscriptions[0]) >= 2) for sub in subscriptions[0]: if not sub["name"].startswith("mit_"): raise AssertionError("Unexpected stream!") if sub["name"] == "mit_invite_only": self.assertTrue(len(sub["subscribers"]) == len(users_to_subscribe)) else: self.assertTrue(len(sub["subscribers"]) == 0) self.assert_length(queries, 6) def test_nonsubscriber(self) -> None: """ Even a non-subscriber to a public stream can query a stream's membership with get_subscribers. """ # Create a stream for which Hamlet is the only subscriber. stream_name = "Saxony" self.common_subscribe_to_streams(self.email, [stream_name]) other_email = self.example_email("othello") # Fetch the subscriber list as a non-member. self.login(other_email) self.make_successful_subscriber_request(stream_name) def test_subscriber_private_stream(self) -> None: """ A subscriber to a private stream can query that stream's membership. """ stream_name = "Saxony" self.common_subscribe_to_streams(self.email, [stream_name], invite_only=True) self.make_successful_subscriber_request(stream_name) stream_id = get_stream(stream_name, self.user_profile.realm).id # Verify another user can't get the data. self.login(self.example_email("cordelia")) result = self.client_get("/json/streams/%d/members" % (stream_id,)) self.assert_json_error(result, u'Invalid stream id') # But an organization administrator can self.login(self.example_email("iago")) result = self.client_get("/json/streams/%d/members" % (stream_id,)) self.assert_json_success(result) def test_json_get_subscribers_stream_not_exist(self) -> None: """ json_get_subscribers also returns the list of subscribers for a stream. """ stream_id = 99999999 result = self.client_get("/json/streams/%d/members" % (stream_id,)) self.assert_json_error(result, u'Invalid stream id') def test_json_get_subscribers(self) -> None: """ json_get_subscribers in zerver/views/streams.py also returns the list of subscribers for a stream. """ stream_name = gather_subscriptions(self.user_profile)[0][0]['name'] stream_id = get_stream(stream_name, self.user_profile.realm).id expected_subscribers = gather_subscriptions(self.user_profile)[0][0]['subscribers'] result = self.client_get("/json/streams/%d/members" % (stream_id,)) self.assert_json_success(result) result_dict = result.json() self.assertIn('subscribers', result_dict) self.assertIsInstance(result_dict['subscribers'], list) subscribers = [] # type: List[str] for subscriber in result_dict['subscribers']: self.assertIsInstance(subscriber, str) subscribers.append(subscriber) self.assertEqual(set(subscribers), set(expected_subscribers)) def test_nonsubscriber_private_stream(self) -> None: """ A non-subscriber non realm admin user to a private stream can't query that stream's membership. But unsubscribed realm admin users can query private stream's membership. """ # Create a private stream for which Hamlet is the only subscriber. stream_name = "NewStream" self.common_subscribe_to_streams(self.email, [stream_name], invite_only=True) user_profile = self.example_user('othello') other_email = user_profile.email # Try to fetch the subscriber list as a non-member & non-realm-admin-user. stream_id = get_stream(stream_name, user_profile.realm).id result = self.make_subscriber_request(stream_id, email=other_email) self.assert_json_error(result, "Invalid stream id") # Try to fetch the subscriber list as a non-member & realm-admin-user. self.login(self.example_email("iago")) self.make_successful_subscriber_request(stream_name) class AccessStreamTest(ZulipTestCase): def test_access_stream(self) -> None: """ A comprehensive security test for the access_stream_by_* API functions. """ # Create a private stream for which Hamlet is the only subscriber. hamlet = self.example_user('hamlet') hamlet_email = hamlet.email stream_name = "new_private_stream" self.login(hamlet_email) self.common_subscribe_to_streams(hamlet_email, [stream_name], invite_only=True) stream = get_stream(stream_name, hamlet.realm) othello = self.example_user('othello') # Nobody can access a stream that doesn't exist with self.assertRaisesRegex(JsonableError, "Invalid stream id"): access_stream_by_id(hamlet, 501232) with self.assertRaisesRegex(JsonableError, "Invalid stream name 'invalid stream'"): access_stream_by_name(hamlet, "invalid stream") # Hamlet can access the private stream (stream_ret, rec_ret, sub_ret) = access_stream_by_id(hamlet, stream.id) self.assertEqual(stream.id, stream_ret.id) assert sub_ret is not None self.assertEqual(sub_ret.recipient, rec_ret) self.assertEqual(sub_ret.recipient.type_id, stream.id) (stream_ret2, rec_ret2, sub_ret2) = access_stream_by_name(hamlet, stream.name) self.assertEqual(stream_ret.id, stream_ret2.id) self.assertEqual(sub_ret, sub_ret2) self.assertEqual(rec_ret, rec_ret2) # Othello cannot access the private stream with self.assertRaisesRegex(JsonableError, "Invalid stream id"): access_stream_by_id(othello, stream.id) with self.assertRaisesRegex(JsonableError, "Invalid stream name 'new_private_stream'"): access_stream_by_name(othello, stream.name) # Both Othello and Hamlet can access a public stream that only # Hamlet is subscribed to in this realm public_stream_name = "public_stream" self.common_subscribe_to_streams(hamlet_email, [public_stream_name], invite_only=False) public_stream = get_stream(public_stream_name, hamlet.realm) access_stream_by_id(othello, public_stream.id) access_stream_by_name(othello, public_stream.name) access_stream_by_id(hamlet, public_stream.id) access_stream_by_name(hamlet, public_stream.name) # Nobody can access a public stream in another realm mit_realm = get_realm("zephyr") mit_stream = ensure_stream(mit_realm, "mit_stream", invite_only=False) sipbtest = self.mit_user("sipbtest") with self.assertRaisesRegex(JsonableError, "Invalid stream id"): access_stream_by_id(hamlet, mit_stream.id) with self.assertRaisesRegex(JsonableError, "Invalid stream name 'mit_stream'"): access_stream_by_name(hamlet, mit_stream.name) with self.assertRaisesRegex(JsonableError, "Invalid stream id"): access_stream_by_id(sipbtest, stream.id) with self.assertRaisesRegex(JsonableError, "Invalid stream name 'new_private_stream'"): access_stream_by_name(sipbtest, stream.name) # MIT realm users cannot access even public streams in their realm with self.assertRaisesRegex(JsonableError, "Invalid stream id"): access_stream_by_id(sipbtest, mit_stream.id) with self.assertRaisesRegex(JsonableError, "Invalid stream name 'mit_stream'"): access_stream_by_name(sipbtest, mit_stream.name) # But they can access streams they are subscribed to self.common_subscribe_to_streams(sipbtest.email, [mit_stream.name], subdomain="zephyr") access_stream_by_id(sipbtest, mit_stream.id) access_stream_by_name(sipbtest, mit_stream.name) def test_stream_access_by_guest(self) -> None: guest_user_profile = self.example_user('polonius') self.login(guest_user_profile.email) stream_name = "public_stream_1" stream = self.make_stream(stream_name, guest_user_profile.realm, invite_only=False) # Guest user don't have access to unsubscribed public streams with self.assertRaisesRegex(JsonableError, "Invalid stream id"): access_stream_by_id(guest_user_profile, stream.id) # Guest user have access to subscribed public streams self.subscribe(guest_user_profile, stream_name) (stream_ret, rec_ret, sub_ret) = access_stream_by_id(guest_user_profile, stream.id) assert sub_ret is not None self.assertEqual(stream.id, stream_ret.id) self.assertEqual(sub_ret.recipient, rec_ret) self.assertEqual(sub_ret.recipient.type_id, stream.id) stream_name = "private_stream_1" stream = self.make_stream(stream_name, guest_user_profile.realm, invite_only=True) # Obviously, a guest user doesn't have access to unsubscribed private streams either with self.assertRaisesRegex(JsonableError, "Invalid stream id"): access_stream_by_id(guest_user_profile, stream.id) # Guest user have access to subscribed private streams self.subscribe(guest_user_profile, stream_name) (stream_ret, rec_ret, sub_ret) = access_stream_by_id(guest_user_profile, stream.id) assert sub_ret is not None self.assertEqual(stream.id, stream_ret.id) self.assertEqual(sub_ret.recipient, rec_ret) self.assertEqual(sub_ret.recipient.type_id, stream.id) class StreamTrafficTest(ZulipTestCase): def test_average_weekly_stream_traffic_calculation(self) -> None: # No traffic data for the stream self.assertEqual( get_average_weekly_stream_traffic(42, timezone_now() - timedelta(days=300), {1: 4003}), 0) # using high numbers here to make it more likely to catch small errors in the denominators # of the calculations. That being said we don't want to go over 100, since then the 2 # significant digits calculation gets applied # old stream self.assertEqual( get_average_weekly_stream_traffic(42, timezone_now() - timedelta(days=300), {42: 98*4+3}), 98) # stream between 7 and 27 days old self.assertEqual( get_average_weekly_stream_traffic(42, timezone_now() - timedelta(days=10), {42: (98*10+9) // 7}), 98) # stream less than 7 days old self.assertEqual( get_average_weekly_stream_traffic(42, timezone_now() - timedelta(days=5), {42: 100}), None) # average traffic between 0 and 1 self.assertEqual( get_average_weekly_stream_traffic(42, timezone_now() - timedelta(days=300), {42: 1}), 1) def test_round_to_2_significant_digits(self) -> None: self.assertEqual(120, round_to_2_significant_digits(116))
[ "str", "Stream", "int", "Realm", "Realm", "DefaultStreamGroup", "Any", "str", "HttpRequest", "UserProfile", "HttpRequest", "UserProfile", "List[str]", "List[str]", "Dict[str, Any]", "List[str]", "List[str]", "str", "List[str]", "Realm", "str", "Realm", "List[str]", "List[str]", "Dict[str, Any]", "str", "List[str]", "Realm", "str", "bool", "bool", "UserProfile", "str", "str", "str", "str", "Dict[str, Any]", "str", "Realm", "int", "str" ]
[ 30228, 30833, 35170, 42173, 42387, 48464, 74842, 74865, 78505, 78532, 78717, 78744, 79652, 81370, 81442, 81517, 81595, 81660, 81675, 81740, 95594, 95614, 95680, 115847, 115919, 115992, 116007, 116075, 118886, 118907, 118925, 123727, 123753, 129213, 140005, 140305, 140491, 140520, 140532, 141178, 141427 ]
[ 30231, 30839, 35173, 42178, 42392, 48482, 74845, 74868, 78516, 78543, 78728, 78755, 79661, 81379, 81456, 81526, 81604, 81663, 81684, 81745, 95597, 95619, 95689, 115856, 115933, 115995, 116016, 116080, 118889, 118911, 118929, 123738, 123756, 129216, 140008, 140308, 140505, 140523, 140537, 141181, 141430 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_templates.py
# -*- coding: utf-8 -*- import os import re from typing import Any, Dict, Iterable import logging from django.conf import settings from django.test import override_settings from django.template import Template, Context from django.template.loader import get_template from zerver.lib.test_helpers import get_all_templates from zerver.lib.test_classes import ( ZulipTestCase, ) from zerver.lib.test_runner import slow from zerver.context_processors import common_context class get_form_value: def __init__(self, value: Any) -> None: self._value = value def value(self) -> Any: return self._value class DummyForm(Dict[str, Any]): pass class TemplateTestCase(ZulipTestCase): """ Tests that backend template rendering doesn't crash. This renders all the Zulip backend templates, passing dummy data as the context, which allows us to verify whether any of the templates are broken enough to not render at all (no verification is done that the output looks right). Please see `get_context` function documentation for more information. """ @slow("Tests a large number of different templates") @override_settings(TERMS_OF_SERVICE=None) def test_templates(self) -> None: # Just add the templates whose context has a conflict with other # templates' context in `defer`. defer = ['analytics/activity.html'] # Django doesn't send template_rendered signal for parent templates # https://code.djangoproject.com/ticket/24622 covered = [ 'zerver/portico.html', 'zerver/portico_signup.html', ] logged_out = [ 'confirmation/confirm.html', # seems unused 'zerver/compare.html', 'zerver/footer.html', ] logged_in = [ 'analytics/stats.html', 'zerver/drafts.html', 'zerver/home.html', 'zerver/invite_user.html', 'zerver/keyboard_shortcuts.html', 'zerver/left_sidebar.html', 'zerver/landing_nav.html', 'zerver/logout.html', 'zerver/markdown_help.html', 'zerver/navbar.html', 'zerver/right_sidebar.html', 'zerver/search_operators.html', 'zerver/settings_overlay.html', 'zerver/settings_sidebar.html', 'zerver/stream_creation_prompt.html', 'zerver/subscriptions.html', 'zerver/message_history.html', 'zerver/delete_message.html', ] unusual = [ 'zerver/emails/confirm_new_email.subject', 'zerver/emails/compiled/confirm_new_email.html', 'zerver/emails/confirm_new_email.txt', 'zerver/emails/notify_change_in_email.subject', 'zerver/emails/compiled/notify_change_in_email.html', 'zerver/emails/digest.subject', 'zerver/emails/digest.html', 'zerver/emails/digest.txt', 'zerver/emails/followup_day1.subject', 'zerver/emails/compiled/followup_day1.html', 'zerver/emails/followup_day1.txt', 'zerver/emails/followup_day2.subject', 'zerver/emails/followup_day2.txt', 'zerver/emails/compiled/followup_day2.html', 'zerver/emails/compiled/password_reset.html', 'corporate/mit.html', 'corporate/zephyr.html', 'corporate/zephyr-mirror.html', 'pipeline/css.jinja', 'pipeline/inline_js.jinja', 'pipeline/js.jinja', 'zilencer/enterprise_tos_accept_body.txt', 'zerver/zulipchat_migration_tos.html', 'zilencer/enterprise_tos_accept_body.txt', 'zerver/invalid_email.html', 'zerver/topic_is_muted.html', 'zerver/bankruptcy.html', 'zerver/lightbox_overlay.html', 'zerver/invalid_realm.html', 'zerver/compose.html', 'zerver/debug.html', 'zerver/base.html', 'zerver/api_content.json', 'zerver/handlebars_compilation_failed.html', 'zerver/portico-header.html', 'zerver/deprecation_notice.html', 'two_factor/_wizard_forms.html', ] integrations_regexp = re.compile('zerver/integrations/.*.html') # Since static/generated/bots/ is searched by Jinja2 for templates, # it mistakes logo files under that directory for templates. bot_logos_regexp = re.compile(r'\w+\/logo\.(svg|png)$') skip = covered + defer + logged_out + logged_in + unusual + ['tests/test_markdown.html', 'zerver/terms.html', 'zerver/privacy.html'] templates = [t for t in get_all_templates() if not ( t in skip or integrations_regexp.match(t) or bot_logos_regexp.match(t))] self.render_templates(templates, self.get_context()) # Test the deferred templates with updated context. update = {'data': [('one', 'two')]} self.render_templates(defer, self.get_context(**update)) def render_templates(self, templates: Iterable[str], context: Dict[str, Any]) -> None: for template_name in templates: template = get_template(template_name) try: template.render(context) except Exception: # nocoverage # nicer error handler logging.error("Exception while rendering '{}'".format(template.template.name)) raise def get_context(self, **kwargs: Any) -> Dict[str, Any]: """Get the dummy context for shallow testing. The context returned will always contain a parameter called `shallow_tested`, which tells the signal receiver that the test was not rendered in an actual logical test (so we can still do coverage reporting on which templates have a logical test). Note: `context` just holds dummy values used to make the test pass. This context only ensures that the templates do not throw a 500 error when rendered using dummy data. If new required parameters are added to a template, this test will fail; the usual fix is to just update the context below to add the new parameter to the dummy data. :param kwargs: Keyword arguments can be used to update the base context. """ user_profile = self.example_user('hamlet') email = user_profile.email context = dict( sidebar_index="zerver/help/include/sidebar_index.md", doc_root="/help/", article="zerver/help/index.md", shallow_tested=True, user_profile=user_profile, user=user_profile, form=DummyForm( full_name=get_form_value('John Doe'), terms=get_form_value(True), email=get_form_value(email), emails=get_form_value(email), ), current_url=lambda: 'www.zulip.com', integrations_dict={}, referrer=dict( full_name='John Doe', realm=dict(name='zulip.com'), ), message_count=0, messages=[dict(header='Header')], new_streams=dict(html=''), data=dict(title='Title'), device_info={"device_browser": "Chrome", "device_os": "Windows", "device_ip": "127.0.0.1", "login_time": "9:33am NewYork, NewYork", }, api_uri_context={}, cloud_annual_price=80, seat_count=8, ) context.update(kwargs) return context def test_markdown_in_template(self) -> None: template = get_template("tests/test_markdown.html") context = { 'markdown_test_file': "zerver/tests/markdown/test_markdown.md" } content = template.render(context) content_sans_whitespace = content.replace(" ", "").replace('\n', '') self.assertEqual(content_sans_whitespace, 'header<h1id="hello">Hello!</h1><p>Thisissome<em>boldtext</em>.</p>footer') def test_markdown_tabbed_sections_extension(self) -> None: template = get_template("tests/test_markdown.html") context = { 'markdown_test_file': "zerver/tests/markdown/test_tabbed_sections.md" } content = template.render(context) content_sans_whitespace = content.replace(" ", "").replace('\n', '') # Note that the expected HTML has a lot of stray <p> tags. This is a # consequence of how the Markdown renderer converts newlines to HTML # and how elements are delimited by newlines and so forth. However, # stray <p> tags are usually matched with closing tags by HTML renderers # so this doesn't affect the final rendered UI in any visible way. expected_html = """ header <h1 id="heading">Heading</h1> <p> <div class="code-section" markdown="1"> <ul class="nav"> <li data-language="ios">iOS</li> <li data-language="desktop-web">Desktop/Web</li> </ul> <div class="blocks"> <div data-language="ios" markdown="1"></p> <p>iOS instructions</p> <p></div> <div data-language="desktop-web" markdown="1"></p> <p>Desktop/browser instructions</p> <p></div> </div> </div> </p> <h2 id="heading-2">Heading 2</h2> <p> <div class="code-section" markdown="1"> <ul class="nav"> <li data-language="desktop-web">Desktop/Web</li> <li data-language="android">Android</li> </ul> <div class="blocks"> <div data-language="desktop-web" markdown="1"></p> <p>Desktop/browser instructions</p> <p></div> <div data-language="android" markdown="1"></p> <p>Android instructions</p> <p></div> </div> </div> </p> footer """ expected_html_sans_whitespace = expected_html.replace(" ", "").replace('\n', '') self.assertEqual(content_sans_whitespace, expected_html_sans_whitespace) def test_encoded_unicode_decimals_in_markdown_template(self) -> None: template = get_template("tests/test_unicode_decimals.html") context = {'unescape_rendered_html': False} content = template.render(context) content_sans_whitespace = content.replace(" ", "").replace('\n', '') self.assertEqual(content_sans_whitespace, 'header<p>&#123;&#125;</p>footer') context = {'unescape_rendered_html': True} content = template.render(context) content_sans_whitespace = content.replace(" ", "").replace('\n', '') self.assertEqual(content_sans_whitespace, 'header<p>{}</p>footer') def test_markdown_nested_code_blocks(self) -> None: template = get_template("tests/test_markdown.html") context = { 'markdown_test_file': "zerver/tests/markdown/test_nested_code_blocks.md" } content = template.render(context) content_sans_whitespace = content.replace(" ", "").replace('\n', '') expected = ('header<h1id="this-is-a-heading">Thisisaheading.</h1><ol>' '<li><p>Alistitemwithanindentedcodeblock:</p><divclass="codehilite">' '<pre>indentedcodeblockwithmultiplelines</pre></div></li></ol>' '<divclass="codehilite"><pre><span></span>' 'non-indentedcodeblockwithmultiplelines</pre></div>footer') self.assertEqual(content_sans_whitespace, expected) def test_custom_tos_template(self) -> None: response = self.client_get("/terms/") self.assert_in_success_response([u"Thanks for using our products and services (\"Services\"). ", u"By using our Services, you are agreeing to these terms"], response) def test_custom_terms_of_service_template(self) -> None: not_configured_message = 'This installation of Zulip does not have a configured ' \ 'terms of service' with self.settings(TERMS_OF_SERVICE=None): response = self.client_get('/terms/') self.assert_in_success_response([not_configured_message], response) with self.settings(TERMS_OF_SERVICE='zerver/tests/markdown/test_markdown.md'): response = self.client_get('/terms/') self.assert_in_success_response(['This is some <em>bold text</em>.'], response) self.assert_not_in_success_response([not_configured_message], response) def test_custom_privacy_policy_template(self) -> None: not_configured_message = 'This installation of Zulip does not have a configured ' \ 'privacy policy' with self.settings(PRIVACY_POLICY=None): response = self.client_get('/privacy/') self.assert_in_success_response([not_configured_message], response) with self.settings(PRIVACY_POLICY='zerver/tests/markdown/test_markdown.md'): response = self.client_get('/privacy/') self.assert_in_success_response(['This is some <em>bold text</em>.'], response) self.assert_not_in_success_response([not_configured_message], response) def test_custom_privacy_policy_template_with_absolute_url(self) -> None: current_dir = os.path.dirname(os.path.abspath(__file__)) abs_path = os.path.join(current_dir, '..', '..', 'templates/zerver/tests/markdown/test_markdown.md') with self.settings(PRIVACY_POLICY=abs_path): response = self.client_get('/privacy/') self.assert_in_success_response(['This is some <em>bold text</em>.'], response)
[ "Any", "Iterable[str]", "Dict[str, Any]", "Any" ]
[ 530, 5281, 5305, 5699 ]
[ 533, 5294, 5319, 5702 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_thumbnail.py
# -*- coding: utf-8 -*- from django.conf import settings from zerver.lib.test_classes import ZulipTestCase, UploadSerializeMixin from zerver.lib.test_helpers import ( use_s3_backend, override_settings, get_test_image_file ) from zerver.lib.upload import upload_backend, upload_emoji_image from zerver.lib.users import get_api_key from io import StringIO from boto.s3.connection import S3Connection import ujson import urllib import base64 class ThumbnailTest(ZulipTestCase): @use_s3_backend def test_s3_source_type(self) -> None: def get_file_path_urlpart(uri: str, size: str='') -> str: url_in_result = 'smart/filters:no_upscale():sharpen(0.5,0.2,true)/%s/source_type/s3' if size: url_in_result = '/%s/%s' % (size, url_in_result) hex_uri = base64.urlsafe_b64encode(uri.encode()).decode('utf-8') return url_in_result % (hex_uri) conn = S3Connection(settings.S3_KEY, settings.S3_SECRET_KEY) conn.create_bucket(settings.S3_AUTH_UPLOADS_BUCKET) conn.create_bucket(settings.S3_AVATAR_BUCKET) self.login(self.example_email("hamlet")) fp = StringIO("zulip!") fp.name = "zulip.jpeg" result = self.client_post("/json/user_uploads", {'file': fp}) self.assert_json_success(result) json = ujson.loads(result.content) self.assertIn("uri", json) uri = json["uri"] base = '/user_uploads/' self.assertEqual(base, uri[:len(base)]) quoted_uri = urllib.parse.quote(uri[1:], safe='') # Test full size image. result = self.client_get("/thumbnail?url=%s&size=full" % (quoted_uri)) self.assertEqual(result.status_code, 302, result) expected_part_url = get_file_path_urlpart(uri) self.assertIn(expected_part_url, result.url) # Test thumbnail size. result = self.client_get("/thumbnail?url=%s&size=thumbnail" % (quoted_uri)) self.assertEqual(result.status_code, 302, result) expected_part_url = get_file_path_urlpart(uri, '0x300') self.assertIn(expected_part_url, result.url) # Test custom emoji urls in Zulip messages. user_profile = self.example_user("hamlet") image_file = get_test_image_file("img.png") file_name = "emoji.png" upload_emoji_image(image_file, file_name, user_profile) custom_emoji_url = upload_backend.get_emoji_url(file_name, user_profile.realm_id) emoji_url_base = '/user_avatars/' self.assertEqual(emoji_url_base, custom_emoji_url[:len(emoji_url_base)]) quoted_emoji_url = urllib.parse.quote(custom_emoji_url[1:], safe='') # Test full size custom emoji image (for emoji link in messages case). result = self.client_get("/thumbnail?url=%s&size=full" % (quoted_emoji_url)) self.assertEqual(result.status_code, 302, result) self.assertIn(custom_emoji_url, result.url) # Tests the /api/v1/thumbnail api endpoint with standard API auth self.logout() result = self.api_get( self.example_email("hamlet"), '/thumbnail?url=%s&size=full' % (quoted_uri,)) self.assertEqual(result.status_code, 302, result) expected_part_url = get_file_path_urlpart(uri) self.assertIn(expected_part_url, result.url) # Test with another user trying to access image using thumbor. self.login(self.example_email("iago")) result = self.client_get("/thumbnail?url=%s&size=full" % (quoted_uri)) self.assertEqual(result.status_code, 403, result) self.assert_in_response("You are not authorized to view this file.", result) def test_external_source_type(self) -> None: def run_test_with_image_url(image_url: str) -> None: # Test full size image. self.login(self.example_email("hamlet")) quoted_url = urllib.parse.quote(image_url, safe='') encoded_url = base64.urlsafe_b64encode(image_url.encode()).decode('utf-8') result = self.client_get("/thumbnail?url=%s&size=full" % (quoted_url)) self.assertEqual(result.status_code, 302, result) expected_part_url = '/smart/filters:no_upscale():sharpen(0.5,0.2,true)/' + encoded_url + '/source_type/external' self.assertIn(expected_part_url, result.url) # Test thumbnail size. result = self.client_get("/thumbnail?url=%s&size=thumbnail" % (quoted_url)) self.assertEqual(result.status_code, 302, result) expected_part_url = '/0x300/smart/filters:no_upscale():sharpen(0.5,0.2,true)/' + encoded_url + '/source_type/external' self.assertIn(expected_part_url, result.url) # Test api endpoint with standard API authentication. self.logout() user_profile = self.example_user("hamlet") result = self.api_get(user_profile.email, "/thumbnail?url=%s&size=thumbnail" % (quoted_url,)) self.assertEqual(result.status_code, 302, result) expected_part_url = '/0x300/smart/filters:no_upscale():sharpen(0.5,0.2,true)/' + encoded_url + '/source_type/external' self.assertIn(expected_part_url, result.url) # Test api endpoint with legacy API authentication. user_profile = self.example_user("hamlet") result = self.client_get("/thumbnail?url=%s&size=thumbnail&api_key=%s" % ( quoted_url, get_api_key(user_profile))) self.assertEqual(result.status_code, 302, result) expected_part_url = '/0x300/smart/filters:no_upscale():sharpen(0.5,0.2,true)/' + encoded_url + '/source_type/external' self.assertIn(expected_part_url, result.url) # Test a second logged-in user; they should also be able to access it user_profile = self.example_user("iago") result = self.client_get("/thumbnail?url=%s&size=thumbnail&api_key=%s" % ( quoted_url, get_api_key(user_profile))) self.assertEqual(result.status_code, 302, result) expected_part_url = '/0x300/smart/filters:no_upscale():sharpen(0.5,0.2,true)/' + encoded_url + '/source_type/external' self.assertIn(expected_part_url, result.url) # Test with another user trying to access image using thumbor. # File should be always accessible to user in case of external source self.login(self.example_email("iago")) result = self.client_get("/thumbnail?url=%s&size=full" % (quoted_url)) self.assertEqual(result.status_code, 302, result) expected_part_url = '/smart/filters:no_upscale():sharpen(0.5,0.2,true)/' + encoded_url + '/source_type/external' self.assertIn(expected_part_url, result.url) image_url = 'https://images.foobar.com/12345' run_test_with_image_url(image_url) image_url = 'http://images.foobar.com/12345' run_test_with_image_url(image_url) def test_local_file_type(self) -> None: def get_file_path_urlpart(uri: str, size: str='') -> str: url_in_result = 'smart/filters:no_upscale():sharpen(0.5,0.2,true)/%s/source_type/local_file' if size: url_in_result = '/%s/%s' % (size, url_in_result) hex_uri = base64.urlsafe_b64encode(uri.encode()).decode('utf-8') return url_in_result % (hex_uri) self.login(self.example_email("hamlet")) fp = StringIO("zulip!") fp.name = "zulip.jpeg" result = self.client_post("/json/user_uploads", {'file': fp}) self.assert_json_success(result) json = ujson.loads(result.content) self.assertIn("uri", json) uri = json["uri"] base = '/user_uploads/' self.assertEqual(base, uri[:len(base)]) # Test full size image. # We remove the forward slash infront of the `/user_uploads/` to match # bugdown behaviour. quoted_uri = urllib.parse.quote(uri[1:], safe='') result = self.client_get("/thumbnail?url=%s&size=full" % (quoted_uri)) self.assertEqual(result.status_code, 302, result) expected_part_url = get_file_path_urlpart(uri) self.assertIn(expected_part_url, result.url) # Test thumbnail size. result = self.client_get("/thumbnail?url=%s&size=thumbnail" % (quoted_uri)) self.assertEqual(result.status_code, 302, result) expected_part_url = get_file_path_urlpart(uri, '0x300') self.assertIn(expected_part_url, result.url) # Test with a unicode filename. fp = StringIO("zulip!") fp.name = "μένει.jpg" result = self.client_post("/json/user_uploads", {'file': fp}) self.assert_json_success(result) json = ujson.loads(result.content) self.assertIn("uri", json) uri = json["uri"] # We remove the forward slash infront of the `/user_uploads/` to match # bugdown behaviour. quoted_uri = urllib.parse.quote(uri[1:], safe='') result = self.client_get("/thumbnail?url=%s&size=full" % (quoted_uri)) self.assertEqual(result.status_code, 302, result) expected_part_url = get_file_path_urlpart(uri) self.assertIn(expected_part_url, result.url) # Test custom emoji urls in Zulip messages. user_profile = self.example_user("hamlet") image_file = get_test_image_file("img.png") file_name = "emoji.png" upload_emoji_image(image_file, file_name, user_profile) custom_emoji_url = upload_backend.get_emoji_url(file_name, user_profile.realm_id) emoji_url_base = '/user_avatars/' self.assertEqual(emoji_url_base, custom_emoji_url[:len(emoji_url_base)]) quoted_emoji_url = urllib.parse.quote(custom_emoji_url[1:], safe='') # Test full size custom emoji image (for emoji link in messages case). result = self.client_get("/thumbnail?url=%s&size=full" % (quoted_emoji_url)) self.assertEqual(result.status_code, 302, result) self.assertIn(custom_emoji_url, result.url) # Tests the /api/v1/thumbnail api endpoint with HTTP basic auth. self.logout() user_profile = self.example_user("hamlet") result = self.api_get( self.example_email("hamlet"), '/thumbnail?url=%s&size=full' % (quoted_uri,)) self.assertEqual(result.status_code, 302, result) expected_part_url = get_file_path_urlpart(uri) self.assertIn(expected_part_url, result.url) # Tests the /api/v1/thumbnail api endpoint with ?api_key # auth. user_profile = self.example_user("hamlet") result = self.client_get( '/thumbnail?url=%s&size=full&api_key=%s' % (quoted_uri, get_api_key(user_profile))) self.assertEqual(result.status_code, 302, result) expected_part_url = get_file_path_urlpart(uri) self.assertIn(expected_part_url, result.url) # Test with another user trying to access image using thumbor. self.login(self.example_email("iago")) result = self.client_get("/thumbnail?url=%s&size=full" % (quoted_uri)) self.assertEqual(result.status_code, 403, result) self.assert_in_response("You are not authorized to view this file.", result) @override_settings(THUMBOR_URL='127.0.0.1:9995') def test_with_static_files(self) -> None: self.login(self.example_email("hamlet")) uri = '/static/images/cute/turtle.png' quoted_uri = urllib.parse.quote(uri[1:], safe='') result = self.client_get("/thumbnail?url=%s&size=full" % (quoted_uri)) self.assertEqual(result.status_code, 302, result) self.assertEqual(uri, result.url) def test_with_thumbor_disabled(self) -> None: self.login(self.example_email("hamlet")) fp = StringIO("zulip!") fp.name = "zulip.jpeg" result = self.client_post("/json/user_uploads", {'file': fp}) self.assert_json_success(result) json = ujson.loads(result.content) self.assertIn("uri", json) uri = json["uri"] base = '/user_uploads/' self.assertEqual(base, uri[:len(base)]) quoted_uri = urllib.parse.quote(uri[1:], safe='') with self.settings(THUMBOR_URL=''): result = self.client_get("/thumbnail?url=%s&size=full" % (quoted_uri)) self.assertEqual(result.status_code, 302, result) self.assertEqual(uri, result.url) uri = 'https://www.google.com/images/srpr/logo4w.png' quoted_uri = urllib.parse.quote(uri, safe='') with self.settings(THUMBOR_URL=''): result = self.client_get("/thumbnail?url=%s&size=full" % (quoted_uri)) self.assertEqual(result.status_code, 302, result) self.assertEqual(uri, result.url) uri = 'http://www.google.com/images/srpr/logo4w.png' quoted_uri = urllib.parse.quote(uri, safe='') with self.settings(THUMBOR_URL=''): result = self.client_get("/thumbnail?url=%s&size=full" % (quoted_uri)) self.assertEqual(result.status_code, 302, result) base = 'https://external-content.zulipcdn.net/external_content/7b6552b60c635e41e8f6daeb36d88afc4eabde79/687474703a2f2f7777772e676f6f676c652e636f6d2f696d616765732f737270722f6c6f676f34772e706e67' self.assertEqual(base, result.url) def test_with_different_THUMBOR_URL(self) -> None: self.login(self.example_email("hamlet")) fp = StringIO("zulip!") fp.name = "zulip.jpeg" result = self.client_post("/json/user_uploads", {'file': fp}) self.assert_json_success(result) json = ujson.loads(result.content) self.assertIn("uri", json) uri = json["uri"] base = '/user_uploads/' self.assertEqual(base, uri[:len(base)]) quoted_uri = urllib.parse.quote(uri[1:], safe='') hex_uri = base64.urlsafe_b64encode(uri.encode()).decode('utf-8') with self.settings(THUMBOR_URL='http://test-thumborhost.com'): result = self.client_get("/thumbnail?url=%s&size=full" % (quoted_uri)) self.assertEqual(result.status_code, 302, result) base = 'http://test-thumborhost.com/' self.assertEqual(base, result.url[:len(base)]) expected_part_url = '/smart/filters:no_upscale():sharpen(0.5,0.2,true)/' + hex_uri + '/source_type/local_file' self.assertIn(expected_part_url, result.url) def test_with_different_sizes(self) -> None: def get_file_path_urlpart(uri: str, size: str='') -> str: url_in_result = 'smart/filters:no_upscale():sharpen(0.5,0.2,true)/%s/source_type/local_file' if size: url_in_result = '/%s/%s' % (size, url_in_result) hex_uri = base64.urlsafe_b64encode(uri.encode()).decode('utf-8') return url_in_result % (hex_uri) self.login(self.example_email("hamlet")) fp = StringIO("zulip!") fp.name = "zulip.jpeg" result = self.client_post("/json/user_uploads", {'file': fp}) self.assert_json_success(result) json = ujson.loads(result.content) self.assertIn("uri", json) uri = json["uri"] base = '/user_uploads/' self.assertEqual(base, uri[:len(base)]) # Test with size supplied as a query parameter. # size=thumbnail should return a 0x300 sized image. # size=full should return the original resolution image. quoted_uri = urllib.parse.quote(uri[1:], safe='') result = self.client_get("/thumbnail?url=%s&size=thumbnail" % (quoted_uri)) self.assertEqual(result.status_code, 302, result) expected_part_url = get_file_path_urlpart(uri, '0x300') self.assertIn(expected_part_url, result.url) result = self.client_get("/thumbnail?url=%s&size=full" % (quoted_uri)) self.assertEqual(result.status_code, 302, result) expected_part_url = get_file_path_urlpart(uri) self.assertIn(expected_part_url, result.url) # Test with size supplied as a query parameter where size is anything # else than 'full' or 'thumbnail'. Result should be an error message. result = self.client_get("/thumbnail?url=%s&size=480x360" % (quoted_uri)) self.assertEqual(result.status_code, 403, result) self.assert_in_response("Invalid size.", result) # Test with no size param supplied. In this case as well we show an # error message. result = self.client_get("/thumbnail?url=%s" % (quoted_uri)) self.assertEqual(result.status_code, 400, "Missing 'size' argument")
[ "str", "str", "str", "str" ]
[ 593, 3810, 7160, 14677 ]
[ 596, 3813, 7163, 14680 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_timestamp.py
from django.utils.timezone import utc as timezone_utc from zerver.lib.test_classes import ZulipTestCase from zerver.lib.timestamp import floor_to_hour, floor_to_day, ceiling_to_hour, \ ceiling_to_day, timestamp_to_datetime, datetime_to_timestamp, \ TimezoneNotUTCException, convert_to_UTC from datetime import datetime, timedelta from dateutil import parser import pytz class TestTimestamp(ZulipTestCase): def test_datetime_and_timestamp_conversions(self) -> None: timestamp = 1483228800 for dt in [ parser.parse('2017-01-01 00:00:00.123 UTC'), parser.parse('2017-01-01 00:00:00.123').replace(tzinfo=timezone_utc), parser.parse('2017-01-01 00:00:00.123').replace(tzinfo=pytz.utc)]: self.assertEqual(timestamp_to_datetime(timestamp), dt-timedelta(microseconds=123000)) self.assertEqual(datetime_to_timestamp(dt), timestamp) for dt in [ parser.parse('2017-01-01 00:00:00.123+01:00'), parser.parse('2017-01-01 00:00:00.123')]: with self.assertRaises(TimezoneNotUTCException): datetime_to_timestamp(dt) def test_convert_to_UTC(self) -> None: utc_datetime = parser.parse('2017-01-01 00:00:00.123 UTC') for dt in [ parser.parse('2017-01-01 00:00:00.123').replace(tzinfo=timezone_utc), parser.parse('2017-01-01 00:00:00.123'), parser.parse('2017-01-01 05:00:00.123+05')]: self.assertEqual(convert_to_UTC(dt), utc_datetime) def test_enforce_UTC(self) -> None: non_utc_datetime = parser.parse('2017-01-01 00:00:00.123') for function in [floor_to_hour, floor_to_day, ceiling_to_hour, ceiling_to_hour]: with self.assertRaises(TimezoneNotUTCException): function(non_utc_datetime)
[]
[]
[]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_tornado.py
# -*- coding: utf-8 -*- """WebSocketBaseTestCase is based on combination of Tornado and Django test systems. It require to use decorator '@gen.coroutine' for each test case method( see documentation: http://www.tornadoweb.org/en/stable/testing.html). It requires implementation of 'get_app' method to initialize tornado application and launch it. """ import time import ujson from django.conf import settings from django.http import HttpRequest, HttpResponse from django.db import close_old_connections from django.core import signals from django.test import override_settings from tornado.gen import Return from tornado.httpclient import HTTPRequest, HTTPResponse from zerver.lib.test_helpers import POSTRequestMock from zerver.lib.test_classes import ZulipTestCase from zerver.lib.topic import TOPIC_NAME from zerver.models import UserProfile, get_client from tornado import gen from tornado.testing import AsyncHTTPTestCase, gen_test from tornado.web import Application from tornado.websocket import websocket_connect from zerver.tornado.application import create_tornado_application from zerver.tornado import event_queue from zerver.tornado.event_queue import fetch_events, \ allocate_client_descriptor, process_event from zerver.tornado.views import get_events from http.cookies import SimpleCookie import urllib.parse from unittest.mock import patch from typing import Any, Callable, Dict, Generator, Optional, List, cast class TornadoWebTestCase(AsyncHTTPTestCase, ZulipTestCase): def setUp(self) -> None: super().setUp() signals.request_started.disconnect(close_old_connections) signals.request_finished.disconnect(close_old_connections) self.session_cookie = None # type: Optional[Dict[str, str]] def tearDown(self) -> None: super().tearDown() self.session_cookie = None # type: Optional[Dict[str, str]] @override_settings(DEBUG=False) def get_app(self) -> Application: return create_tornado_application(9993) def client_get(self, path: str, **kwargs: Any) -> HTTPResponse: self.add_session_cookie(kwargs) self.set_http_host(kwargs) if 'HTTP_HOST' in kwargs: kwargs['headers']['Host'] = kwargs['HTTP_HOST'] del kwargs['HTTP_HOST'] return self.fetch(path, method='GET', **kwargs) def fetch_async(self, method: str, path: str, **kwargs: Any) -> None: self.add_session_cookie(kwargs) self.set_http_host(kwargs) if 'HTTP_HOST' in kwargs: kwargs['headers']['Host'] = kwargs['HTTP_HOST'] del kwargs['HTTP_HOST'] self.http_client.fetch( self.get_url(path), self.stop, method=method, **kwargs ) def client_get_async(self, path: str, **kwargs: Any) -> None: self.set_http_host(kwargs) self.fetch_async('GET', path, **kwargs) def login(self, *args: Any, **kwargs: Any) -> None: super().login(*args, **kwargs) session_cookie = settings.SESSION_COOKIE_NAME session_key = self.client.session.session_key self.session_cookie = { "Cookie": "{}={}".format(session_cookie, session_key) } def get_session_cookie(self) -> Dict[str, str]: return {} if self.session_cookie is None else self.session_cookie def add_session_cookie(self, kwargs: Dict[str, Any]) -> None: # TODO: Currently only allows session cookie headers = kwargs.get('headers', {}) headers.update(self.get_session_cookie()) kwargs['headers'] = headers def create_queue(self, **kwargs: Any) -> str: response = self.client_get('/json/events?dont_block=true', subdomain="zulip") self.assertEqual(response.code, 200) body = ujson.loads(response.body) self.assertEqual(body['events'], []) self.assertIn('queue_id', body) return body['queue_id'] class EventsTestCase(TornadoWebTestCase): def test_create_queue(self) -> None: self.login(self.example_email('hamlet')) queue_id = self.create_queue() self.assertIn(queue_id, event_queue.clients) def test_events_async(self) -> None: user_profile = self.example_user('hamlet') self.login(user_profile.email) event_queue_id = self.create_queue() data = { 'queue_id': event_queue_id, 'last_event_id': 0, } path = '/json/events?{}'.format(urllib.parse.urlencode(data)) self.client_get_async(path) def process_events() -> None: users = [user_profile.id] event = dict( type='test', data='test data', ) process_event(event, users) self.io_loop.call_later(0.1, process_events) response = self.wait() data = ujson.loads(response.body) events = data['events'] events = cast(List[Dict[str, Any]], events) self.assertEqual(len(events), 1) self.assertEqual(events[0]['data'], 'test data') self.assertEqual(data['result'], 'success') class WebSocketBaseTestCase(AsyncHTTPTestCase, ZulipTestCase): def setUp(self) -> None: settings.RUNNING_INSIDE_TORNADO = True super().setUp() def tearDown(self) -> None: super().tearDown() settings.RUNNING_INSIDE_TORNADO = False @gen.coroutine def ws_connect(self, path: str, cookie_header: str, compression_options: Optional[Any]=None ) -> Generator[Any, Callable[[HTTPRequest, Optional[Any]], Any], None]: request = HTTPRequest(url='ws://127.0.0.1:%d%s' % (self.get_http_port(), path)) request.headers.add('Cookie', cookie_header) ws = yield websocket_connect( request, compression_options=compression_options) raise gen.Return(ws) @gen.coroutine def close(self, ws: Any) -> None: """Close a websocket connection and wait for the server side. """ ws.close() class TornadoTestCase(WebSocketBaseTestCase): @override_settings(DEBUG=False) def get_app(self) -> Application: """ Return tornado app to launch for test cases """ return create_tornado_application(9993) @staticmethod def tornado_call(view_func: Callable[[HttpRequest, UserProfile], HttpResponse], user_profile: UserProfile, post_data: Dict[str, Any]) -> HttpResponse: request = POSTRequestMock(post_data, user_profile) return view_func(request, user_profile) @staticmethod def get_cookie_header(cookies: SimpleCookie) -> str: return ';'.join( ["{}={}".format(name, value.value) for name, value in cookies.items()]) def _get_cookies(self, user_profile: UserProfile) -> SimpleCookie: resp = self.login_with_return(user_profile.email) return resp.cookies @gen.coroutine def _websocket_auth(self, ws: Any, queue_events_data: Dict[str, Dict[str, str]], cookies: SimpleCookie) -> Generator[str, str, None]: auth_queue_id = ':'.join((queue_events_data['response']['queue_id'], '0')) message = { "req_id": auth_queue_id, "type": "auth", "request": { "csrf_token": cookies.get('csrftoken').coded_value, "queue_id": queue_events_data['response']['queue_id'], "status_inquiries": [] } } auth_frame_str = ujson.dumps(message) ws.write_message(ujson.dumps([auth_frame_str])) response_ack = yield ws.read_message() response_message = yield ws.read_message() raise gen.Return([response_ack, response_message]) @staticmethod def _get_queue_events_data(email: str) -> Dict[str, Dict[str, str]]: user_profile = UserProfile.objects.filter(email=email).first() events_query = { 'queue_id': None, 'narrow': [], 'handler_id': 0, 'user_profile_email': user_profile.email, 'all_public_streams': False, 'client_type_name': 'website', 'new_queue_data': { 'apply_markdown': True, 'client_gravatar': False, 'narrow': [], 'user_profile_email': user_profile.email, 'all_public_streams': False, 'realm_id': user_profile.realm_id, 'client_type_name': 'website', 'event_types': None, 'user_profile_id': user_profile.id, 'queue_timeout': 0, 'last_connection_time': time.time()}, 'last_event_id': -1, 'event_types': None, 'user_profile_id': user_profile.id, 'dont_block': True, 'lifespan_secs': 0 } result = fetch_events(events_query) return result def _check_message_sending(self, request_id: str, ack_resp: str, msg_resp: str, profile: UserProfile, queue_events_data: Dict[str, Dict[str, str]]) -> None: self.assertEqual(ack_resp[0], 'a') self.assertEqual( ujson.loads(ack_resp[1:]), [ { "type": "ack", "req_id": request_id } ]) self.assertEqual(msg_resp[0], 'a') result = self.tornado_call(get_events, profile, {"queue_id": queue_events_data['response']['queue_id'], "user_client": "website", "last_event_id": -1, "dont_block": ujson.dumps(True), }) result_content = ujson.loads(result.content) self.assertEqual(len(result_content['events']), 1) message_id = result_content['events'][0]['message']['id'] self.assertEqual( ujson.loads(msg_resp[1:]), [ { "type": "response", "response": { "result": "success", "id": message_id, "msg": "" }, "req_id": request_id } ]) @gen_test def test_tornado_connect(self) -> Generator[str, Any, None]: user_profile = self.example_user('hamlet') cookies = self._get_cookies(user_profile) cookie_header = self.get_cookie_header(cookies) ws = yield self.ws_connect('/sockjs/366/v8nw22qe/websocket', cookie_header=cookie_header) response = yield ws.read_message() self.assertEqual(response, 'o') yield self.close(ws) @gen_test def test_tornado_auth(self) -> Generator[str, 'TornadoTestCase', None]: user_profile = self.example_user('hamlet') cookies = self._get_cookies(user_profile) cookie_header = self.get_cookie_header(cookies) ws = yield self.ws_connect('/sockjs/366/v8nw22qe/websocket', cookie_header=cookie_header) yield ws.read_message() queue_events_data = self._get_queue_events_data(user_profile.email) request_id = ':'.join((queue_events_data['response']['queue_id'], '0')) response = yield self._websocket_auth(ws, queue_events_data, cookies) self.assertEqual(response[0][0], 'a') self.assertEqual( ujson.loads(response[0][1:]), [ { "type": "ack", "req_id": request_id } ]) self.assertEqual(response[1][0], 'a') self.assertEqual( ujson.loads(response[1][1:]), [ {"req_id": request_id, "response": { "result": "success", "status_inquiries": {}, "msg": "" }, "type": "response"} ]) yield self.close(ws) @gen_test def test_sending_private_message(self) -> Generator[str, Any, None]: user_profile = self.example_user('hamlet') cookies = self._get_cookies(user_profile) cookie_header = self.get_cookie_header(cookies) queue_events_data = self._get_queue_events_data(user_profile.email) ws = yield self.ws_connect('/sockjs/366/v8nw22qe/websocket', cookie_header=cookie_header) yield ws.read_message() yield self._websocket_auth(ws, queue_events_data, cookies) request_id = ':'.join((queue_events_data['response']['queue_id'], '1')) user_message = { "req_id": request_id, "type": "request", "request": { "client": "website", "type": "private", TOPIC_NAME: "(no topic)", "stream": "", "private_message_recipient": self.example_email('othello'), "content": "hello", "sender_id": user_profile.id, "queue_id": queue_events_data['response']['queue_id'], "to": ujson.dumps([self.example_email('othello')]), "reply_to": self.example_email('hamlet'), "local_id": -1 } } user_message_str = ujson.dumps(user_message) ws.write_message(ujson.dumps([user_message_str])) ack_resp = yield ws.read_message() msg_resp = yield ws.read_message() self._check_message_sending(request_id, ack_resp, msg_resp, user_profile, queue_events_data) yield self.close(ws) @gen_test def test_sending_stream_message(self) -> Generator[str, Any, None]: user_profile = self.example_user('hamlet') cookies = self._get_cookies(user_profile) cookie_header = self.get_cookie_header(cookies) queue_events_data = self._get_queue_events_data(user_profile.email) ws = yield self.ws_connect('/sockjs/366/v8nw22qe/websocket', cookie_header=cookie_header) yield ws.read_message() yield self._websocket_auth(ws, queue_events_data, cookies) request_id = ':'.join((queue_events_data['response']['queue_id'], '1')) user_message = { "req_id": request_id, "type": "request", "request": { "client": "website", "type": "stream", TOPIC_NAME: "Stream message", "stream": "Denmark", "private_message_recipient": "", "content": "hello", "sender_id": user_profile.id, "queue_id": queue_events_data['response']['queue_id'], "to": ujson.dumps(["Denmark"]), "reply_to": self.example_email('hamlet'), "local_id": -1 } } user_message_str = ujson.dumps(user_message) ws.write_message(ujson.dumps([user_message_str])) ack_resp = yield ws.read_message() msg_resp = yield ws.read_message() self._check_message_sending(request_id, ack_resp, msg_resp, user_profile, queue_events_data) yield self.close(ws) @gen_test def test_sending_stream_message_from_electron(self) -> Generator[str, Any, None]: user_profile = self.example_user('hamlet') cookies = self._get_cookies(user_profile) cookie_header = self.get_cookie_header(cookies) queue_events_data = self._get_queue_events_data(user_profile.email) ws = yield self.ws_connect('/sockjs/366/v8nw22qe/websocket', cookie_header=cookie_header) yield ws.read_message() yield self._websocket_auth(ws, queue_events_data, cookies) request_id = ':'.join((queue_events_data['response']['queue_id'], '1')) user_message = { "req_id": request_id, "type": "request", "request": { "client": "website", "type": "stream", TOPIC_NAME: "Stream message", "stream": "Denmark", "private_message_recipient": "", "content": "hello", "sender_id": user_profile.id, "queue_id": queue_events_data['response']['queue_id'], "to": ujson.dumps(["Denmark"]), "reply_to": self.example_email('hamlet'), "local_id": -1, "socket_user_agent": "ZulipElectron/1.5.0" } } user_message_str = ujson.dumps(user_message) ws.write_message(ujson.dumps([user_message_str])) ack_resp = yield ws.read_message() msg_resp = yield ws.read_message() self._check_message_sending(request_id, ack_resp, msg_resp, user_profile, queue_events_data) yield self.close(ws) @gen_test def test_sending_message_error(self) -> Any: user_profile = self.example_user('hamlet') cookies = self._get_cookies(user_profile) cookie_header = self.get_cookie_header(cookies) queue_events_data = self._get_queue_events_data(user_profile.email) ws = yield self.ws_connect('/sockjs/366/v8nw22qe/websocket', cookie_header=cookie_header) yield ws.read_message() yield self._websocket_auth(ws, queue_events_data, cookies) request_id = ':'.join((queue_events_data['response']['queue_id'], '1')) user_message = { "req_id": request_id, "type": "request", "request": { "client": "website", "type": "stream", TOPIC_NAME: "Stream message", "stream": "Denmark", "private_message_recipient": "", "content": "hello", "sender_id": user_profile.id, "queue_id": queue_events_data['response']['queue_id'], "to": ujson.dumps(["Denmark"]), "reply_to": self.example_email('hamlet'), "local_id": -1 } } user_message_str = ujson.dumps(user_message) ws.write_message(ujson.dumps([user_message_str])) def wrap_get_response(request: HttpRequest) -> HttpResponse: request._log_data = {'bugdown_requests_start': 0, 'time_started': 0, 'bugdown_time_start': 0, 'remote_cache_time_start': 0, 'remote_cache_requests_start': 0, 'startup_time_delta': 0} class ResponseObject(object): def __init__(self) -> None: self.content = '{"msg":"","id":0,"result":"error"}'.encode('utf8') return ResponseObject() # Simulate an error response to cover the respective code paths. with patch('django.core.handlers.base.BaseHandler.get_response', wraps=wrap_get_response), \ patch('django.db.connection.is_usable', return_value=False), \ patch('os.kill', side_effect=OSError()): yield ws.read_message() yield self.close(ws)
[ "str", "Any", "str", "str", "Any", "str", "Any", "Any", "Any", "Dict[str, Any]", "Any", "str", "str", "Any", "Callable[[HttpRequest, UserProfile], HttpResponse]", "UserProfile", "Dict[str, Any]", "SimpleCookie", "UserProfile", "Any", "Dict[str, Dict[str, str]]", "SimpleCookie", "str", "str", "str", "str", "UserProfile", "Dict[str, Dict[str, str]]", "HttpRequest" ]
[ 2043, 2058, 2376, 2387, 2402, 2804, 2819, 2944, 2959, 3397, 3643, 5458, 5478, 5959, 6362, 6449, 6494, 6688, 6861, 7031, 7079, 7139, 7894, 9075, 9121, 9167, 9212, 9275, 18452 ]
[ 2046, 2061, 2379, 2390, 2405, 2807, 2822, 2947, 2962, 3411, 3646, 5461, 5481, 5962, 6412, 6460, 6508, 6700, 6872, 7034, 7104, 7151, 7897, 9078, 9124, 9170, 9223, 9300, 18463 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_tutorial.py
# -*- coding: utf-8 -*- from zerver.lib.test_classes import ZulipTestCase from zerver.lib.test_helpers import message_stream_count, most_recent_message from zerver.models import get_realm, get_user, Recipient, UserProfile from typing import Any, Dict import ujson class TutorialTests(ZulipTestCase): def setUp(self) -> None: # This emulates the welcome message sent by the welcome bot to hamlet@zulip.com # This is only a quick fix - ideally, we would have this message sent by the initialization # code in populate_db.py user_email = 'hamlet@zulip.com' bot_email = 'welcome-bot@zulip.com' content = 'Shortened welcome message.' self.send_personal_message(bot_email, user_email, content) def test_tutorial_status(self) -> None: email = self.example_email('hamlet') self.login(email) cases = [ ('started', UserProfile.TUTORIAL_STARTED), ('finished', UserProfile.TUTORIAL_FINISHED), ] for incoming_status, expected_db_status in cases: params = dict(status=ujson.dumps(incoming_status)) result = self.client_post('/json/users/me/tutorial_status', params) self.assert_json_success(result) user = self.example_user('hamlet') self.assertEqual(user.tutorial_status, expected_db_status) def test_single_response_to_pm(self) -> None: realm = get_realm('zulip') user_email = 'hamlet@zulip.com' bot_email = 'welcome-bot@zulip.com' content = 'whatever' self.login(user_email) self.send_personal_message(user_email, bot_email, content) user = get_user(user_email, realm) user_messages = message_stream_count(user) expected_response = ("Congratulations on your first reply! :tada:\n\n" "Feel free to continue using this space to practice your new messaging " "skills. Or, try clicking on some of the stream names to your left!") self.assertEqual(most_recent_message(user).content, expected_response) # Welcome bot shouldn't respond to further PMs. self.send_personal_message(user_email, bot_email, content) self.assertEqual(message_stream_count(user), user_messages+1) def test_no_response_to_group_pm(self) -> None: realm = get_realm('zulip') # Assume realm is always 'zulip' user1_email = self.example_email('hamlet') user2_email = self.example_email('cordelia') bot_email = self.example_email('welcome_bot') content = "whatever" self.login(user1_email) self.send_huddle_message(user1_email, [bot_email, user2_email], content) user1 = get_user(user1_email, realm) user1_messages = message_stream_count(user1) self.assertEqual(most_recent_message(user1).content, content) # Welcome bot should still respond to initial PM after group PM. self.send_personal_message(user1_email, bot_email, content) self.assertEqual(message_stream_count(user1), user1_messages+2)
[]
[]
[]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_type_debug.py
import sys from unittest import TestCase from io import StringIO from zerver.lib.type_debug import print_types from typing import Any, Callable, Dict, Iterable, Tuple, TypeVar, List T = TypeVar('T') def add(x: Any=0, y: Any=0) -> Any: return x + y def to_dict(v: Iterable[Tuple[Any, Any]]=[]) -> Dict[Any, Any]: return dict(v) class TypesPrintTest(TestCase): # These 2 methods are needed to run tests with our custom test-runner def _pre_setup(self) -> None: pass def _post_teardown(self) -> None: pass def check_signature(self, signature: str, retval: T, func: Callable[..., T], *args: Any, **kwargs: Any) -> None: """ Checks if print_types outputs `signature` when func is called with *args and **kwargs. Do not decorate func with print_types before passing into this function. func will be decorated with print_types within this function. """ try: original_stdout = sys.stdout sys.stdout = StringIO() self.assertEqual(retval, print_types(func)(*args, **kwargs)) self.assertEqual(sys.stdout.getvalue().strip(), signature) finally: sys.stdout = original_stdout def test_empty(self) -> None: def empty_func() -> None: pass self.check_signature("empty_func() -> None", None, empty_func) self.check_signature("<lambda>() -> None", None, (lambda: None)) def test_basic(self) -> None: self.check_signature("add(float, int) -> float", 5.0, add, 2.0, 3) self.check_signature("add(float, y=int) -> float", 5.0, add, 2.0, y=3) self.check_signature("add(x=int) -> int", 2, add, x=2) self.check_signature("add() -> int", 0, add) def test_list(self) -> None: self.check_signature("add([], [str]) -> [str]", ['two'], add, [], ['two']) self.check_signature("add([int], [str]) -> [int, ...]", [2, 'two'], add, [2], ['two']) self.check_signature("add([int, ...], y=[]) -> [int, ...]", [2, 'two'], add, [2, 'two'], y=[]) def test_dict(self) -> None: self.check_signature("to_dict() -> {}", {}, to_dict) self.check_signature("to_dict([(int, str)]) -> {int: str}", {2: 'two'}, to_dict, [(2, 'two')]) self.check_signature("to_dict(((int, str),)) -> {int: str}", {2: 'two'}, to_dict, ((2, 'two'),)) self.check_signature("to_dict([(int, str), ...]) -> {int: str, ...}", {1: 'one', 2: 'two'}, to_dict, [(1, 'one'), (2, 'two')]) def test_tuple(self) -> None: self.check_signature("add((), ()) -> ()", (), add, (), ()) self.check_signature("add((int,), (str,)) -> (int, str)", (1, 'one'), add, (1,), ('one',)) self.check_signature("add(((),), ((),)) -> ((), ())", ((), ()), add, ((),), ((),)) def test_class(self) -> None: class A: pass class B(str): pass self.check_signature("<lambda>(A) -> str", 'A', (lambda x: x.__class__.__name__), A()) self.check_signature("<lambda>(B) -> int", 5, (lambda x: len(x)), B("hello")) def test_sequence(self) -> None: class A(List[Any]): pass class B(List[Any]): pass self.check_signature("add(A([]), B([str])) -> [str]", ['two'], add, A([]), B(['two'])) self.check_signature("add(A([int]), B([str])) -> [int, ...]", [2, 'two'], add, A([2]), B(['two'])) self.check_signature("add(A([int, ...]), y=B([])) -> [int, ...]", [2, 'two'], add, A([2, 'two']), y=B([])) def test_mapping(self) -> None: class A(Dict[Any, Any]): pass def to_A(v: Iterable[Tuple[Any, Any]]=[]) -> A: return A(v) self.check_signature("to_A() -> A([])", A(()), to_A) self.check_signature("to_A([(int, str)]) -> A([(int, str)])", {2: 'two'}, to_A, [(2, 'two')]) self.check_signature("to_A([(int, str), ...]) -> A([(int, str), ...])", {1: 'one', 2: 'two'}, to_A, [(1, 'one'), (2, 'two')]) self.check_signature("to_A(((int, str), (int, str))) -> A([(int, str), ...])", {1: 'one', 2: 'two'}, to_A, ((1, 'one'), (2, 'two')))
[ "str", "T", "Callable[..., T]", "Any", "Any" ]
[ 590, 603, 612, 661, 676 ]
[ 593, 604, 628, 664, 679 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_typing.py
# -*- coding: utf-8 -*- import ujson from typing import Any, Mapping, List from zerver.lib.test_helpers import tornado_redirected_to_list, get_display_recipient from zerver.lib.test_classes import ( ZulipTestCase, ) from zerver.models import get_realm, get_user class TypingNotificationOperatorTest(ZulipTestCase): def test_missing_parameter(self) -> None: """ Sending typing notification without op parameter fails """ sender = self.example_email("hamlet") recipient = self.example_email("othello") result = self.api_post(sender, '/api/v1/typing', {'to': recipient}) self.assert_json_error(result, 'Missing \'op\' argument') def test_invalid_parameter(self) -> None: """ Sending typing notification with invalid value for op parameter fails """ sender = self.example_email("hamlet") recipient = self.example_email("othello") result = self.api_post(sender, '/api/v1/typing', {'to': recipient, 'op': 'foo'}) self.assert_json_error(result, 'Invalid \'op\' value (should be start or stop)') class TypingNotificationRecipientsTest(ZulipTestCase): def test_missing_recipient(self) -> None: """ Sending typing notification without recipient fails """ sender = self.example_email("hamlet") result = self.api_post(sender, '/api/v1/typing', {'op': 'start'}) self.assert_json_error(result, 'Missing parameter: \'to\' (recipient)') def test_invalid_recipient(self) -> None: """ Sending typing notification to invalid recipient fails """ sender = self.example_email("hamlet") invalid = 'invalid email' result = self.api_post(sender, '/api/v1/typing', {'op': 'start', 'to': invalid}) self.assert_json_error(result, 'Invalid email \'' + invalid + '\'') def test_single_recipient(self) -> None: """ Sending typing notification to a single recipient is successful """ sender = self.example_user('hamlet') recipient = self.example_user('othello') expected_recipients = set([sender, recipient]) expected_recipient_emails = set([user.email for user in expected_recipients]) expected_recipient_ids = set([user.id for user in expected_recipients]) events = [] # type: List[Mapping[str, Any]] with tornado_redirected_to_list(events): result = self.api_post(sender.email, '/api/v1/typing', {'to': recipient.email, 'op': 'start'}) self.assert_json_success(result) self.assertEqual(len(events), 1) event = events[0]['event'] event_recipient_emails = set(user['email'] for user in event['recipients']) event_user_ids = set(events[0]['users']) event_recipient_user_ids = set(user['user_id'] for user in event['recipients']) self.assertEqual(expected_recipient_ids, event_recipient_user_ids) self.assertEqual(expected_recipient_ids, event_user_ids) self.assertEqual(event['sender']['email'], sender.email) self.assertEqual(event_recipient_emails, expected_recipient_emails) self.assertEqual(event['type'], 'typing') self.assertEqual(event['op'], 'start') def test_multiple_recipients(self) -> None: """ Sending typing notification to a single recipient is successful """ sender = self.example_user('hamlet') recipient = [self.example_user('othello'), self.example_user('cordelia')] expected_recipients = set(recipient) | set([sender]) expected_recipient_emails = set([user.email for user in expected_recipients]) expected_recipient_ids = set([user.id for user in expected_recipients]) events = [] # type: List[Mapping[str, Any]] with tornado_redirected_to_list(events): result = self.api_post(sender.email, '/api/v1/typing', {'to': ujson.dumps([user.email for user in recipient]), 'op': 'start'}) self.assert_json_success(result) self.assertEqual(len(events), 1) event = events[0]['event'] event_recipient_emails = set(user['email'] for user in event['recipients']) event_user_ids = set(events[0]['users']) event_recipient_user_ids = set(user['user_id'] for user in event['recipients']) self.assertEqual(expected_recipient_ids, event_recipient_user_ids) self.assertEqual(expected_recipient_ids, event_user_ids) self.assertEqual(event['sender']['email'], sender.email) self.assertEqual(event_recipient_emails, expected_recipient_emails) self.assertEqual(event['type'], 'typing') self.assertEqual(event['op'], 'start') class TypingStartedNotificationTest(ZulipTestCase): def test_send_notification_to_self_event(self) -> None: """ Sending typing notification to yourself is successful. """ user = self.example_user('hamlet') email = user.email expected_recipient_emails = set([email]) expected_recipient_ids = set([user.id]) events = [] # type: List[Mapping[str, Any]] with tornado_redirected_to_list(events): result = self.api_post(email, '/api/v1/typing', {'to': email, 'op': 'start'}) self.assert_json_success(result) self.assertEqual(len(events), 1) event = events[0]['event'] event_recipient_emails = set(user['email'] for user in event['recipients']) event_user_ids = set(events[0]['users']) event_recipient_user_ids = set(user['user_id'] for user in event['recipients']) self.assertEqual(expected_recipient_ids, event_recipient_user_ids) self.assertEqual(expected_recipient_ids, event_user_ids) self.assertEqual(event_recipient_emails, expected_recipient_emails) self.assertEqual(event['sender']['email'], email) self.assertEqual(event['type'], 'typing') self.assertEqual(event['op'], 'start') def test_send_notification_to_another_user_event(self) -> None: """ Sending typing notification to another user is successful. """ sender = self.example_user('hamlet') recipient = self.example_user('othello') expected_recipients = set([sender, recipient]) expected_recipient_emails = set([user.email for user in expected_recipients]) expected_recipient_ids = set([user.id for user in expected_recipients]) events = [] # type: List[Mapping[str, Any]] with tornado_redirected_to_list(events): result = self.api_post(sender.email, '/api/v1/typing', {'to': recipient.email, 'op': 'start'}) self.assert_json_success(result) self.assertEqual(len(events), 1) event = events[0]['event'] event_recipient_emails = set(user['email'] for user in event['recipients']) event_user_ids = set(events[0]['users']) event_recipient_user_ids = set(user['user_id'] for user in event['recipients']) self.assertEqual(expected_recipient_ids, event_recipient_user_ids) self.assertEqual(expected_recipient_ids, event_user_ids) self.assertEqual(event_recipient_emails, expected_recipient_emails) self.assertEqual(event['sender']['email'], sender.email) self.assertEqual(event['type'], 'typing') self.assertEqual(event['op'], 'start') class StoppedTypingNotificationTest(ZulipTestCase): def test_send_notification_to_self_event(self) -> None: """ Sending stopped typing notification to yourself is successful. """ user = self.example_user('hamlet') email = user.email expected_recipient_emails = set([email]) expected_recipient_ids = set([user.id]) events = [] # type: List[Mapping[str, Any]] with tornado_redirected_to_list(events): result = self.api_post(email, '/api/v1/typing', {'to': email, 'op': 'stop'}) self.assert_json_success(result) self.assertEqual(len(events), 1) event = events[0]['event'] event_recipient_emails = set(user['email'] for user in event['recipients']) event_user_ids = set(events[0]['users']) event_recipient_user_ids = set(user['user_id'] for user in event['recipients']) self.assertEqual(expected_recipient_ids, event_recipient_user_ids) self.assertEqual(expected_recipient_ids, event_user_ids) self.assertEqual(event_recipient_emails, expected_recipient_emails) self.assertEqual(event['sender']['email'], email) self.assertEqual(event['type'], 'typing') self.assertEqual(event['op'], 'stop') def test_send_notification_to_another_user_event(self) -> None: """ Sending stopped typing notification to another user is successful. """ sender = self.example_user('hamlet') recipient = self.example_user('othello') expected_recipients = set([sender, recipient]) expected_recipient_emails = set([user.email for user in expected_recipients]) expected_recipient_ids = set([user.id for user in expected_recipients]) events = [] # type: List[Mapping[str, Any]] with tornado_redirected_to_list(events): result = self.api_post(sender.email, '/api/v1/typing', {'to': recipient.email, 'op': 'stop'}) self.assert_json_success(result) self.assertEqual(len(events), 1) event = events[0]['event'] event_recipient_emails = set(user['email'] for user in event['recipients']) event_user_ids = set(events[0]['users']) event_recipient_user_ids = set(user['user_id'] for user in event['recipients']) self.assertEqual(expected_recipient_ids, event_recipient_user_ids) self.assertEqual(expected_recipient_ids, event_user_ids) self.assertEqual(event_recipient_emails, expected_recipient_emails) self.assertEqual(event['sender']['email'], sender.email) self.assertEqual(event['type'], 'typing') self.assertEqual(event['op'], 'stop')
[]
[]
[]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_unread.py
# -*- coding: utf-8 -*-AA from typing import Any, Dict, List, Mapping from django.db import connection from django.test import override_settings from zerver.models import ( get_realm, get_stream, get_stream_recipient, get_user, Recipient, Stream, Subscription, UserMessage, UserProfile, ) from zerver.lib.fix_unreads import ( fix, fix_pre_pointer, fix_unsubscribed, ) from zerver.lib.test_helpers import ( get_subscription, tornado_redirected_to_list, ) from zerver.lib.test_classes import ( ZulipTestCase, ) from zerver.lib.topic_mutes import add_topic_mute import mock import ujson class PointerTest(ZulipTestCase): def test_update_pointer(self) -> None: """ Posting a pointer to /update (in the form {"pointer": pointer}) changes the pointer we store for your UserProfile. """ self.login(self.example_email("hamlet")) self.assertEqual(self.example_user('hamlet').pointer, -1) msg_id = self.send_stream_message(self.example_email("othello"), "Verona") result = self.client_post("/json/users/me/pointer", {"pointer": msg_id}) self.assert_json_success(result) self.assertEqual(self.example_user('hamlet').pointer, msg_id) def test_api_update_pointer(self) -> None: """ Same as above, but for the API view """ user = self.example_user('hamlet') email = user.email self.assertEqual(user.pointer, -1) msg_id = self.send_stream_message(self.example_email("othello"), "Verona") result = self.api_post(email, "/api/v1/users/me/pointer", {"pointer": msg_id}) self.assert_json_success(result) self.assertEqual(get_user(email, user.realm).pointer, msg_id) def test_missing_pointer(self) -> None: """ Posting json to /json/users/me/pointer which does not contain a pointer key/value pair returns a 400 and error message. """ self.login(self.example_email("hamlet")) self.assertEqual(self.example_user('hamlet').pointer, -1) result = self.client_post("/json/users/me/pointer", {"foo": 1}) self.assert_json_error(result, "Missing 'pointer' argument") self.assertEqual(self.example_user('hamlet').pointer, -1) def test_invalid_pointer(self) -> None: """ Posting json to /json/users/me/pointer with an invalid pointer returns a 400 and error message. """ self.login(self.example_email("hamlet")) self.assertEqual(self.example_user('hamlet').pointer, -1) result = self.client_post("/json/users/me/pointer", {"pointer": "foo"}) self.assert_json_error(result, "Bad value for 'pointer': foo") self.assertEqual(self.example_user('hamlet').pointer, -1) def test_pointer_out_of_range(self) -> None: """ Posting json to /json/users/me/pointer with an out of range (< 0) pointer returns a 400 and error message. """ self.login(self.example_email("hamlet")) self.assertEqual(self.example_user('hamlet').pointer, -1) result = self.client_post("/json/users/me/pointer", {"pointer": -2}) self.assert_json_error(result, "Bad value for 'pointer': -2") self.assertEqual(self.example_user('hamlet').pointer, -1) def test_use_first_unread_anchor_interaction_with_pointer(self) -> None: """ Getting old messages (a get request to /json/messages) should never return an unread message older than the current pointer, when there's no narrow set. """ self.login(self.example_email("hamlet")) # Ensure the pointer is not set (-1) self.assertEqual(self.example_user('hamlet').pointer, -1) # Mark all existing messages as read result = self.client_post("/json/mark_all_as_read") self.assert_json_success(result) # Send a new message (this will be unread) new_message_id = self.send_stream_message(self.example_email("othello"), "Verona", "test") # If we call get_messages with use_first_unread_anchor=True, we # should get the message we just sent messages_response = self.get_messages_response( anchor=0, num_before=0, num_after=1, use_first_unread_anchor=True) self.assertEqual(messages_response['messages'][0]['id'], new_message_id) self.assertEqual(messages_response['anchor'], new_message_id) # We want to get the message_id of an arbitrar old message. We can # call get_messages with use_first_unread_anchor=False and simply # save the first message we're returned. messages = self.get_messages( anchor=0, num_before=0, num_after=2, use_first_unread_anchor=False) old_message_id = messages[0]['id'] next_old_message_id = messages[1]['id'] # Verify the message is marked as read user_message = UserMessage.objects.get( message_id=old_message_id, user_profile=self.example_user('hamlet')) self.assertTrue(user_message.flags.read) # Let's set this old message to be unread result = self.client_post("/json/messages/flags", {"messages": ujson.dumps([old_message_id]), "op": "remove", "flag": "read"}) # Verify it's now marked as unread user_message = UserMessage.objects.get( message_id=old_message_id, user_profile=self.example_user('hamlet')) self.assert_json_success(result) self.assertFalse(user_message.flags.read) # Now if we call get_messages with use_first_unread_anchor=True, # we should get the old message we just set to unread messages_response = self.get_messages_response( anchor=0, num_before=0, num_after=1, use_first_unread_anchor=True) self.assertEqual(messages_response['messages'][0]['id'], old_message_id) self.assertEqual(messages_response['anchor'], old_message_id) # Let's update the pointer to be *after* this old unread message (but # still on or before the new unread message we just sent) result = self.client_post("/json/users/me/pointer", {"pointer": next_old_message_id}) self.assert_json_success(result) self.assertEqual(self.example_user('hamlet').pointer, next_old_message_id) # Verify that moving the pointer didn't mark our message as read. user_message = UserMessage.objects.get( message_id=old_message_id, user_profile=self.example_user('hamlet')) self.assertFalse(user_message.flags.read) # Now if we call get_messages with use_first_unread_anchor=True, # we should not get the old unread message (because it's before the # pointer), and instead should get the newly sent unread message messages_response = self.get_messages_response( anchor=0, num_before=0, num_after=1, use_first_unread_anchor=True) self.assertEqual(messages_response['messages'][0]['id'], new_message_id) self.assertEqual(messages_response['anchor'], new_message_id) def test_visible_messages_use_first_unread_anchor(self) -> None: self.login(self.example_email("hamlet")) self.assertEqual(self.example_user('hamlet').pointer, -1) result = self.client_post("/json/mark_all_as_read") self.assert_json_success(result) new_message_id = self.send_stream_message(self.example_email("othello"), "Verona", "test") messages_response = self.get_messages_response( anchor=0, num_before=0, num_after=1, use_first_unread_anchor=True) self.assertEqual(messages_response['messages'][0]['id'], new_message_id) self.assertEqual(messages_response['anchor'], new_message_id) with mock.patch('zerver.views.messages.get_first_visible_message_id', return_value=new_message_id): messages_response = self.get_messages_response( anchor=0, num_before=0, num_after=1, use_first_unread_anchor=True) self.assertEqual(messages_response['messages'][0]['id'], new_message_id) self.assertEqual(messages_response['anchor'], new_message_id) with mock.patch('zerver.views.messages.get_first_visible_message_id', return_value=new_message_id + 1): messages_reponse = self.get_messages_response( anchor=0, num_before=0, num_after=1, use_first_unread_anchor=True) self.assert_length(messages_reponse['messages'], 0) self.assertIn('anchor', messages_reponse) with mock.patch('zerver.views.messages.get_first_visible_message_id', return_value=new_message_id - 1): messages = self.get_messages( anchor=0, num_before=0, num_after=1, use_first_unread_anchor=True) self.assert_length(messages, 1) class UnreadCountTests(ZulipTestCase): def setUp(self) -> None: self.unread_msg_ids = [ self.send_personal_message( self.example_email("iago"), self.example_email("hamlet"), "hello"), self.send_personal_message( self.example_email("iago"), self.example_email("hamlet"), "hello2")] # Sending a new message results in unread UserMessages being created def test_new_message(self) -> None: self.login(self.example_email("hamlet")) content = "Test message for unset read bit" last_msg = self.send_stream_message(self.example_email("hamlet"), "Verona", content) user_messages = list(UserMessage.objects.filter(message=last_msg)) self.assertEqual(len(user_messages) > 0, True) for um in user_messages: self.assertEqual(um.message.content, content) if um.user_profile.email != self.example_email("hamlet"): self.assertFalse(um.flags.read) def test_update_flags(self) -> None: self.login(self.example_email("hamlet")) result = self.client_post("/json/messages/flags", {"messages": ujson.dumps(self.unread_msg_ids), "op": "add", "flag": "read"}) self.assert_json_success(result) # Ensure we properly set the flags found = 0 for msg in self.get_messages(): if msg['id'] in self.unread_msg_ids: self.assertEqual(msg['flags'], ['read']) found += 1 self.assertEqual(found, 2) result = self.client_post("/json/messages/flags", {"messages": ujson.dumps([self.unread_msg_ids[1]]), "op": "remove", "flag": "read"}) self.assert_json_success(result) # Ensure we properly remove just one flag for msg in self.get_messages(): if msg['id'] == self.unread_msg_ids[0]: self.assertEqual(msg['flags'], ['read']) elif msg['id'] == self.unread_msg_ids[1]: self.assertEqual(msg['flags'], []) def test_mark_all_in_stream_read(self) -> None: self.login(self.example_email("hamlet")) user_profile = self.example_user('hamlet') stream = self.subscribe(user_profile, "test_stream") self.subscribe(self.example_user("cordelia"), "test_stream") message_id = self.send_stream_message(self.example_email("hamlet"), "test_stream", "hello") unrelated_message_id = self.send_stream_message(self.example_email("hamlet"), "Denmark", "hello") events = [] # type: List[Mapping[str, Any]] with tornado_redirected_to_list(events): result = self.client_post("/json/mark_stream_as_read", { "stream_id": stream.id }) self.assert_json_success(result) self.assertTrue(len(events) == 1) event = events[0]['event'] expected = dict(operation='add', messages=[message_id], flag='read', type='update_message_flags', all=False) differences = [key for key in expected if expected[key] != event[key]] self.assertTrue(len(differences) == 0) um = list(UserMessage.objects.filter(message=message_id)) for msg in um: if msg.user_profile.email == self.example_email("hamlet"): self.assertTrue(msg.flags.read) else: self.assertFalse(msg.flags.read) unrelated_messages = list(UserMessage.objects.filter(message=unrelated_message_id)) for msg in unrelated_messages: if msg.user_profile.email == self.example_email("hamlet"): self.assertFalse(msg.flags.read) def test_mark_all_in_invalid_stream_read(self) -> None: self.login(self.example_email("hamlet")) invalid_stream_id = "12345678" result = self.client_post("/json/mark_stream_as_read", { "stream_id": invalid_stream_id }) self.assert_json_error(result, 'Invalid stream id') def test_mark_all_topics_unread_with_invalid_stream_name(self) -> None: self.login(self.example_email("hamlet")) invalid_stream_id = "12345678" result = self.client_post("/json/mark_topic_as_read", { "stream_id": invalid_stream_id, 'topic_name': 'whatever', }) self.assert_json_error(result, "Invalid stream id") def test_mark_all_in_stream_topic_read(self) -> None: self.login(self.example_email("hamlet")) user_profile = self.example_user('hamlet') self.subscribe(user_profile, "test_stream") message_id = self.send_stream_message(self.example_email("hamlet"), "test_stream", "hello", "test_topic") unrelated_message_id = self.send_stream_message(self.example_email("hamlet"), "Denmark", "hello", "Denmark2") events = [] # type: List[Mapping[str, Any]] with tornado_redirected_to_list(events): result = self.client_post("/json/mark_topic_as_read", { "stream_id": get_stream("test_stream", user_profile.realm).id, "topic_name": "test_topic", }) self.assert_json_success(result) self.assertTrue(len(events) == 1) event = events[0]['event'] expected = dict(operation='add', messages=[message_id], flag='read', type='update_message_flags', all=False) differences = [key for key in expected if expected[key] != event[key]] self.assertTrue(len(differences) == 0) um = list(UserMessage.objects.filter(message=message_id)) for msg in um: if msg.user_profile.email == self.example_email("hamlet"): self.assertTrue(msg.flags.read) unrelated_messages = list(UserMessage.objects.filter(message=unrelated_message_id)) for msg in unrelated_messages: if msg.user_profile.email == self.example_email("hamlet"): self.assertFalse(msg.flags.read) def test_mark_all_in_invalid_topic_read(self) -> None: self.login(self.example_email("hamlet")) invalid_topic_name = "abc" result = self.client_post("/json/mark_topic_as_read", { "stream_id": get_stream("Denmark", get_realm("zulip")).id, "topic_name": invalid_topic_name, }) self.assert_json_error(result, 'No such topic \'abc\'') class FixUnreadTests(ZulipTestCase): def test_fix_unreads(self) -> None: user = self.example_user('hamlet') realm = get_realm('zulip') def send_message(stream_name: str, topic_name: str) -> int: msg_id = self.send_stream_message( self.example_email("othello"), stream_name, topic_name=topic_name) um = UserMessage.objects.get( user_profile=user, message_id=msg_id) return um.id def assert_read(user_message_id: int) -> None: um = UserMessage.objects.get(id=user_message_id) self.assertTrue(um.flags.read) def assert_unread(user_message_id: int) -> None: um = UserMessage.objects.get(id=user_message_id) self.assertFalse(um.flags.read) def mute_stream(stream_name: str) -> None: stream = get_stream(stream_name, realm) recipient = get_stream_recipient(stream.id) subscription = Subscription.objects.get( user_profile=user, recipient=recipient ) subscription.in_home_view = False subscription.save() def mute_topic(stream_name: str, topic_name: str) -> None: stream = get_stream(stream_name, realm) recipient = get_stream_recipient(stream.id) add_topic_mute( user_profile=user, stream_id=stream.id, recipient_id=recipient.id, topic_name=topic_name, ) def force_unsubscribe(stream_name: str) -> None: ''' We don't want side effects here, since the eventual unsubscribe path may mark messages as read, defeating the test setup here. ''' sub = get_subscription(stream_name, user) sub.active = False sub.save() # The data setup here is kind of funny, because some of these # conditions should not actually happen in practice going forward, # but we may have had bad data from the past. mute_stream('Denmark') mute_topic('Verona', 'muted_topic') um_normal_id = send_message('Verona', 'normal') um_muted_topic_id = send_message('Verona', 'muted_topic') um_muted_stream_id = send_message('Denmark', 'whatever') user.pointer = self.get_last_message().id user.save() um_post_pointer_id = send_message('Verona', 'muted_topic') self.subscribe(user, 'temporary') um_unsubscribed_id = send_message('temporary', 'whatever') force_unsubscribe('temporary') # verify data setup assert_unread(um_normal_id) assert_unread(um_muted_topic_id) assert_unread(um_muted_stream_id) assert_unread(um_post_pointer_id) assert_unread(um_unsubscribed_id) with connection.cursor() as cursor: fix_pre_pointer(cursor, user) # The only message that should have been fixed is the "normal" # unumuted message before the pointer. assert_read(um_normal_id) # We don't "fix" any messages that are either muted or after the # pointer, because they can be legitimately unread. assert_unread(um_muted_topic_id) assert_unread(um_muted_stream_id) assert_unread(um_post_pointer_id) assert_unread(um_unsubscribed_id) # fix unsubscribed with connection.cursor() as cursor: fix_unsubscribed(cursor, user) # Most messages don't change. assert_unread(um_muted_topic_id) assert_unread(um_muted_stream_id) assert_unread(um_post_pointer_id) # The unsubscribed entry should change. assert_read(um_unsubscribed_id) # test idempotency fix(user) assert_read(um_normal_id) assert_unread(um_muted_topic_id) assert_unread(um_muted_stream_id) assert_unread(um_post_pointer_id) assert_read(um_unsubscribed_id) class PushNotificationMarkReadFlowsTest(ZulipTestCase): def get_mobile_push_notification_ids(self, user_profile: UserProfile) -> List[int]: return list(UserMessage.objects.filter( user_profile=user_profile, flags=UserMessage.flags.active_mobile_push_notification).order_by( "message_id").values_list("message_id", flat=True)) @override_settings(SEND_REMOVE_PUSH_NOTIFICATIONS=True) def test_track_active_mobile_push_notifications(self) -> None: self.login(self.example_email("hamlet")) user_profile = self.example_user('hamlet') stream = self.subscribe(user_profile, "test_stream") second_stream = self.subscribe(user_profile, "second_stream") property_name = "push_notifications" result = self.api_post(user_profile.email, "/api/v1/users/me/subscriptions/properties", {"subscription_data": ujson.dumps([{"property": property_name, "value": True, "stream_id": stream.id}])}) result = self.api_post(user_profile.email, "/api/v1/users/me/subscriptions/properties", {"subscription_data": ujson.dumps([{"property": property_name, "value": True, "stream_id": second_stream.id}])}) self.assert_json_success(result) self.assertEqual(self.get_mobile_push_notification_ids(user_profile), []) message_id = self.send_stream_message(self.example_email("cordelia"), "test_stream", "hello", "test_topic") second_message_id = self.send_stream_message(self.example_email("cordelia"), "test_stream", "hello", "other_topic") third_message_id = self.send_stream_message(self.example_email("cordelia"), "second_stream", "hello", "test_topic") self.assertEqual(self.get_mobile_push_notification_ids(user_profile), [message_id, second_message_id, third_message_id]) result = self.client_post("/json/mark_topic_as_read", { "stream_id": str(stream.id), "topic_name": "test_topic", }) self.assert_json_success(result) self.assertEqual(self.get_mobile_push_notification_ids(user_profile), [second_message_id, third_message_id]) result = self.client_post("/json/mark_stream_as_read", { "stream_id": str(stream.id), "topic_name": "test_topic", }) self.assertEqual(self.get_mobile_push_notification_ids(user_profile), [third_message_id]) fourth_message_id = self.send_stream_message(self.example_email("cordelia"), "test_stream", "hello", "test_topic") self.assertEqual(self.get_mobile_push_notification_ids(user_profile), [third_message_id, fourth_message_id]) result = self.client_post("/json/mark_all_as_read", {}) self.assertEqual(self.get_mobile_push_notification_ids(user_profile), [])
[ "str", "str", "int", "int", "str", "str", "str", "str", "UserProfile" ]
[ 16021, 16038, 16392, 16554, 16711, 17086, 17103, 17466, 20040 ]
[ 16024, 16041, 16395, 16557, 16714, 17089, 17106, 17469, 20051 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_upload.py
# -*- coding: utf-8 -*- from django.conf import settings from django.test import TestCase from unittest import skip from zerver.lib.avatar import ( avatar_url, get_avatar_field, ) from zerver.lib.avatar_hash import user_avatar_path from zerver.lib.bugdown import url_filename from zerver.lib.realm_icon import realm_icon_url from zerver.lib.test_classes import ZulipTestCase, UploadSerializeMixin from zerver.lib.test_helpers import ( avatar_disk_path, get_test_image_file, POSTRequestMock, use_s3_backend, queries_captured, ) from zerver.lib.test_runner import slow from zerver.lib.upload import sanitize_name, S3UploadBackend, \ upload_message_file, upload_emoji_image, delete_message_image, LocalUploadBackend, \ ZulipUploadBackend, MEDIUM_AVATAR_SIZE, resize_avatar, \ resize_emoji, BadImageError, get_realm_for_filename, \ currently_used_upload_space, DEFAULT_AVATAR_SIZE, DEFAULT_EMOJI_SIZE, \ exif_rotate import zerver.lib.upload from zerver.models import Attachment, get_user, \ get_old_unclaimed_attachments, Message, UserProfile, Stream, Realm, \ RealmDomain, RealmEmoji, get_realm, get_system_bot, \ validate_attachment_request from zerver.lib.actions import ( do_delete_old_unclaimed_attachments, internal_send_private_message, ) from zerver.lib.create_user import copy_user_settings from zerver.lib.request import JsonableError from zerver.lib.users import get_api_key from zerver.views.upload import upload_file_backend, serve_local import urllib from PIL import Image from boto.s3.connection import S3Connection from boto.s3.key import Key from io import StringIO import mock import os import io import shutil import re import datetime import requests import base64 from datetime import timedelta from django.http import HttpRequest from django.utils.timezone import now as timezone_now from sendfile import _get_sendfile from typing import Any, Callable def destroy_uploads() -> None: if os.path.exists(settings.LOCAL_UPLOADS_DIR): shutil.rmtree(settings.LOCAL_UPLOADS_DIR) class FileUploadTest(UploadSerializeMixin, ZulipTestCase): def test_rest_endpoint(self) -> None: """ Tests the /api/v1/user_uploads api endpoint. Here a single file is uploaded and downloaded using a username and api_key """ fp = StringIO("zulip!") fp.name = "zulip.txt" # Upload file via API result = self.api_post(self.example_email("hamlet"), '/api/v1/user_uploads', {'file': fp}) self.assertIn("uri", result.json()) uri = result.json()['uri'] base = '/user_uploads/' self.assertEqual(base, uri[:len(base)]) # Download file via API self.logout() response = self.api_get(self.example_email("hamlet"), uri) self.assertEqual(response.status_code, 200) data = b"".join(response.streaming_content) self.assertEqual(b"zulip!", data) # Files uploaded through the API should be accesible via the web client self.login(self.example_email("hamlet")) self.assert_url_serves_contents_of_file(uri, b"zulip!") def test_mobile_api_endpoint(self) -> None: """ Tests the /api/v1/user_uploads api endpoint with ?api_key auth. Here a single file is uploaded and downloaded using a username and api_key """ fp = StringIO("zulip!") fp.name = "zulip.txt" # Upload file via API result = self.api_post(self.example_email("hamlet"), '/api/v1/user_uploads', {'file': fp}) self.assertIn("uri", result.json()) uri = result.json()['uri'] base = '/user_uploads/' self.assertEqual(base, uri[:len(base)]) self.logout() # Try to download file via API, passing URL and invalid API key user_profile = self.example_user("hamlet") response = self.client_get(uri + "?api_key=" + "invalid") self.assertEqual(response.status_code, 400) response = self.client_get(uri + "?api_key=" + get_api_key(user_profile)) self.assertEqual(response.status_code, 200) data = b"".join(response.streaming_content) self.assertEqual(b"zulip!", data) def test_upload_file_with_supplied_mimetype(self) -> None: """ When files are copied into the system clipboard and pasted for upload the filename may not be supplied so the extension is determined from a query string parameter. """ fp = StringIO("zulip!") fp.name = "pasted_file" result = self.api_post(self.example_email("hamlet"), "/api/v1/user_uploads?mimetype=image/png", {"file": fp}) self.assertEqual(result.status_code, 200) uri = result.json()["uri"] self.assertTrue(uri.endswith("pasted_file.png")) def test_filename_encoding(self) -> None: """ In Python 2, we need to encode unicode filenames (which converts them to str) before they can be rendered correctly. However, in Python 3, the separate unicode type does not exist, and we don't need to perform this encoding. This test ensures that we handle filename encodings properly, and does so in a way that preserves 100% test coverage for Python 3. """ user_profile = self.example_user('hamlet') mock_file = mock.Mock() mock_file._get_size = mock.Mock(return_value=1024) mock_files = mock.Mock() mock_files.__len__ = mock.Mock(return_value=1) mock_files.values = mock.Mock(return_value=[mock_file]) mock_request = mock.Mock() mock_request.FILES = mock_files # str filenames should not be encoded. mock_filename = mock.Mock(spec=str) mock_file.name = mock_filename with mock.patch('zerver.views.upload.upload_message_image_from_request'): result = upload_file_backend(mock_request, user_profile) self.assert_json_success(result) mock_filename.encode.assert_not_called() # Non-str filenames should be encoded. mock_filename = mock.Mock(spec=None) # None is not str mock_file.name = mock_filename with mock.patch('zerver.views.upload.upload_message_image_from_request'): result = upload_file_backend(mock_request, user_profile) self.assert_json_success(result) mock_filename.encode.assert_called_once_with('ascii') def test_file_too_big_failure(self) -> None: """ Attempting to upload big files should fail. """ self.login(self.example_email("hamlet")) fp = StringIO("bah!") fp.name = "a.txt" # Use MAX_FILE_UPLOAD_SIZE of 0, because the next increment # would be 1MB. with self.settings(MAX_FILE_UPLOAD_SIZE=0): result = self.client_post("/json/user_uploads", {'f1': fp}) self.assert_json_error(result, 'Uploaded file is larger than the allowed limit of 0 MB') def test_multiple_upload_failure(self) -> None: """ Attempting to upload two files should fail. """ self.login(self.example_email("hamlet")) fp = StringIO("bah!") fp.name = "a.txt" fp2 = StringIO("pshaw!") fp2.name = "b.txt" result = self.client_post("/json/user_uploads", {'f1': fp, 'f2': fp2}) self.assert_json_error(result, "You may only upload one file at a time") def test_no_file_upload_failure(self) -> None: """ Calling this endpoint with no files should fail. """ self.login(self.example_email("hamlet")) result = self.client_post("/json/user_uploads") self.assert_json_error(result, "You must specify a file to upload") # This test will go through the code path for uploading files onto LOCAL storage # when zulip is in DEVELOPMENT mode. def test_file_upload_authed(self) -> None: """ A call to /json/user_uploads should return a uri and actually create an entry in the database. This entry will be marked unclaimed till a message refers it. """ self.login(self.example_email("hamlet")) fp = StringIO("zulip!") fp.name = "zulip.txt" result = self.client_post("/json/user_uploads", {'file': fp}) self.assert_json_success(result) self.assertIn("uri", result.json()) uri = result.json()["uri"] base = '/user_uploads/' self.assertEqual(base, uri[:len(base)]) # In the future, local file requests will follow the same style as S3 # requests; they will be first authenthicated and redirected self.assert_url_serves_contents_of_file(uri, b"zulip!") # check if DB has attachment marked as unclaimed entry = Attachment.objects.get(file_name='zulip.txt') self.assertEqual(entry.is_claimed(), False) self.subscribe(self.example_user("hamlet"), "Denmark") body = "First message ...[zulip.txt](http://localhost:9991" + uri + ")" self.send_stream_message(self.example_email("hamlet"), "Denmark", body, "test") self.assertIn('title="zulip.txt"', self.get_last_message().rendered_content) def test_file_download_unauthed(self) -> None: self.login(self.example_email("hamlet")) fp = StringIO("zulip!") fp.name = "zulip.txt" result = self.client_post("/json/user_uploads", {'file': fp}) uri = result.json()["uri"] self.logout() response = self.client_get(uri) self.assert_json_error(response, "Not logged in: API authentication or user session required", status_code=401) def test_removed_file_download(self) -> None: ''' Trying to download deleted files should return 404 error ''' self.login(self.example_email("hamlet")) fp = StringIO("zulip!") fp.name = "zulip.txt" result = self.client_post("/json/user_uploads", {'file': fp}) destroy_uploads() response = self.client_get(result.json()["uri"]) self.assertEqual(response.status_code, 404) def test_non_existing_file_download(self) -> None: ''' Trying to download a file that was never uploaded will return a json_error ''' self.login(self.example_email("hamlet")) response = self.client_get("http://localhost:9991/user_uploads/1/ff/gg/abc.py") self.assertEqual(response.status_code, 404) self.assert_in_response('File not found.', response) def test_delete_old_unclaimed_attachments(self) -> None: # Upload some files and make them older than a weeek self.login(self.example_email("hamlet")) d1 = StringIO("zulip!") d1.name = "dummy_1.txt" result = self.client_post("/json/user_uploads", {'file': d1}) d1_path_id = re.sub('/user_uploads/', '', result.json()['uri']) d2 = StringIO("zulip!") d2.name = "dummy_2.txt" result = self.client_post("/json/user_uploads", {'file': d2}) d2_path_id = re.sub('/user_uploads/', '', result.json()['uri']) two_week_ago = timezone_now() - datetime.timedelta(weeks=2) d1_attachment = Attachment.objects.get(path_id = d1_path_id) d1_attachment.create_time = two_week_ago d1_attachment.save() self.assertEqual(str(d1_attachment), u'<Attachment: dummy_1.txt>') d2_attachment = Attachment.objects.get(path_id = d2_path_id) d2_attachment.create_time = two_week_ago d2_attachment.save() # Send message referring only dummy_1 self.subscribe(self.example_user("hamlet"), "Denmark") body = "Some files here ...[zulip.txt](http://localhost:9991/user_uploads/" + d1_path_id + ")" self.send_stream_message(self.example_email("hamlet"), "Denmark", body, "test") # dummy_2 should not exist in database or the uploads folder do_delete_old_unclaimed_attachments(2) self.assertTrue(not Attachment.objects.filter(path_id = d2_path_id).exists()) self.assertTrue(not delete_message_image(d2_path_id)) def test_attachment_url_without_upload(self) -> None: self.login(self.example_email("hamlet")) body = "Test message ...[zulip.txt](http://localhost:9991/user_uploads/1/64/fake_path_id.txt)" self.send_stream_message(self.example_email("hamlet"), "Denmark", body, "test") self.assertFalse(Attachment.objects.filter(path_id = "1/64/fake_path_id.txt").exists()) def test_multiple_claim_attachments(self) -> None: """ This test tries to claim the same attachment twice. The messages field in the Attachment model should have both the messages in its entry. """ self.login(self.example_email("hamlet")) d1 = StringIO("zulip!") d1.name = "dummy_1.txt" result = self.client_post("/json/user_uploads", {'file': d1}) d1_path_id = re.sub('/user_uploads/', '', result.json()['uri']) self.subscribe(self.example_user("hamlet"), "Denmark") body = "First message ...[zulip.txt](http://localhost:9991/user_uploads/" + d1_path_id + ")" self.send_stream_message(self.example_email("hamlet"), "Denmark", body, "test") body = "Second message ...[zulip.txt](http://localhost:9991/user_uploads/" + d1_path_id + ")" self.send_stream_message(self.example_email("hamlet"), "Denmark", body, "test") self.assertEqual(Attachment.objects.get(path_id=d1_path_id).messages.count(), 2) def test_multiple_claim_attachments_different_owners(self) -> None: """This test tries to claim the same attachment more than once, first with a private stream and then with different recipients.""" self.login(self.example_email("hamlet")) d1 = StringIO("zulip!") d1.name = "dummy_1.txt" result = self.client_post("/json/user_uploads", {'file': d1}) d1_path_id = re.sub('/user_uploads/', '', result.json()['uri']) self.make_stream("private_stream", invite_only=True) self.subscribe(self.example_user("hamlet"), "private_stream") # First, send the mesasge to the new private stream. body = "First message ...[zulip.txt](http://localhost:9991/user_uploads/" + d1_path_id + ")" self.send_stream_message(self.example_email("hamlet"), "private_stream", body, "test") self.assertFalse(Attachment.objects.get(path_id=d1_path_id).is_realm_public) self.assertEqual(Attachment.objects.get(path_id=d1_path_id).messages.count(), 1) # Then, try having a user who didn't receive the message try to publish it, and fail body = "Illegal message ...[zulip.txt](http://localhost:9991/user_uploads/" + d1_path_id + ")" self.send_stream_message(self.example_email("cordelia"), "Denmark", body, "test") self.assertEqual(Attachment.objects.get(path_id=d1_path_id).messages.count(), 1) self.assertFalse(Attachment.objects.get(path_id=d1_path_id).is_realm_public) # Then, have the owner PM it to another user, giving that other user access. body = "Second message ...[zulip.txt](http://localhost:9991/user_uploads/" + d1_path_id + ")" self.send_personal_message(self.example_email("hamlet"), self.example_email("othello"), body) self.assertEqual(Attachment.objects.get(path_id=d1_path_id).messages.count(), 2) self.assertFalse(Attachment.objects.get(path_id=d1_path_id).is_realm_public) # Then, have that new recipient user publish it. body = "Third message ...[zulip.txt](http://localhost:9991/user_uploads/" + d1_path_id + ")" self.send_stream_message(self.example_email("othello"), "Denmark", body, "test") self.assertEqual(Attachment.objects.get(path_id=d1_path_id).messages.count(), 3) self.assertTrue(Attachment.objects.get(path_id=d1_path_id).is_realm_public) def test_check_attachment_reference_update(self) -> None: f1 = StringIO("file1") f1.name = "file1.txt" f2 = StringIO("file2") f2.name = "file2.txt" f3 = StringIO("file3") f3.name = "file3.txt" self.login(self.example_email("hamlet")) result = self.client_post("/json/user_uploads", {'file': f1}) f1_path_id = re.sub('/user_uploads/', '', result.json()['uri']) result = self.client_post("/json/user_uploads", {'file': f2}) f2_path_id = re.sub('/user_uploads/', '', result.json()['uri']) self.subscribe(self.example_user("hamlet"), "test") body = ("[f1.txt](http://localhost:9991/user_uploads/" + f1_path_id + ")" "[f2.txt](http://localhost:9991/user_uploads/" + f2_path_id + ")") msg_id = self.send_stream_message(self.example_email("hamlet"), "test", body, "test") result = self.client_post("/json/user_uploads", {'file': f3}) f3_path_id = re.sub('/user_uploads/', '', result.json()['uri']) new_body = ("[f3.txt](http://localhost:9991/user_uploads/" + f3_path_id + ")" "[f2.txt](http://localhost:9991/user_uploads/" + f2_path_id + ")") result = self.client_patch("/json/messages/" + str(msg_id), { 'message_id': msg_id, 'content': new_body }) self.assert_json_success(result) message = Message.objects.get(id=msg_id) f1_attachment = Attachment.objects.get(path_id=f1_path_id) f2_attachment = Attachment.objects.get(path_id=f2_path_id) f3_attachment = Attachment.objects.get(path_id=f3_path_id) self.assertTrue(message not in f1_attachment.messages.all()) self.assertTrue(message in f2_attachment.messages.all()) self.assertTrue(message in f3_attachment.messages.all()) # Delete all the attachments from the message new_body = "(deleted)" result = self.client_patch("/json/messages/" + str(msg_id), { 'message_id': msg_id, 'content': new_body }) self.assert_json_success(result) message = Message.objects.get(id=msg_id) f1_attachment = Attachment.objects.get(path_id=f1_path_id) f2_attachment = Attachment.objects.get(path_id=f2_path_id) f3_attachment = Attachment.objects.get(path_id=f3_path_id) self.assertTrue(message not in f1_attachment.messages.all()) self.assertTrue(message not in f2_attachment.messages.all()) self.assertTrue(message not in f3_attachment.messages.all()) def test_file_name(self) -> None: """ Unicode filenames should be processed correctly. """ self.login(self.example_email("hamlet")) for expected in ["Здравейте.txt", "test"]: fp = StringIO("bah!") fp.name = urllib.parse.quote(expected) result = self.client_post("/json/user_uploads", {'f1': fp}) assert sanitize_name(expected) in result.json()['uri'] def test_realm_quota(self) -> None: """ Realm quota for uploading should not be exceeded. """ self.login(self.example_email("hamlet")) d1 = StringIO("zulip!") d1.name = "dummy_1.txt" result = self.client_post("/json/user_uploads", {'file': d1}) d1_path_id = re.sub('/user_uploads/', '', result.json()['uri']) d1_attachment = Attachment.objects.get(path_id = d1_path_id) self.assert_json_success(result) realm = get_realm("zulip") realm.upload_quota_gb = 1 realm.save(update_fields=['upload_quota_gb']) # The size of StringIO("zulip!") is 6 bytes. Setting the size of # d1_attachment to realm.upload_quota_bytes() - 11 should allow # us to upload only one more attachment. quota = realm.upload_quota_bytes() assert(quota is not None) d1_attachment.size = quota - 11 d1_attachment.save(update_fields=['size']) d2 = StringIO("zulip!") d2.name = "dummy_2.txt" result = self.client_post("/json/user_uploads", {'file': d2}) self.assert_json_success(result) d3 = StringIO("zulip!") d3.name = "dummy_3.txt" result = self.client_post("/json/user_uploads", {'file': d3}) self.assert_json_error(result, "Upload would exceed your organization's upload quota.") realm.upload_quota_gb = None realm.save(update_fields=['upload_quota_gb']) result = self.client_post("/json/user_uploads", {'file': d3}) self.assert_json_success(result) def test_cross_realm_file_access(self) -> None: def create_user(email: str, realm_id: str) -> UserProfile: self.register(email, 'test', subdomain=realm_id) return get_user(email, get_realm(realm_id)) test_subdomain = "uploadtest.example.com" user1_email = 'user1@uploadtest.example.com' user2_email = 'test-og-bot@zulip.com' user3_email = 'other-user@uploadtest.example.com' r1 = Realm.objects.create(string_id=test_subdomain, invite_required=False) RealmDomain.objects.create(realm=r1, domain=test_subdomain) create_user(user1_email, test_subdomain) create_user(user2_email, 'zulip') create_user(user3_email, test_subdomain) # Send a message from @zulip.com -> @uploadtest.example.com self.login(user2_email, 'test') fp = StringIO("zulip!") fp.name = "zulip.txt" result = self.client_post("/json/user_uploads", {'file': fp}) uri = result.json()['uri'] fp_path_id = re.sub('/user_uploads/', '', uri) body = "First message ...[zulip.txt](http://localhost:9991/user_uploads/" + fp_path_id + ")" with self.settings(CROSS_REALM_BOT_EMAILS = set((user2_email, user3_email))): internal_send_private_message( realm=r1, sender=get_system_bot(user2_email), recipient_user=get_user(user1_email, r1), content=body, ) self.login(user1_email, 'test', realm=r1) response = self.client_get(uri, subdomain=test_subdomain) self.assertEqual(response.status_code, 200) data = b"".join(response.streaming_content) self.assertEqual(b"zulip!", data) self.logout() # Confirm other cross-realm users can't read it. self.login(user3_email, 'test', realm=r1) response = self.client_get(uri, subdomain=test_subdomain) self.assertEqual(response.status_code, 403) self.assert_in_response("You are not authorized to view this file.", response) def test_file_download_authorization_invite_only(self) -> None: user = self.example_user("hamlet") subscribed_emails = [user.email, self.example_email("cordelia")] unsubscribed_emails = [self.example_email("othello"), self.example_email("prospero")] stream_name = "test-subscribe" self.make_stream(stream_name, realm=user.realm, invite_only=True, history_public_to_subscribers=False) for email in subscribed_emails: self.subscribe(get_user(email, user.realm), stream_name) self.login(user.email) fp = StringIO("zulip!") fp.name = "zulip.txt" result = self.client_post("/json/user_uploads", {'file': fp}) uri = result.json()['uri'] fp_path_id = re.sub('/user_uploads/', '', uri) body = "First message ...[zulip.txt](http://localhost:9991/user_uploads/" + fp_path_id + ")" self.send_stream_message(user.email, stream_name, body, "test") self.logout() # Owner user should be able to view file self.login(user.email) with queries_captured() as queries: response = self.client_get(uri) self.assertEqual(response.status_code, 200) data = b"".join(response.streaming_content) self.assertEqual(b"zulip!", data) self.logout() self.assertEqual(len(queries), 5) # Subscribed user who recieved the message should be able to view file self.login(subscribed_emails[1]) with queries_captured() as queries: response = self.client_get(uri) self.assertEqual(response.status_code, 200) data = b"".join(response.streaming_content) self.assertEqual(b"zulip!", data) self.logout() self.assertEqual(len(queries), 6) def assert_cannot_access_file(user_email: str) -> None: response = self.api_get(user_email, uri) self.assertEqual(response.status_code, 403) self.assert_in_response("You are not authorized to view this file.", response) late_subscribed_user = self.example_user("aaron") self.subscribe(late_subscribed_user, stream_name) assert_cannot_access_file(late_subscribed_user.email) # Unsubscribed user should not be able to view file for unsubscribed_user in unsubscribed_emails: assert_cannot_access_file(unsubscribed_user) def test_file_download_authorization_invite_only_with_shared_history(self) -> None: user = self.example_user("hamlet") subscribed_emails = [user.email, self.example_email("polonius")] unsubscribed_emails = [self.example_email("othello"), self.example_email("prospero")] stream_name = "test-subscribe" self.make_stream(stream_name, realm=user.realm, invite_only=True, history_public_to_subscribers=True) for email in subscribed_emails: self.subscribe(get_user(email, user.realm), stream_name) self.login(user.email) fp = StringIO("zulip!") fp.name = "zulip.txt" result = self.client_post("/json/user_uploads", {'file': fp}) uri = result.json()['uri'] fp_path_id = re.sub('/user_uploads/', '', uri) body = "First message ...[zulip.txt](http://localhost:9991/user_uploads/" + fp_path_id + ")" self.send_stream_message(user.email, stream_name, body, "test") self.logout() # Add aaron as a subscribed after the message was sent late_subscribed_user = self.example_user("aaron") self.subscribe(late_subscribed_user, stream_name) subscribed_emails.append(late_subscribed_user.email) # Owner user should be able to view file self.login(user.email) with queries_captured() as queries: response = self.client_get(uri) self.assertEqual(response.status_code, 200) data = b"".join(response.streaming_content) self.assertEqual(b"zulip!", data) self.logout() self.assertEqual(len(queries), 5) # Originally subscribed user should be able to view file self.login(subscribed_emails[1]) with queries_captured() as queries: response = self.client_get(uri) self.assertEqual(response.status_code, 200) data = b"".join(response.streaming_content) self.assertEqual(b"zulip!", data) self.logout() self.assertEqual(len(queries), 6) # Subscribed user who did not receive the message should also be able to view file self.login(late_subscribed_user.email) with queries_captured() as queries: response = self.client_get(uri) self.assertEqual(response.status_code, 200) data = b"".join(response.streaming_content) self.assertEqual(b"zulip!", data) self.logout() # It takes a few extra queries to verify access because of shared history. self.assertEqual(len(queries), 9) def assert_cannot_access_file(user_email: str) -> None: self.login(user_email) with queries_captured() as queries: response = self.client_get(uri) self.assertEqual(response.status_code, 403) # It takes a few extra queries to verify lack of access with shared history. self.assertEqual(len(queries), 8) self.assert_in_response("You are not authorized to view this file.", response) self.logout() # Unsubscribed user should not be able to view file for unsubscribed_user in unsubscribed_emails: assert_cannot_access_file(unsubscribed_user) def test_multiple_message_attachment_file_download(self) -> None: hamlet = self.example_user("hamlet") for i in range(0, 5): stream_name = "test-subscribe %s" % (i,) self.make_stream(stream_name, realm=hamlet.realm, invite_only=True, history_public_to_subscribers=True) self.subscribe(hamlet, stream_name) self.login(hamlet.email) fp = StringIO("zulip!") fp.name = "zulip.txt" result = self.client_post("/json/user_uploads", {'file': fp}) uri = result.json()['uri'] fp_path_id = re.sub('/user_uploads/', '', uri) for i in range(20): body = "First message ...[zulip.txt](http://localhost:9991/user_uploads/" + fp_path_id + ")" self.send_stream_message(self.example_email("hamlet"), "test-subscribe %s" % (i % 5,), body, "test") self.logout() user = self.example_user("aaron") self.login(user.email) with queries_captured() as queries: response = self.client_get(uri) self.assertEqual(response.status_code, 403) self.assert_in_response("You are not authorized to view this file.", response) self.assertEqual(len(queries), 8) self.subscribe(user, "test-subscribe 1") self.subscribe(user, "test-subscribe 2") with queries_captured() as queries: response = self.client_get(uri) self.assertEqual(response.status_code, 200) data = b"".join(response.streaming_content) self.assertEqual(b"zulip!", data) # If we were accidentally one query per message, this would be 20+ self.assertEqual(len(queries), 9) with queries_captured() as queries: self.assertTrue(validate_attachment_request(user, fp_path_id)) self.assertEqual(len(queries), 6) self.logout() def test_file_download_authorization_public(self) -> None: subscribed_users = [self.example_email("hamlet"), self.example_email("iago")] unsubscribed_users = [self.example_email("othello"), self.example_email("prospero")] realm = get_realm("zulip") for email in subscribed_users: self.subscribe(get_user(email, realm), "test-subscribe") self.login(self.example_email("hamlet")) fp = StringIO("zulip!") fp.name = "zulip.txt" result = self.client_post("/json/user_uploads", {'file': fp}) uri = result.json()['uri'] fp_path_id = re.sub('/user_uploads/', '', uri) body = "First message ...[zulip.txt](http://localhost:9991/user_uploads/" + fp_path_id + ")" self.send_stream_message(self.example_email("hamlet"), "test-subscribe", body, "test") self.logout() # Now all users should be able to access the files for user in subscribed_users + unsubscribed_users: self.login(user) response = self.client_get(uri) data = b"".join(response.streaming_content) self.assertEqual(b"zulip!", data) self.logout() def test_serve_local(self) -> None: def check_xsend_links(name: str, name_str_for_test: str, content_disposition: str='') -> None: with self.settings(SENDFILE_BACKEND='sendfile.backends.nginx'): _get_sendfile.clear() # To clearout cached version of backend from djangosendfile self.login(self.example_email("hamlet")) fp = StringIO("zulip!") fp.name = name result = self.client_post("/json/user_uploads", {'file': fp}) uri = result.json()['uri'] fp_path_id = re.sub('/user_uploads/', '', uri) fp_path = os.path.split(fp_path_id)[0] response = self.client_get(uri) _get_sendfile.clear() test_upload_dir = os.path.split(settings.LOCAL_UPLOADS_DIR)[1] self.assertEqual(response['X-Accel-Redirect'], '/serve_uploads/../../' + test_upload_dir + '/files/' + fp_path + '/' + name_str_for_test) if content_disposition != '': self.assertIn('attachment;', response['Content-disposition']) self.assertIn(content_disposition, response['Content-disposition']) else: self.assertEqual(response.get('Content-disposition'), None) check_xsend_links('zulip.txt', 'zulip.txt', "filename*=UTF-8''zulip.txt") check_xsend_links('áéБД.txt', '%C3%A1%C3%A9%D0%91%D0%94.txt', "filename*=UTF-8''%C3%A1%C3%A9%D0%91%D0%94.txt") check_xsend_links('zulip.html', 'zulip.html', "filename*=UTF-8''zulip.html") check_xsend_links('zulip.sh', 'zulip.sh', "filename*=UTF-8''zulip.sh") check_xsend_links('zulip.jpeg', 'zulip.jpeg') check_xsend_links('áéБД.pdf', '%C3%A1%C3%A9%D0%91%D0%94.pdf') check_xsend_links('zulip', 'zulip', "filename*=UTF-8''zulip") def tearDown(self) -> None: destroy_uploads() class AvatarTest(UploadSerializeMixin, ZulipTestCase): def test_get_avatar_field(self) -> None: with self.settings(AVATAR_SALT="salt"): url = get_avatar_field( user_id=17, realm_id=5, email='foo@example.com', avatar_source=UserProfile.AVATAR_FROM_USER, avatar_version=2, medium=True, client_gravatar=False, ) self.assertEqual( url, '/user_avatars/5/fc2b9f1a81f4508a4df2d95451a2a77e0524ca0e-medium.png?x=x&version=2' ) url = get_avatar_field( user_id=9999, realm_id=9999, email='foo@example.com', avatar_source=UserProfile.AVATAR_FROM_GRAVATAR, avatar_version=2, medium=True, client_gravatar=False, ) self.assertEqual( url, 'https://secure.gravatar.com/avatar/b48def645758b95537d4424c84d1a9ff?d=identicon&s=500&version=2' ) url = get_avatar_field( user_id=9999, realm_id=9999, email='foo@example.com', avatar_source=UserProfile.AVATAR_FROM_GRAVATAR, avatar_version=2, medium=True, client_gravatar=True, ) self.assertEqual(url, None) def test_avatar_url(self) -> None: """Verifies URL schemes for avatars and realm icons.""" backend = LocalUploadBackend() # type: ZulipUploadBackend self.assertEqual(backend.get_avatar_url("hash", False), "/user_avatars/hash.png?x=x") self.assertEqual(backend.get_avatar_url("hash", True), "/user_avatars/hash-medium.png?x=x") self.assertEqual(backend.get_realm_icon_url(15, 1), "/user_avatars/15/realm/icon.png?version=1") with self.settings(S3_AVATAR_BUCKET="bucket"): backend = S3UploadBackend() self.assertEqual(backend.get_avatar_url("hash", False), "https://bucket.s3.amazonaws.com/hash?x=x") self.assertEqual(backend.get_avatar_url("hash", True), "https://bucket.s3.amazonaws.com/hash-medium.png?x=x") self.assertEqual(backend.get_realm_icon_url(15, 1), "https://bucket.s3.amazonaws.com/15/realm/icon.png?version=1") def test_multiple_upload_failure(self) -> None: """ Attempting to upload two files should fail. """ self.login(self.example_email("hamlet")) with get_test_image_file('img.png') as fp1, \ get_test_image_file('img.png') as fp2: result = self.client_post("/json/users/me/avatar", {'f1': fp1, 'f2': fp2}) self.assert_json_error(result, "You must upload exactly one avatar.") def test_no_file_upload_failure(self) -> None: """ Calling this endpoint with no files should fail. """ self.login(self.example_email("hamlet")) result = self.client_post("/json/users/me/avatar") self.assert_json_error(result, "You must upload exactly one avatar.") correct_files = [ ('img.png', 'png_resized.png'), ('img.jpg', None), # jpeg resizing is platform-dependent ('img.gif', 'gif_resized.png'), ('img.tif', 'tif_resized.png'), ('cmyk.jpg', None) ] corrupt_files = ['text.txt', 'corrupt.png', 'corrupt.gif'] def test_get_gravatar_avatar(self) -> None: self.login(self.example_email("hamlet")) cordelia = self.example_user('cordelia') cordelia.avatar_source = UserProfile.AVATAR_FROM_GRAVATAR cordelia.save() with self.settings(ENABLE_GRAVATAR=True): response = self.client_get("/avatar/cordelia@zulip.com?foo=bar") redirect_url = response['Location'] self.assertEqual(redirect_url, str(avatar_url(cordelia)) + '&foo=bar') with self.settings(ENABLE_GRAVATAR=False): response = self.client_get("/avatar/cordelia@zulip.com?foo=bar") redirect_url = response['Location'] self.assertTrue(redirect_url.endswith(str(avatar_url(cordelia)) + '&foo=bar')) def test_get_user_avatar(self) -> None: hamlet = self.example_email("hamlet") self.login(hamlet) cordelia = self.example_user('cordelia') cross_realm_bot = self.example_user('welcome_bot') cordelia.avatar_source = UserProfile.AVATAR_FROM_USER cordelia.save() response = self.client_get("/avatar/cordelia@zulip.com?foo=bar") redirect_url = response['Location'] self.assertTrue(redirect_url.endswith(str(avatar_url(cordelia)) + '&foo=bar')) response = self.client_get("/avatar/%s?foo=bar" % (cordelia.id)) redirect_url = response['Location'] self.assertTrue(redirect_url.endswith(str(avatar_url(cordelia)) + '&foo=bar')) response = self.client_get("/avatar/") self.assertEqual(response.status_code, 404) self.logout() # Test /avatar/<email_or_id> endpoint with HTTP basic auth. response = self.api_get(hamlet, "/avatar/cordelia@zulip.com?foo=bar") redirect_url = response['Location'] self.assertTrue(redirect_url.endswith(str(avatar_url(cordelia)) + '&foo=bar')) response = self.api_get(hamlet, "/avatar/%s?foo=bar" % (cordelia.id)) redirect_url = response['Location'] self.assertTrue(redirect_url.endswith(str(avatar_url(cordelia)) + '&foo=bar')) # Test cross_realm_bot avatar access using email. response = self.api_get(hamlet, "/avatar/welcome-bot@zulip.com?foo=bar") redirect_url = response['Location'] self.assertTrue(redirect_url.endswith(str(avatar_url(cross_realm_bot)) + '&foo=bar')) # Test cross_realm_bot avatar access using id. response = self.api_get(hamlet, "/avatar/%s?foo=bar" % (cross_realm_bot.id)) redirect_url = response['Location'] self.assertTrue(redirect_url.endswith(str(avatar_url(cross_realm_bot)) + '&foo=bar')) response = self.client_get("/avatar/cordelia@zulip.com?foo=bar") self.assert_json_error(response, "Not logged in: API authentication or user session required", status_code=401) def test_get_user_avatar_medium(self) -> None: hamlet = self.example_email("hamlet") self.login(hamlet) cordelia = self.example_user('cordelia') cordelia.avatar_source = UserProfile.AVATAR_FROM_USER cordelia.save() response = self.client_get("/avatar/cordelia@zulip.com/medium?foo=bar") redirect_url = response['Location'] self.assertTrue(redirect_url.endswith(str(avatar_url(cordelia, True)) + '&foo=bar')) response = self.client_get("/avatar/%s/medium?foo=bar" % (cordelia.id,)) redirect_url = response['Location'] self.assertTrue(redirect_url.endswith(str(avatar_url(cordelia, True)) + '&foo=bar')) self.logout() # Test /avatar/<email_or_id>/medium endpoint with HTTP basic auth. response = self.api_get(hamlet, "/avatar/cordelia@zulip.com/medium?foo=bar") redirect_url = response['Location'] self.assertTrue(redirect_url.endswith(str(avatar_url(cordelia, True)) + '&foo=bar')) response = self.api_get(hamlet, "/avatar/%s/medium?foo=bar" % (cordelia.id,)) redirect_url = response['Location'] self.assertTrue(redirect_url.endswith(str(avatar_url(cordelia, True)) + '&foo=bar')) response = self.client_get("/avatar/cordelia@zulip.com/medium?foo=bar") self.assert_json_error(response, "Not logged in: API authentication or user session required", status_code=401) def test_non_valid_user_avatar(self) -> None: # It's debatable whether we should generate avatars for non-users, # but this test just validates the current code's behavior. self.login(self.example_email("hamlet")) response = self.client_get("/avatar/nonexistent_user@zulip.com?foo=bar") redirect_url = response['Location'] actual_url = 'https://secure.gravatar.com/avatar/444258b521f152129eb0c162996e572d?d=identicon&version=1&foo=bar' self.assertEqual(redirect_url, actual_url) def test_valid_avatars(self) -> None: """ A PUT request to /json/users/me/avatar with a valid file should return a url and actually create an avatar. """ version = 2 for fname, rfname in self.correct_files: # TODO: use self.subTest once we're exclusively on python 3 by uncommenting the line below. # with self.subTest(fname=fname): self.login(self.example_email("hamlet")) with get_test_image_file(fname) as fp: result = self.client_post("/json/users/me/avatar", {'file': fp}) self.assert_json_success(result) self.assertIn("avatar_url", result.json()) base = '/user_avatars/' url = result.json()['avatar_url'] self.assertEqual(base, url[:len(base)]) if rfname is not None: response = self.client_get(url) data = b"".join(response.streaming_content) self.assertEqual(Image.open(io.BytesIO(data)).size, (100, 100)) # Verify that the medium-size avatar was created user_profile = self.example_user('hamlet') medium_avatar_disk_path = avatar_disk_path(user_profile, medium=True) self.assertTrue(os.path.exists(medium_avatar_disk_path)) # Verify that ensure_medium_avatar_url does not overwrite this file if it exists with mock.patch('zerver.lib.upload.write_local_file') as mock_write_local_file: zerver.lib.upload.upload_backend.ensure_medium_avatar_image(user_profile) self.assertFalse(mock_write_local_file.called) # Confirm that ensure_medium_avatar_url works to recreate # medium size avatars from the original if needed os.remove(medium_avatar_disk_path) self.assertFalse(os.path.exists(medium_avatar_disk_path)) zerver.lib.upload.upload_backend.ensure_medium_avatar_image(user_profile) self.assertTrue(os.path.exists(medium_avatar_disk_path)) # Verify whether the avatar_version gets incremented with every new upload self.assertEqual(user_profile.avatar_version, version) version += 1 def test_copy_avatar_image(self) -> None: self.login(self.example_email("hamlet")) with get_test_image_file('img.png') as image_file: self.client_post("/json/users/me/avatar", {'file': image_file}) source_user_profile = self.example_user('hamlet') target_user_profile = self.example_user('iago') copy_user_settings(source_user_profile, target_user_profile) source_path_id = avatar_disk_path(source_user_profile) target_path_id = avatar_disk_path(target_user_profile) self.assertNotEqual(source_path_id, target_path_id) self.assertEqual(open(source_path_id, "rb").read(), open(target_path_id, "rb").read()) source_original_path_id = avatar_disk_path(source_user_profile, original=True) target_original_path_id = avatar_disk_path(target_user_profile, original=True) self.assertEqual(open(source_original_path_id, "rb").read(), open(target_original_path_id, "rb").read()) source_medium_path_id = avatar_disk_path(source_user_profile, medium=True) target_medium_path_id = avatar_disk_path(target_user_profile, medium=True) self.assertEqual(open(source_medium_path_id, "rb").read(), open(target_medium_path_id, "rb").read()) def test_delete_avatar_image(self) -> None: self.login(self.example_email("hamlet")) with get_test_image_file('img.png') as image_file: self.client_post("/json/users/me/avatar", {'file': image_file}) user = self.example_user('hamlet') avatar_path_id = avatar_disk_path(user) avatar_original_path_id = avatar_disk_path(user, original=True) avatar_medium_path_id = avatar_disk_path(user, medium=True) self.assertEqual(user.avatar_source, UserProfile.AVATAR_FROM_USER) self.assertTrue(os.path.isfile(avatar_path_id)) self.assertTrue(os.path.isfile(avatar_original_path_id)) self.assertTrue(os.path.isfile(avatar_medium_path_id)) zerver.lib.actions.do_delete_avatar_image(user) self.assertEqual(user.avatar_source, UserProfile.AVATAR_FROM_GRAVATAR) self.assertFalse(os.path.isfile(avatar_path_id)) self.assertFalse(os.path.isfile(avatar_original_path_id)) self.assertFalse(os.path.isfile(avatar_medium_path_id)) def test_invalid_avatars(self) -> None: """ A PUT request to /json/users/me/avatar with an invalid file should fail. """ for fname in self.corrupt_files: # with self.subTest(fname=fname): self.login(self.example_email("hamlet")) with get_test_image_file(fname) as fp: result = self.client_post("/json/users/me/avatar", {'file': fp}) self.assert_json_error(result, "Could not decode image; did you upload an image file?") user_profile = self.example_user('hamlet') self.assertEqual(user_profile.avatar_version, 1) def test_delete_avatar(self) -> None: """ A DELETE request to /json/users/me/avatar should delete the user avatar and return gravatar URL """ self.login(self.example_email("hamlet")) hamlet = self.example_user('hamlet') hamlet.avatar_source = UserProfile.AVATAR_FROM_USER hamlet.save() result = self.client_delete("/json/users/me/avatar") user_profile = self.example_user('hamlet') self.assert_json_success(result) self.assertIn("avatar_url", result.json()) self.assertEqual(result.json()["avatar_url"], avatar_url(user_profile)) self.assertEqual(user_profile.avatar_source, UserProfile.AVATAR_FROM_GRAVATAR) self.assertEqual(user_profile.avatar_version, 2) def test_avatar_upload_file_size_error(self) -> None: self.login(self.example_email("hamlet")) with get_test_image_file(self.correct_files[0][0]) as fp: with self.settings(MAX_AVATAR_FILE_SIZE=0): result = self.client_post("/json/users/me/avatar", {'file': fp}) self.assert_json_error(result, "Uploaded file is larger than the allowed limit of 0 MB") def tearDown(self) -> None: destroy_uploads() class EmojiTest(UploadSerializeMixin, ZulipTestCase): # While testing GIF resizing, we can't test if the final GIF has the same # number of frames as the original one because PIL drops duplicate frames # with a corresponding increase in the duration of the previous frame. def test_resize_emoji(self) -> None: # Test unequal width and height of animated GIF image animated_unequal_img_data = get_test_image_file('animated_unequal_img.gif').read() resized_img_data = resize_emoji(animated_unequal_img_data, size=50) im = Image.open(io.BytesIO(resized_img_data)) self.assertEqual((50, 50), im.size) # Test for large animated image (128x128) animated_large_img_data = get_test_image_file('animated_large_img.gif').read() resized_img_data = resize_emoji(animated_large_img_data, size=50) im = Image.open(io.BytesIO(resized_img_data)) self.assertEqual((50, 50), im.size) # Test corrupt image exception corrupted_img_data = get_test_image_file('corrupt.gif').read() with self.assertRaises(BadImageError): resize_emoji(corrupted_img_data) def tearDown(self) -> None: destroy_uploads() class RealmIconTest(UploadSerializeMixin, ZulipTestCase): def test_multiple_upload_failure(self) -> None: """ Attempting to upload two files should fail. """ # Log in as admin self.login(self.example_email("iago")) with get_test_image_file('img.png') as fp1, \ get_test_image_file('img.png') as fp2: result = self.client_post("/json/realm/icon", {'f1': fp1, 'f2': fp2}) self.assert_json_error(result, "You must upload exactly one icon.") def test_no_file_upload_failure(self) -> None: """ Calling this endpoint with no files should fail. """ self.login(self.example_email("iago")) result = self.client_post("/json/realm/icon") self.assert_json_error(result, "You must upload exactly one icon.") correct_files = [ ('img.png', 'png_resized.png'), ('img.jpg', None), # jpeg resizing is platform-dependent ('img.gif', 'gif_resized.png'), ('img.tif', 'tif_resized.png'), ('cmyk.jpg', None) ] corrupt_files = ['text.txt', 'corrupt.png', 'corrupt.gif'] def test_no_admin_user_upload(self) -> None: self.login(self.example_email("hamlet")) with get_test_image_file(self.correct_files[0][0]) as fp: result = self.client_post("/json/realm/icon", {'file': fp}) self.assert_json_error(result, 'Must be an organization administrator') def test_get_gravatar_icon(self) -> None: self.login(self.example_email("hamlet")) realm = get_realm('zulip') realm.icon_source = Realm.ICON_FROM_GRAVATAR realm.save() with self.settings(ENABLE_GRAVATAR=True): response = self.client_get("/json/realm/icon?foo=bar") redirect_url = response['Location'] self.assertEqual(redirect_url, realm_icon_url(realm) + '&foo=bar') with self.settings(ENABLE_GRAVATAR=False): response = self.client_get("/json/realm/icon?foo=bar") redirect_url = response['Location'] self.assertTrue(redirect_url.endswith(realm_icon_url(realm) + '&foo=bar')) def test_get_realm_icon(self) -> None: self.login(self.example_email("hamlet")) realm = get_realm('zulip') realm.icon_source = Realm.ICON_UPLOADED realm.save() response = self.client_get("/json/realm/icon?foo=bar") redirect_url = response['Location'] self.assertTrue(redirect_url.endswith(realm_icon_url(realm) + '&foo=bar')) def test_valid_icons(self) -> None: """ A PUT request to /json/realm/icon with a valid file should return a url and actually create an realm icon. """ for fname, rfname in self.correct_files: # TODO: use self.subTest once we're exclusively on python 3 by uncommenting the line below. # with self.subTest(fname=fname): self.login(self.example_email("iago")) with get_test_image_file(fname) as fp: result = self.client_post("/json/realm/icon", {'file': fp}) realm = get_realm('zulip') self.assert_json_success(result) self.assertIn("icon_url", result.json()) base = '/user_avatars/%s/realm/icon.png' % (realm.id,) url = result.json()['icon_url'] self.assertEqual(base, url[:len(base)]) if rfname is not None: response = self.client_get(url) data = b"".join(response.streaming_content) self.assertEqual(Image.open(io.BytesIO(data)).size, (100, 100)) def test_invalid_icons(self) -> None: """ A PUT request to /json/realm/icon with an invalid file should fail. """ for fname in self.corrupt_files: # with self.subTest(fname=fname): self.login(self.example_email("iago")) with get_test_image_file(fname) as fp: result = self.client_post("/json/realm/icon", {'file': fp}) self.assert_json_error(result, "Could not decode image; did you upload an image file?") def test_delete_icon(self) -> None: """ A DELETE request to /json/realm/icon should delete the realm icon and return gravatar URL """ self.login(self.example_email("iago")) realm = get_realm('zulip') realm.icon_source = Realm.ICON_UPLOADED realm.save() result = self.client_delete("/json/realm/icon") self.assert_json_success(result) self.assertIn("icon_url", result.json()) realm = get_realm('zulip') self.assertEqual(result.json()["icon_url"], realm_icon_url(realm)) self.assertEqual(realm.icon_source, Realm.ICON_FROM_GRAVATAR) def test_realm_icon_version(self) -> None: self.login(self.example_email("iago")) realm = get_realm('zulip') icon_version = realm.icon_version self.assertEqual(icon_version, 1) with get_test_image_file(self.correct_files[0][0]) as fp: self.client_post("/json/realm/icon", {'file': fp}) realm = get_realm('zulip') self.assertEqual(realm.icon_version, icon_version + 1) def test_realm_icon_upload_file_size_error(self) -> None: self.login(self.example_email("iago")) with get_test_image_file(self.correct_files[0][0]) as fp: with self.settings(MAX_ICON_FILE_SIZE=0): result = self.client_post("/json/realm/icon", {'file': fp}) self.assert_json_error(result, "Uploaded file is larger than the allowed limit of 0 MB") def tearDown(self) -> None: destroy_uploads() class LocalStorageTest(UploadSerializeMixin, ZulipTestCase): def test_file_upload_local(self) -> None: user_profile = self.example_user('hamlet') uri = upload_message_file(u'dummy.txt', len(b'zulip!'), u'text/plain', b'zulip!', user_profile) base = '/user_uploads/' self.assertEqual(base, uri[:len(base)]) path_id = re.sub('/user_uploads/', '', uri) file_path = os.path.join(settings.LOCAL_UPLOADS_DIR, 'files', path_id) self.assertTrue(os.path.isfile(file_path)) uploaded_file = Attachment.objects.get(owner=user_profile, path_id=path_id) self.assertEqual(len(b'zulip!'), uploaded_file.size) def test_delete_message_image_local(self) -> None: self.login(self.example_email("hamlet")) fp = StringIO("zulip!") fp.name = "zulip.txt" result = self.client_post("/json/user_uploads", {'file': fp}) path_id = re.sub('/user_uploads/', '', result.json()['uri']) self.assertTrue(delete_message_image(path_id)) def test_emoji_upload_local(self) -> None: user_profile = self.example_user("hamlet") image_file = get_test_image_file("img.png") file_name = "emoji.png" upload_emoji_image(image_file, file_name, user_profile) emoji_path = RealmEmoji.PATH_ID_TEMPLATE.format( realm_id=user_profile.realm_id, emoji_file_name=file_name, ) file_path = os.path.join(settings.LOCAL_UPLOADS_DIR, "avatars", emoji_path) image_file.seek(0) self.assertEqual(image_file.read(), open(file_path + ".original", "rb").read()) resized_image = Image.open(open(file_path, "rb")) expected_size = (DEFAULT_EMOJI_SIZE, DEFAULT_EMOJI_SIZE) self.assertEqual(expected_size, resized_image.size) def test_get_emoji_url_local(self) -> None: user_profile = self.example_user("hamlet") image_file = get_test_image_file("img.png") file_name = "emoji.png" upload_emoji_image(image_file, file_name, user_profile) url = zerver.lib.upload.upload_backend.get_emoji_url(file_name, user_profile.realm_id) emoji_path = RealmEmoji.PATH_ID_TEMPLATE.format( realm_id=user_profile.realm_id, emoji_file_name=file_name, ) expected_url = "/user_avatars/{emoji_path}".format(emoji_path=emoji_path) self.assertEqual(expected_url, url) def tearDown(self) -> None: destroy_uploads() class S3Test(ZulipTestCase): @use_s3_backend def test_file_upload_s3(self) -> None: conn = S3Connection(settings.S3_KEY, settings.S3_SECRET_KEY) bucket = conn.create_bucket(settings.S3_AUTH_UPLOADS_BUCKET) user_profile = self.example_user('hamlet') uri = upload_message_file(u'dummy.txt', len(b'zulip!'), u'text/plain', b'zulip!', user_profile) base = '/user_uploads/' self.assertEqual(base, uri[:len(base)]) path_id = re.sub('/user_uploads/', '', uri) content = bucket.get_key(path_id).get_contents_as_string() self.assertEqual(b"zulip!", content) uploaded_file = Attachment.objects.get(owner=user_profile, path_id=path_id) self.assertEqual(len(b"zulip!"), uploaded_file.size) self.subscribe(self.example_user("hamlet"), "Denmark") body = "First message ...[zulip.txt](http://localhost:9991" + uri + ")" self.send_stream_message(self.example_email("hamlet"), "Denmark", body, "test") self.assertIn('title="dummy.txt"', self.get_last_message().rendered_content) @use_s3_backend def test_file_upload_s3_with_undefined_content_type(self) -> None: conn = S3Connection(settings.S3_KEY, settings.S3_SECRET_KEY) bucket = conn.create_bucket(settings.S3_AUTH_UPLOADS_BUCKET) user_profile = self.example_user('hamlet') uri = upload_message_file(u'dummy.txt', len(b'zulip!'), None, b'zulip!', user_profile) path_id = re.sub('/user_uploads/', '', uri) self.assertEqual(b"zulip!", bucket.get_key(path_id).get_contents_as_string()) uploaded_file = Attachment.objects.get(owner=user_profile, path_id=path_id) self.assertEqual(len(b"zulip!"), uploaded_file.size) @use_s3_backend def test_message_image_delete_s3(self) -> None: conn = S3Connection(settings.S3_KEY, settings.S3_SECRET_KEY) conn.create_bucket(settings.S3_AUTH_UPLOADS_BUCKET) user_profile = self.example_user('hamlet') uri = upload_message_file(u'dummy.txt', len(b'zulip!'), u'text/plain', b'zulip!', user_profile) path_id = re.sub('/user_uploads/', '', uri) self.assertTrue(delete_message_image(path_id)) @use_s3_backend def test_message_image_delete_when_file_doesnt_exist(self) -> None: self.assertEqual(False, delete_message_image('non-existant-file')) @use_s3_backend def test_file_upload_authed(self) -> None: """ A call to /json/user_uploads should return a uri and actually create an object. """ conn = S3Connection(settings.S3_KEY, settings.S3_SECRET_KEY) conn.create_bucket(settings.S3_AUTH_UPLOADS_BUCKET) self.login(self.example_email("hamlet")) fp = StringIO("zulip!") fp.name = "zulip.txt" result = self.client_post("/json/user_uploads", {'file': fp}) self.assert_json_success(result) self.assertIn("uri", result.json()) base = '/user_uploads/' uri = result.json()['uri'] self.assertEqual(base, uri[:len(base)]) response = self.client_get(uri) redirect_url = response['Location'] self.assertEqual(b"zulip!", urllib.request.urlopen(redirect_url).read().strip()) self.subscribe(self.example_user("hamlet"), "Denmark") body = "First message ...[zulip.txt](http://localhost:9991" + uri + ")" self.send_stream_message(self.example_email("hamlet"), "Denmark", body, "test") self.assertIn('title="zulip.txt"', self.get_last_message().rendered_content) @use_s3_backend def test_upload_avatar_image(self) -> None: conn = S3Connection(settings.S3_KEY, settings.S3_SECRET_KEY) bucket = conn.create_bucket(settings.S3_AVATAR_BUCKET) user_profile = self.example_user('hamlet') path_id = user_avatar_path(user_profile) original_image_path_id = path_id + ".original" medium_path_id = path_id + "-medium.png" with get_test_image_file('img.png') as image_file: zerver.lib.upload.upload_backend.upload_avatar_image(image_file, user_profile, user_profile) test_image_data = open(get_test_image_file('img.png').name, 'rb').read() test_medium_image_data = resize_avatar(test_image_data, MEDIUM_AVATAR_SIZE) original_image_key = bucket.get_key(original_image_path_id) self.assertEqual(original_image_key.key, original_image_path_id) image_data = original_image_key.get_contents_as_string() self.assertEqual(image_data, test_image_data) medium_image_key = bucket.get_key(medium_path_id) self.assertEqual(medium_image_key.key, medium_path_id) medium_image_data = medium_image_key.get_contents_as_string() self.assertEqual(medium_image_data, test_medium_image_data) bucket.delete_key(medium_image_key) zerver.lib.upload.upload_backend.ensure_medium_avatar_image(user_profile) medium_image_key = bucket.get_key(medium_path_id) self.assertEqual(medium_image_key.key, medium_path_id) @use_s3_backend def test_copy_avatar_image(self) -> None: conn = S3Connection(settings.S3_KEY, settings.S3_SECRET_KEY) bucket = conn.create_bucket(settings.S3_AVATAR_BUCKET) self.login(self.example_email("hamlet")) with get_test_image_file('img.png') as image_file: self.client_post("/json/users/me/avatar", {'file': image_file}) source_user_profile = self.example_user('hamlet') target_user_profile = self.example_user('othello') copy_user_settings(source_user_profile, target_user_profile) source_path_id = user_avatar_path(source_user_profile) target_path_id = user_avatar_path(target_user_profile) self.assertNotEqual(source_path_id, target_path_id) source_image_key = bucket.get_key(source_path_id) target_image_key = bucket.get_key(target_path_id) self.assertEqual(target_image_key.key, target_path_id) self.assertEqual(source_image_key.content_type, target_image_key.content_type) source_image_data = source_image_key.get_contents_as_string() target_image_data = target_image_key.get_contents_as_string() self.assertEqual(source_image_data, target_image_data) source_original_image_path_id = source_path_id + ".original" target_original_image_path_id = target_path_id + ".original" target_original_image_key = bucket.get_key(target_original_image_path_id) self.assertEqual(target_original_image_key.key, target_original_image_path_id) source_original_image_key = bucket.get_key(source_original_image_path_id) self.assertEqual(source_original_image_key.content_type, target_original_image_key.content_type) source_image_data = source_original_image_key.get_contents_as_string() target_image_data = target_original_image_key.get_contents_as_string() self.assertEqual(source_image_data, target_image_data) target_medium_path_id = target_path_id + "-medium.png" source_medium_path_id = source_path_id + "-medium.png" source_medium_image_key = bucket.get_key(source_medium_path_id) target_medium_image_key = bucket.get_key(target_medium_path_id) self.assertEqual(target_medium_image_key.key, target_medium_path_id) self.assertEqual(source_medium_image_key.content_type, target_medium_image_key.content_type) source_medium_image_data = source_medium_image_key.get_contents_as_string() target_medium_image_data = target_medium_image_key.get_contents_as_string() self.assertEqual(source_medium_image_data, target_medium_image_data) @use_s3_backend def test_delete_avatar_image(self) -> None: conn = S3Connection(settings.S3_KEY, settings.S3_SECRET_KEY) bucket = conn.create_bucket(settings.S3_AVATAR_BUCKET) self.login(self.example_email("hamlet")) with get_test_image_file('img.png') as image_file: self.client_post("/json/users/me/avatar", {'file': image_file}) user = self.example_user('hamlet') avatar_path_id = user_avatar_path(user) avatar_original_image_path_id = avatar_path_id + ".original" avatar_medium_path_id = avatar_path_id + "-medium.png" self.assertEqual(user.avatar_source, UserProfile.AVATAR_FROM_USER) self.assertIsNotNone(bucket.get_key(avatar_path_id)) self.assertIsNotNone(bucket.get_key(avatar_original_image_path_id)) self.assertIsNotNone(bucket.get_key(avatar_medium_path_id)) zerver.lib.actions.do_delete_avatar_image(user) self.assertEqual(user.avatar_source, UserProfile.AVATAR_FROM_GRAVATAR) self.assertIsNone(bucket.get_key(avatar_path_id)) self.assertIsNone(bucket.get_key(avatar_original_image_path_id)) self.assertIsNone(bucket.get_key(avatar_medium_path_id)) @use_s3_backend def test_get_realm_for_filename(self) -> None: conn = S3Connection(settings.S3_KEY, settings.S3_SECRET_KEY) conn.create_bucket(settings.S3_AUTH_UPLOADS_BUCKET) user_profile = self.example_user('hamlet') uri = upload_message_file(u'dummy.txt', len(b'zulip!'), u'text/plain', b'zulip!', user_profile) path_id = re.sub('/user_uploads/', '', uri) self.assertEqual(user_profile.realm_id, get_realm_for_filename(path_id)) @use_s3_backend def test_get_realm_for_filename_when_key_doesnt_exist(self) -> None: self.assertEqual(None, get_realm_for_filename('non-existent-file-path')) @use_s3_backend def test_upload_realm_icon_image(self) -> None: conn = S3Connection(settings.S3_KEY, settings.S3_SECRET_KEY) bucket = conn.create_bucket(settings.S3_AVATAR_BUCKET) user_profile = self.example_user("hamlet") image_file = get_test_image_file("img.png") zerver.lib.upload.upload_backend.upload_realm_icon_image(image_file, user_profile) original_path_id = os.path.join(str(user_profile.realm.id), "realm", "icon.original") original_key = bucket.get_key(original_path_id) image_file.seek(0) self.assertEqual(image_file.read(), original_key.get_contents_as_string()) resized_path_id = os.path.join(str(user_profile.realm.id), "realm", "icon.png") resized_data = bucket.get_key(resized_path_id).read() resized_image = Image.open(io.BytesIO(resized_data)).size self.assertEqual(resized_image, (DEFAULT_AVATAR_SIZE, DEFAULT_AVATAR_SIZE)) @use_s3_backend def test_upload_emoji_image(self) -> None: conn = S3Connection(settings.S3_KEY, settings.S3_SECRET_KEY) bucket = conn.create_bucket(settings.S3_AVATAR_BUCKET) user_profile = self.example_user("hamlet") image_file = get_test_image_file("img.png") emoji_name = "emoji.png" zerver.lib.upload.upload_backend.upload_emoji_image(image_file, emoji_name, user_profile) emoji_path = RealmEmoji.PATH_ID_TEMPLATE.format( realm_id=user_profile.realm_id, emoji_file_name=emoji_name, ) original_key = bucket.get_key(emoji_path + ".original") image_file.seek(0) self.assertEqual(image_file.read(), original_key.get_contents_as_string()) resized_data = bucket.get_key(emoji_path).read() resized_image = Image.open(io.BytesIO(resized_data)) self.assertEqual(resized_image.size, (DEFAULT_EMOJI_SIZE, DEFAULT_EMOJI_SIZE)) @use_s3_backend def test_get_emoji_url(self) -> None: emoji_name = "emoji.png" realm_id = 1 bucket = settings.S3_AVATAR_BUCKET path = RealmEmoji.PATH_ID_TEMPLATE.format(realm_id=realm_id, emoji_file_name=emoji_name) url = zerver.lib.upload.upload_backend.get_emoji_url('emoji.png', realm_id) expected_url = "https://{bucket}.s3.amazonaws.com/{path}".format(bucket=bucket, path=path) self.assertEqual(expected_url, url) class UploadTitleTests(TestCase): def test_upload_titles(self) -> None: self.assertEqual(url_filename("http://localhost:9991/user_uploads/1/LUeQZUG5jxkagzVzp1Ox_amr/dummy.txt"), "dummy.txt") self.assertEqual(url_filename("http://localhost:9991/user_uploads/1/94/SzGYe0RFT-tEcOhQ6n-ZblFZ/zulip.txt"), "zulip.txt") self.assertEqual(url_filename("https://zulip.com/user_uploads/4142/LUeQZUG5jxkagzVzp1Ox_amr/pasted_image.png"), "pasted_image.png") self.assertEqual(url_filename("https://zulipchat.com/integrations"), "https://zulipchat.com/integrations") self.assertEqual(url_filename("https://example.com"), "https://example.com") class SanitizeNameTests(TestCase): def test_file_name(self) -> None: self.assertEqual(sanitize_name(u'test.txt'), u'test.txt') self.assertEqual(sanitize_name(u'.hidden'), u'.hidden') self.assertEqual(sanitize_name(u'.hidden.txt'), u'.hidden.txt') self.assertEqual(sanitize_name(u'tarball.tar.gz'), u'tarball.tar.gz') self.assertEqual(sanitize_name(u'.hidden_tarball.tar.gz'), u'.hidden_tarball.tar.gz') self.assertEqual(sanitize_name(u'Testing{}*&*#().ta&&%$##&&r.gz'), u'Testing.tar.gz') self.assertEqual(sanitize_name(u'*testingfile?*.txt'), u'testingfile.txt') self.assertEqual(sanitize_name(u'snowman☃.txt'), u'snowman.txt') self.assertEqual(sanitize_name(u'테스트.txt'), u'테스트.txt') self.assertEqual(sanitize_name(u'~/."\\`\\?*"u0`000ssh/test.t**{}ar.gz'), u'.u0000sshtest.tar.gz') class UploadSpaceTests(UploadSerializeMixin, ZulipTestCase): def setUp(self) -> None: self.realm = get_realm("zulip") self.user_profile = self.example_user('hamlet') def test_currently_used_upload_space(self) -> None: self.assertEqual(0, currently_used_upload_space(self.realm)) data = b'zulip!' upload_message_file(u'dummy.txt', len(data), u'text/plain', data, self.user_profile) self.assertEqual(len(data), currently_used_upload_space(self.realm)) data2 = b'more-data!' upload_message_file(u'dummy2.txt', len(data2), u'text/plain', data2, self.user_profile) self.assertEqual(len(data) + len(data2), currently_used_upload_space(self.realm)) class ExifRotateTests(TestCase): def test_image_do_not_rotate(self) -> None: # Image does not have _getexif method. img_data = get_test_image_file('img.png').read() img = Image.open(io.BytesIO(img_data)) result = exif_rotate(img) self.assertEqual(result, img) # Image with no exif data. img_data = get_test_image_file('img_no_exif.jpg').read() img = Image.open(io.BytesIO(img_data)) result = exif_rotate(img) self.assertEqual(result, img) # Orientation of the image is 1. img_data = get_test_image_file('img.jpg').read() img = Image.open(io.BytesIO(img_data)) result = exif_rotate(img) self.assertEqual(result, img) def test_image_rotate(self) -> None: with mock.patch('PIL.Image.Image.rotate') as rotate: img_data = get_test_image_file('img_orientation_3.jpg').read() img = Image.open(io.BytesIO(img_data)) exif_rotate(img) rotate.assert_called_with(180, expand=True) img_data = get_test_image_file('img_orientation_6.jpg').read() img = Image.open(io.BytesIO(img_data)) exif_rotate(img) rotate.assert_called_with(270, expand=True) img_data = get_test_image_file('img_orientation_8.jpg').read() img = Image.open(io.BytesIO(img_data)) exif_rotate(img) rotate.assert_called_with(90, expand=True)
[ "str", "str", "str", "str", "str", "str" ]
[ 20753, 20768, 24607, 27811, 31595, 31619 ]
[ 20756, 20771, 24610, 27814, 31598, 31622 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_urls.py
# -*- coding: utf-8 -*- import importlib import os import ujson import django.urls.resolvers from django.test import TestCase, Client from typing import List, Optional from zerver.lib.test_classes import ZulipTestCase from zerver.lib.test_runner import slow from zerver.models import Stream from zproject import urls class PublicURLTest(ZulipTestCase): """ Account creation URLs are accessible even when not logged in. Authenticated URLs redirect to a page. """ def fetch(self, method: str, urls: List[str], expected_status: int) -> None: for url in urls: # e.g. self.client_post(url) if method is "post" response = getattr(self, method)(url) self.assertEqual(response.status_code, expected_status, msg="Expected %d, received %d for %s to %s" % ( expected_status, response.status_code, method, url)) @slow("Tests dozens of endpoints, including all of our /help/ documents") def test_public_urls(self) -> None: """ Test which views are accessible when not logged in. """ # FIXME: We should also test the Tornado URLs -- this codepath # can't do so because this Django test mechanism doesn't go # through Tornado. denmark_stream_id = Stream.objects.get(name='Denmark').id get_urls = {200: ["/accounts/home/", "/accounts/login/" "/en/accounts/home/", "/ru/accounts/home/", "/en/accounts/login/", "/ru/accounts/login/", "/help/"], 302: ["/", "/en/", "/ru/"], 401: ["/json/streams/%d/members" % (denmark_stream_id,), "/api/v1/users/me/subscriptions", "/api/v1/messages", "/json/messages", "/api/v1/streams", ], 404: ["/help/nonexistent", "/help/include/admin"], } # Add all files in 'templates/zerver/help' directory (except for 'main.html' and # 'index.md') to `get_urls['200']` list. for doc in os.listdir('./templates/zerver/help'): if doc.startswith(".") or '~' in doc or '#' in doc: continue # nocoverage -- just here for convenience if doc not in {'main.html', 'index.md', 'include'}: get_urls[200].append('/help/' + os.path.splitext(doc)[0]) # Strip the extension. post_urls = {200: ["/accounts/login/"], 302: ["/accounts/logout/"], 401: ["/json/messages", "/json/invites", "/json/subscriptions/exists", "/api/v1/users/me/subscriptions/properties", "/json/fetch_api_key", "/json/users/me/pointer", "/json/users/me/subscriptions", "/api/v1/users/me/subscriptions", ], 400: ["/api/v1/external/github", "/api/v1/fetch_api_key", ], } patch_urls = { 401: ["/json/settings"], } put_urls = {401: ["/json/users/me/pointer"], } for status_code, url_set in get_urls.items(): self.fetch("client_get", url_set, status_code) for status_code, url_set in post_urls.items(): self.fetch("client_post", url_set, status_code) for status_code, url_set in patch_urls.items(): self.fetch("client_patch", url_set, status_code) for status_code, url_set in put_urls.items(): self.fetch("client_put", url_set, status_code) def test_get_gcid_when_not_configured(self) -> None: with self.settings(GOOGLE_CLIENT_ID=None): resp = self.client_get("/api/v1/fetch_google_client_id") self.assertEqual(400, resp.status_code, msg="Expected 400, received %d for GET /api/v1/fetch_google_client_id" % ( resp.status_code,)) self.assertEqual('error', resp.json()['result']) def test_get_gcid_when_configured(self) -> None: with self.settings(GOOGLE_CLIENT_ID="ABCD"): resp = self.client_get("/api/v1/fetch_google_client_id") self.assertEqual(200, resp.status_code, msg="Expected 200, received %d for GET /api/v1/fetch_google_client_id" % ( resp.status_code,)) data = ujson.loads(resp.content) self.assertEqual('success', data['result']) self.assertEqual('ABCD', data['google_client_id']) class URLResolutionTest(TestCase): def get_callback_string(self, pattern: django.urls.resolvers.RegexURLPattern) -> Optional[str]: callback_str = hasattr(pattern, 'lookup_str') and 'lookup_str' callback_str = callback_str or '_callback_str' return getattr(pattern, callback_str, None) def check_function_exists(self, module_name: str, view: str) -> None: module = importlib.import_module(module_name) self.assertTrue(hasattr(module, view), "View %s.%s does not exist" % (module_name, view)) # Tests that all views in urls.v1_api_and_json_patterns exist def test_rest_api_url_resolution(self) -> None: for pattern in urls.v1_api_and_json_patterns: callback_str = self.get_callback_string(pattern) if callback_str and hasattr(pattern, "default_args"): for func_string in pattern.default_args.values(): if isinstance(func_string, tuple): func_string = func_string[0] module_name, view = func_string.rsplit('.', 1) self.check_function_exists(module_name, view) # Tests function-based views declared in urls.urlpatterns for # whether the function exists. We at present do not test the # class-based views. def test_non_api_url_resolution(self) -> None: for pattern in urls.urlpatterns: callback_str = self.get_callback_string(pattern) if callback_str: (module_name, base_view) = callback_str.rsplit(".", 1) self.check_function_exists(module_name, base_view) class ErrorPageTest(TestCase): def test_bogus_http_host(self) -> None: # This tests that we've successfully worked around a certain bug in # Django's exception handling. The enforce_csrf_checks=True, # secure=True, and HTTP_REFERER with an `https:` scheme are all # there to get us down just the right path for Django to blow up # when presented with an HTTP_HOST that's not a valid DNS name. client = Client(enforce_csrf_checks=True) result = client.post('/json/users', secure=True, HTTP_REFERER='https://somewhere', HTTP_HOST='$nonsense') self.assertEqual(result.status_code, 400)
[ "str", "List[str]", "int", "django.urls.resolvers.RegexURLPattern", "str", "str" ]
[ 511, 522, 550, 4949, 5234, 5245 ]
[ 514, 531, 553, 4986, 5237, 5248 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_user_groups.py
# -*- coding: utf-8 -*- from typing import Any, List, Optional import ujson import django import mock from zerver.lib.actions import ( ensure_stream, ) from zerver.lib.test_classes import ZulipTestCase from zerver.lib.test_helpers import ( most_recent_usermessage, ) from zerver.lib.user_groups import ( check_add_user_to_user_group, check_remove_user_from_user_group, create_user_group, get_user_groups, user_groups_in_realm, get_memberships_of_users, user_groups_in_realm_serialized, ) from zerver.models import UserProfile, UserGroup, get_realm, Realm, \ UserGroupMembership class UserGroupTestCase(ZulipTestCase): def create_user_group_for_test(self, group_name: str, realm: Realm=get_realm('zulip')) -> UserGroup: members = [self.example_user('othello')] return create_user_group(group_name, members, realm) def test_user_groups_in_realm(self) -> None: realm = get_realm('zulip') self.assertEqual(len(user_groups_in_realm(realm)), 1) self.create_user_group_for_test('support') user_groups = user_groups_in_realm(realm) self.assertEqual(len(user_groups), 2) names = set([ug.name for ug in user_groups]) self.assertEqual(names, set(['hamletcharacters', 'support'])) def test_user_groups_in_realm_serialized(self) -> None: realm = get_realm('zulip') user_group = UserGroup.objects.first() membership = UserGroupMembership.objects.filter(user_group=user_group) membership = membership.values_list('user_profile_id', flat=True) empty_user_group = create_user_group('newgroup', [], realm) user_groups = user_groups_in_realm_serialized(realm) self.assertEqual(len(user_groups), 2) self.assertEqual(user_groups[0]['id'], user_group.id) self.assertEqual(user_groups[0]['name'], 'hamletcharacters') self.assertEqual(user_groups[0]['description'], 'Characters of Hamlet') self.assertEqual(set(user_groups[0]['members']), set(membership)) self.assertEqual(user_groups[1]['id'], empty_user_group.id) self.assertEqual(user_groups[1]['name'], 'newgroup') self.assertEqual(user_groups[1]['description'], '') self.assertEqual(user_groups[1]['members'], []) def test_get_user_groups(self) -> None: othello = self.example_user('othello') self.create_user_group_for_test('support') user_groups = get_user_groups(othello) self.assertEqual(len(user_groups), 1) self.assertEqual(user_groups[0].name, 'support') def test_check_add_user_to_user_group(self) -> None: user_group = self.create_user_group_for_test('support') hamlet = self.example_user('hamlet') self.assertTrue(check_add_user_to_user_group(hamlet, user_group)) self.assertFalse(check_add_user_to_user_group(hamlet, user_group)) def test_check_remove_user_from_user_group(self) -> None: user_group = self.create_user_group_for_test('support') othello = self.example_user('othello') self.assertTrue(check_remove_user_from_user_group(othello, user_group)) self.assertFalse(check_remove_user_from_user_group(othello, user_group)) with mock.patch('zerver.lib.user_groups.remove_user_from_user_group', side_effect=Exception): self.assertFalse(check_remove_user_from_user_group(othello, user_group)) class UserGroupAPITestCase(ZulipTestCase): def test_user_group_create(self) -> None: hamlet = self.example_user('hamlet') # Test success self.login(self.example_email("hamlet")) params = { 'name': 'support', 'members': ujson.dumps([hamlet.id]), 'description': 'Support team', } result = self.client_post('/json/user_groups/create', info=params) self.assert_json_success(result) self.assert_length(UserGroup.objects.all(), 2) # Test invalid member error params = { 'name': 'backend', 'members': ujson.dumps([1111]), 'description': 'Backend team', } result = self.client_post('/json/user_groups/create', info=params) self.assert_json_error(result, "Invalid user ID: 1111") self.assert_length(UserGroup.objects.all(), 2) # Test we cannot add hamlet again params = { 'name': 'support', 'members': ujson.dumps([hamlet.id]), 'description': 'Support team', } result = self.client_post('/json/user_groups/create', info=params) self.assert_json_error(result, "User group 'support' already exists.") self.assert_length(UserGroup.objects.all(), 2) def test_user_group_get(self) -> None: # Test success user_profile = self.example_user('hamlet') self.login(user_profile.email) result = self.client_get('/json/user_groups') self.assert_json_success(result) self.assert_length(result.json()['user_groups'], UserGroup.objects.filter(realm=user_profile.realm).count()) def test_user_group_create_by_guest_user(self) -> None: guest_user = self.example_user('polonius') # Guest users can't create user group self.login(guest_user.email) params = { 'name': 'support', 'members': ujson.dumps([guest_user.id]), 'description': 'Support team', } result = self.client_post('/json/user_groups/create', info=params) self.assert_json_error(result, "Not allowed for guest users") def test_user_group_update(self) -> None: hamlet = self.example_user('hamlet') self.login(self.example_email("hamlet")) params = { 'name': 'support', 'members': ujson.dumps([hamlet.id]), 'description': 'Support team', } self.client_post('/json/user_groups/create', info=params) user_group = UserGroup.objects.get(name='support') # Test success params = { 'name': 'help', 'description': 'Troubleshooting team', } result = self.client_patch('/json/user_groups/{}'.format(user_group.id), info=params) self.assert_json_success(result) self.assertEqual(result.json()['name'], 'Name successfully updated.') self.assertEqual(result.json()['description'], 'Description successfully updated.') # Test when new data is not supplied. result = self.client_patch('/json/user_groups/{}'.format(user_group.id), info={}) self.assert_json_error(result, "No new data supplied") # Test when invalid user group is supplied params = {'name': 'help'} result = self.client_patch('/json/user_groups/1111', info=params) self.assert_json_error(result, "Invalid user group") self.logout() # Test when user not a member of user group tries to modify it cordelia = self.example_user('cordelia') self.login(cordelia.email) params = { 'name': 'help', 'description': 'Troubleshooting', } result = self.client_patch('/json/user_groups/{}'.format(user_group.id), info=params) self.assert_json_error(result, "Only group members and organization administrators can administer this group.") self.logout() # Test when organization admin tries to modify group iago = self.example_user('iago') self.login(iago.email) params = { 'name': 'help', 'description': 'Troubleshooting', } result = self.client_patch('/json/user_groups/{}'.format(user_group.id), info=params) self.assert_json_success(result) self.assertEqual(result.json()['description'], 'Description successfully updated.') def test_user_group_update_by_guest_user(self) -> None: hamlet = self.example_user('hamlet') guest_user = self.example_user('polonius') self.login(hamlet.email) params = { 'name': 'support', 'members': ujson.dumps([hamlet.id, guest_user.id]), 'description': 'Support team', } result = self.client_post('/json/user_groups/create', info=params) self.assert_json_success(result) user_group = UserGroup.objects.get(name='support') # Guest user can't edit any detail of an user group self.login(guest_user.email) params = { 'name': 'help', 'description': 'Troubleshooting team', } result = self.client_patch('/json/user_groups/{}'.format(user_group.id), info=params) self.assert_json_error(result, "Not allowed for guest users") def test_user_group_update_to_already_existing_name(self) -> None: hamlet = self.example_user('hamlet') self.login(hamlet.email) realm = get_realm('zulip') support_user_group = create_user_group('support', [hamlet], realm) marketing_user_group = create_user_group('marketing', [hamlet], realm) params = { 'name': marketing_user_group.name, } result = self.client_patch('/json/user_groups/{}'.format(support_user_group.id), info=params) self.assert_json_error( result, "User group '{}' already exists.".format(marketing_user_group.name)) def test_user_group_delete(self) -> None: hamlet = self.example_user('hamlet') self.login(self.example_email("hamlet")) params = { 'name': 'support', 'members': ujson.dumps([hamlet.id]), 'description': 'Support team', } self.client_post('/json/user_groups/create', info=params) user_group = UserGroup.objects.get(name='support') # Test success self.assertEqual(UserGroup.objects.count(), 2) self.assertEqual(UserGroupMembership.objects.count(), 3) result = self.client_delete('/json/user_groups/{}'.format(user_group.id)) self.assert_json_success(result) self.assertEqual(UserGroup.objects.count(), 1) self.assertEqual(UserGroupMembership.objects.count(), 2) # Test when invalid user group is supplied result = self.client_delete('/json/user_groups/1111') self.assert_json_error(result, "Invalid user group") # Test when user not a member of user group tries to delete it params = { 'name': 'Development', 'members': ujson.dumps([hamlet.id]), 'description': 'Development team', } self.client_post('/json/user_groups/create', info=params) user_group = UserGroup.objects.get(name='Development') self.assertEqual(UserGroup.objects.count(), 2) self.logout() cordelia = self.example_user('cordelia') self.login(cordelia.email) result = self.client_delete('/json/user_groups/{}'.format(user_group.id)) self.assert_json_error(result, "Only group members and organization administrators can administer this group.") self.assertEqual(UserGroup.objects.count(), 2) self.logout() # Test when organization admin tries to delete group iago = self.example_user('iago') self.login(iago.email) result = self.client_delete('/json/user_groups/{}'.format(user_group.id)) self.assert_json_success(result) self.assertEqual(UserGroup.objects.count(), 1) self.assertEqual(UserGroupMembership.objects.count(), 2) def test_user_group_delete_by_guest_user(self) -> None: hamlet = self.example_user('hamlet') guest_user = self.example_user('polonius') self.login(hamlet.email) params = { 'name': 'support', 'members': ujson.dumps([hamlet.id, guest_user.id]), 'description': 'Support team', } result = self.client_post('/json/user_groups/create', info=params) self.assert_json_success(result) user_group = UserGroup.objects.get(name='support') # Guest users can't delete any user group(not even those of which they are a member) self.login(guest_user.email) result = self.client_delete('/json/user_groups/{}'.format(user_group.id)) self.assert_json_error(result, "Not allowed for guest users") def test_update_members_of_user_group(self) -> None: hamlet = self.example_user('hamlet') self.login(self.example_email("hamlet")) params = { 'name': 'support', 'members': ujson.dumps([hamlet.id]), 'description': 'Support team', } self.client_post('/json/user_groups/create', info=params) user_group = UserGroup.objects.get(name='support') # Test add members self.assertEqual(UserGroupMembership.objects.count(), 3) othello = self.example_user('othello') add = [othello.id] params = {'add': ujson.dumps(add)} result = self.client_post('/json/user_groups/{}/members'.format(user_group.id), info=params) self.assert_json_success(result) self.assertEqual(UserGroupMembership.objects.count(), 4) members = get_memberships_of_users(user_group, [hamlet, othello]) self.assertEqual(len(members), 2) # Test adding a member already there. result = self.client_post('/json/user_groups/{}/members'.format(user_group.id), info=params) self.assert_json_error(result, "User 6 is already a member of this group") self.assertEqual(UserGroupMembership.objects.count(), 4) members = get_memberships_of_users(user_group, [hamlet, othello]) self.assertEqual(len(members), 2) self.logout() # Test when user not a member of user group tries to add members to it cordelia = self.example_user('cordelia') self.login(cordelia.email) add = [cordelia.id] params = {'add': ujson.dumps(add)} result = self.client_post('/json/user_groups/{}/members'.format(user_group.id), info=params) self.assert_json_error(result, "Only group members and organization administrators can administer this group.") self.assertEqual(UserGroupMembership.objects.count(), 4) self.logout() # Test when organization admin tries to add members to group iago = self.example_user('iago') self.login(iago.email) aaron = self.example_user('aaron') add = [aaron.id] params = {'add': ujson.dumps(add)} result = self.client_post('/json/user_groups/{}/members'.format(user_group.id), info=params) self.assert_json_success(result) self.assertEqual(UserGroupMembership.objects.count(), 5) members = get_memberships_of_users(user_group, [hamlet, othello, aaron]) self.assertEqual(len(members), 3) # For normal testing we again login with hamlet self.logout() self.login(hamlet.email) # Test remove members params = {'delete': ujson.dumps([othello.id])} result = self.client_post('/json/user_groups/{}/members'.format(user_group.id), info=params) self.assert_json_success(result) self.assertEqual(UserGroupMembership.objects.count(), 4) members = get_memberships_of_users(user_group, [hamlet, othello, aaron]) self.assertEqual(len(members), 2) # Test remove a member that's already removed params = {'delete': ujson.dumps([othello.id])} result = self.client_post('/json/user_groups/{}/members'.format(user_group.id), info=params) self.assert_json_error(result, "There is no member '6' in this user group") self.assertEqual(UserGroupMembership.objects.count(), 4) members = get_memberships_of_users(user_group, [hamlet, othello, aaron]) self.assertEqual(len(members), 2) # Test when nothing is provided result = self.client_post('/json/user_groups/{}/members'.format(user_group.id), info={}) msg = 'Nothing to do. Specify at least one of "add" or "delete".' self.assert_json_error(result, msg) # Test when user not a member of user group tries to remove members self.logout() self.login(cordelia.email) params = {'delete': ujson.dumps([hamlet.id])} result = self.client_post('/json/user_groups/{}/members'.format(user_group.id), info=params) self.assert_json_error(result, "Only group members and organization administrators can administer this group.") self.assertEqual(UserGroupMembership.objects.count(), 4) self.logout() # Test when organization admin tries to remove members from group iago = self.example_user('iago') self.login(iago.email) result = self.client_post('/json/user_groups/{}/members'.format(user_group.id), info=params) self.assert_json_success(result) self.assertEqual(UserGroupMembership.objects.count(), 3) members = get_memberships_of_users(user_group, [hamlet, othello, aaron]) self.assertEqual(len(members), 1) def test_mentions(self) -> None: cordelia = self.example_user('cordelia') hamlet = self.example_user('hamlet') othello = self.example_user('othello') zoe = self.example_user('ZOE') realm = cordelia.realm group_name = 'support' stream_name = 'Dev Help' content_with_group_mention = 'hey @*support* can you help us with this?' ensure_stream(realm, stream_name) all_users = {cordelia, hamlet, othello, zoe} support_team = {hamlet, zoe} sender = cordelia other_users = all_users - support_team for user in all_users: self.subscribe(user, stream_name) create_user_group( name=group_name, members=list(support_team), realm=realm, ) payload = dict( type="stream", to=stream_name, sender=sender.email, client='test suite', topic='whatever', content=content_with_group_mention, ) with mock.patch('logging.info'): result = self.api_post(sender.email, "/json/messages", payload) self.assert_json_success(result) for user in support_team: um = most_recent_usermessage(user) self.assertTrue(um.flags.mentioned) for user in other_users: um = most_recent_usermessage(user) self.assertFalse(um.flags.mentioned)
[ "str" ]
[ 715 ]
[ 718 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_users.py
# -*- coding: utf-8 -*- from typing import (Any, Dict, Iterable, List, Mapping, Optional, TypeVar, Union) from django.http import HttpResponse from django.test import TestCase from zerver.lib.test_helpers import ( queries_captured, simulated_empty_cache, tornado_redirected_to_list, get_subscription, most_recent_message, make_client, avatar_disk_path, get_test_image_file ) from zerver.lib.test_classes import ( ZulipTestCase, ) from zerver.lib.test_runner import slow from zerver.models import UserProfile, Recipient, \ Realm, RealmDomain, UserActivity, UserHotspot, \ get_user, get_realm, get_client, get_stream, get_stream_recipient, \ get_source_profile, Message, get_context_for_message, \ ScheduledEmail, check_valid_user_ids, \ get_user_by_id_in_realm_including_cross_realm, CustomProfileField from zerver.lib.avatar import avatar_url from zerver.lib.email_mirror import create_missed_message_address from zerver.lib.exceptions import JsonableError from zerver.lib.send_email import send_future_email from zerver.lib.actions import ( get_emails_from_user_ids, get_recipient_info, do_deactivate_user, do_reactivate_user, do_change_is_admin, do_change_is_guest, do_create_user, ) from zerver.lib.create_user import copy_user_settings from zerver.lib.topic_mutes import add_topic_mute from zerver.lib.stream_topic import StreamTopicTarget from zerver.lib.users import user_ids_to_users, access_user_by_id, \ get_accounts_for_email from django.conf import settings import datetime import mock import os import sys import time import ujson K = TypeVar('K') V = TypeVar('V') def find_dict(lst: Iterable[Dict[K, V]], k: K, v: V) -> Dict[K, V]: for dct in lst: if dct[k] == v: return dct raise AssertionError('Cannot find element in list where key %s == %s' % (k, v)) class PermissionTest(ZulipTestCase): def test_do_change_is_admin(self) -> None: """ Ensures change_is_admin raises an AssertionError when invalid permissions are provided to it. """ # this should work fine user_profile = self.example_user('hamlet') do_change_is_admin(user_profile, True) # this should work a-ok as well do_change_is_admin(user_profile, True, permission='administer') # this should "fail" with an AssertionError with self.assertRaises(AssertionError): do_change_is_admin(user_profile, True, permission='totally-not-valid-perm') def test_get_admin_users(self) -> None: user_profile = self.example_user('hamlet') do_change_is_admin(user_profile, False) admin_users = user_profile.realm.get_admin_users() self.assertFalse(user_profile in admin_users) do_change_is_admin(user_profile, True) admin_users = user_profile.realm.get_admin_users() self.assertTrue(user_profile in admin_users) def test_updating_non_existent_user(self) -> None: self.login(self.example_email("hamlet")) admin = self.example_user('hamlet') do_change_is_admin(admin, True) invalid_user_id = 1000 result = self.client_patch('/json/users/{}'.format(invalid_user_id), {}) self.assert_json_error(result, 'No such user') def test_admin_api(self) -> None: self.login(self.example_email("hamlet")) admin = self.example_user('hamlet') user = self.example_user('othello') realm = admin.realm do_change_is_admin(admin, True) # Make sure we see is_admin flag in /json/users result = self.client_get('/json/users') self.assert_json_success(result) members = result.json()['members'] hamlet = find_dict(members, 'email', self.example_email("hamlet")) self.assertTrue(hamlet['is_admin']) othello = find_dict(members, 'email', self.example_email("othello")) self.assertFalse(othello['is_admin']) # Giveth req = dict(is_admin=ujson.dumps(True)) events = [] # type: List[Mapping[str, Any]] with tornado_redirected_to_list(events): result = self.client_patch('/json/users/{}'.format(self.example_user("othello").id), req) self.assert_json_success(result) admin_users = realm.get_admin_users() self.assertTrue(user in admin_users) person = events[0]['event']['person'] self.assertEqual(person['email'], self.example_email("othello")) self.assertEqual(person['is_admin'], True) # Taketh away req = dict(is_admin=ujson.dumps(False)) events = [] with tornado_redirected_to_list(events): result = self.client_patch('/json/users/{}'.format(self.example_user("othello").id), req) self.assert_json_success(result) admin_users = realm.get_admin_users() self.assertFalse(user in admin_users) person = events[0]['event']['person'] self.assertEqual(person['email'], self.example_email("othello")) self.assertEqual(person['is_admin'], False) # Cannot take away from last admin self.login(self.example_email("iago")) req = dict(is_admin=ujson.dumps(False)) events = [] with tornado_redirected_to_list(events): result = self.client_patch('/json/users/{}'.format(self.example_user("hamlet").id), req) self.assert_json_success(result) admin_users = realm.get_admin_users() self.assertFalse(admin in admin_users) person = events[0]['event']['person'] self.assertEqual(person['email'], self.example_email("hamlet")) self.assertEqual(person['is_admin'], False) with tornado_redirected_to_list([]): result = self.client_patch('/json/users/{}'.format(self.example_user("iago").id), req) self.assert_json_error(result, 'Cannot remove the only organization administrator') # Make sure only admins can patch other user's info. self.login(self.example_email("othello")) result = self.client_patch('/json/users/{}'.format(self.example_user("hamlet").id), req) self.assert_json_error(result, 'Insufficient permission') def test_user_cannot_promote_to_admin(self) -> None: self.login(self.example_email("hamlet")) req = dict(is_admin=ujson.dumps(True)) result = self.client_patch('/json/users/{}'.format(self.example_user('hamlet').id), req) self.assert_json_error(result, 'Insufficient permission') def test_admin_user_can_change_full_name(self) -> None: new_name = 'new name' self.login(self.example_email("iago")) hamlet = self.example_user('hamlet') req = dict(full_name=ujson.dumps(new_name)) result = self.client_patch('/json/users/{}'.format(hamlet.id), req) self.assert_json_success(result) hamlet = self.example_user('hamlet') self.assertEqual(hamlet.full_name, new_name) req['is_admin'] = ujson.dumps(False) result = self.client_patch('/json/users/{}'.format(hamlet.id), req) self.assert_json_success(result) def test_non_admin_cannot_change_full_name(self) -> None: self.login(self.example_email("hamlet")) req = dict(full_name=ujson.dumps('new name')) result = self.client_patch('/json/users/{}'.format(self.example_user('othello').id), req) self.assert_json_error(result, 'Insufficient permission') def test_admin_cannot_set_long_full_name(self) -> None: new_name = 'a' * (UserProfile.MAX_NAME_LENGTH + 1) self.login(self.example_email("iago")) req = dict(full_name=ujson.dumps(new_name)) result = self.client_patch('/json/users/{}'.format(self.example_user('hamlet').id), req) self.assert_json_error(result, 'Name too long!') def test_admin_cannot_set_short_full_name(self) -> None: new_name = 'a' self.login(self.example_email("iago")) req = dict(full_name=ujson.dumps(new_name)) result = self.client_patch('/json/users/{}'.format(self.example_user('hamlet').id), req) self.assert_json_error(result, 'Name too short!') def test_admin_cannot_set_full_name_with_invalid_characters(self) -> None: new_name = 'Opheli*' self.login(self.example_email("iago")) req = dict(full_name=ujson.dumps(new_name)) result = self.client_patch('/json/users/{}'.format(self.example_user('hamlet').id), req) self.assert_json_error(result, 'Invalid characters in name!') def test_access_user_by_id(self) -> None: iago = self.example_user("iago") # Must be a valid user ID in the realm with self.assertRaises(JsonableError): access_user_by_id(iago, 1234) with self.assertRaises(JsonableError): access_user_by_id(iago, self.mit_user("sipbtest").id) # Can only access bot users if allow_deactivated is passed bot = self.example_user("welcome_bot") access_user_by_id(iago, bot.id, allow_bots=True) with self.assertRaises(JsonableError): access_user_by_id(iago, bot.id) # Can only access deactivated users if allow_deactivated is passed hamlet = self.example_user("hamlet") do_deactivate_user(hamlet) with self.assertRaises(JsonableError): access_user_by_id(iago, hamlet.id) access_user_by_id(iago, hamlet.id, allow_deactivated=True) # Non-admin user can't admin another user with self.assertRaises(JsonableError): access_user_by_id(self.example_user("cordelia"), self.example_user("aaron").id) def test_change_regular_member_to_guest(self) -> None: iago = self.example_user("iago") self.login(iago.email) hamlet = self.example_user("hamlet") self.assertFalse(hamlet.is_guest) # Test failure of making user both admin and guest req = dict(is_guest=ujson.dumps(True), is_admin=ujson.dumps(True)) result = self.client_patch('/json/users/{}'.format(hamlet.id), req) self.assert_json_error(result, 'Guests cannot be organization administrators') self.assertFalse(hamlet.is_guest) self.assertFalse(hamlet.is_realm_admin) hamlet = self.example_user("hamlet") req = dict(is_guest=ujson.dumps(True)) events = [] # type: List[Mapping[str, Any]] with tornado_redirected_to_list(events): result = self.client_patch('/json/users/{}'.format(hamlet.id), req) self.assert_json_success(result) hamlet = self.example_user("hamlet") self.assertTrue(hamlet.is_guest) person = events[0]['event']['person'] self.assertEqual(person['email'], hamlet.email) self.assertTrue(person['is_guest']) def test_change_guest_to_regular_member(self) -> None: iago = self.example_user("iago") self.login(iago.email) polonius = self.example_user("polonius") self.assertTrue(polonius.is_guest) req = dict(is_guest=ujson.dumps(False)) events = [] # type: List[Mapping[str, Any]] with tornado_redirected_to_list(events): result = self.client_patch('/json/users/{}'.format(polonius.id), req) self.assert_json_success(result) polonius = self.example_user("polonius") self.assertFalse(polonius.is_guest) person = events[0]['event']['person'] self.assertEqual(person['email'], polonius.email) self.assertFalse(person['is_guest']) def test_change_admin_to_guest(self) -> None: iago = self.example_user("iago") self.login(iago.email) hamlet = self.example_user("hamlet") do_change_is_admin(hamlet, True) self.assertFalse(hamlet.is_guest) self.assertTrue(hamlet.is_realm_admin) # Test failure of making a admin to guest without revoking admin status req = dict(is_guest=ujson.dumps(True)) result = self.client_patch('/json/users/{}'.format(hamlet.id), req) self.assert_json_error(result, 'Guests cannot be organization administrators') # Test changing a user from admin to guest and revoking admin status hamlet = self.example_user("hamlet") self.assertFalse(hamlet.is_guest) req = dict(is_admin=ujson.dumps(False), is_guest=ujson.dumps(True)) events = [] # type: List[Mapping[str, Any]] with tornado_redirected_to_list(events): result = self.client_patch('/json/users/{}'.format(hamlet.id), req) self.assert_json_success(result) hamlet = self.example_user("hamlet") self.assertTrue(hamlet.is_guest) self.assertFalse(hamlet.is_realm_admin) person = events[0]['event']['person'] self.assertEqual(person['email'], hamlet.email) self.assertFalse(person['is_admin']) person = events[1]['event']['person'] self.assertEqual(person['email'], hamlet.email) self.assertTrue(person['is_guest']) def test_change_guest_to_admin(self) -> None: iago = self.example_user("iago") self.login(iago.email) polonius = self.example_user("polonius") self.assertTrue(polonius.is_guest) self.assertFalse(polonius.is_realm_admin) # Test failure of making a guest to admin without revoking guest status req = dict(is_admin=ujson.dumps(True)) result = self.client_patch('/json/users/{}'.format(polonius.id), req) self.assert_json_error(result, 'Guests cannot be organization administrators') # Test changing a user from guest to admin and revoking guest status polonius = self.example_user("polonius") self.assertFalse(polonius.is_realm_admin) req = dict(is_admin=ujson.dumps(True), is_guest=ujson.dumps(False)) events = [] # type: List[Mapping[str, Any]] with tornado_redirected_to_list(events): result = self.client_patch('/json/users/{}'.format(polonius.id), req) self.assert_json_success(result) polonius = self.example_user("polonius") self.assertFalse(polonius.is_guest) self.assertTrue(polonius.is_realm_admin) person = events[0]['event']['person'] self.assertEqual(person['email'], polonius.email) self.assertTrue(person['is_admin']) person = events[1]['event']['person'] self.assertEqual(person['email'], polonius.email) self.assertFalse(person['is_guest']) def test_admin_user_can_change_profile_data(self) -> None: realm = get_realm('zulip') self.login(self.example_email("iago")) new_profile_data = [] cordelia = self.example_user("cordelia") # Test for all type of data fields = { 'Phone number': 'short text data', 'Biography': 'long text data', 'Favorite food': 'short text data', 'Favorite editor': 'vim', 'Birthday': '1909-3-5', 'GitHub profile': 'https://github.com/ABC', 'Mentor': [cordelia.id], } for field_name in fields: field = CustomProfileField.objects.get(name=field_name, realm=realm) new_profile_data.append({ 'id': field.id, 'value': fields[field_name], }) result = self.client_patch('/json/users/{}'.format(cordelia.id), {'profile_data': ujson.dumps(new_profile_data)}) self.assert_json_success(result) cordelia = self.example_user("cordelia") for field_dict in cordelia.profile_data: self.assertEqual(field_dict['value'], fields[field_dict['name']]) # type: ignore # Reason in comment # Invalid index type for dict key, it must be str but field_dict values can be anything # Test admin user cannot set invalid profile data invalid_fields = [ ('Favorite editor', 'invalid choice', "'invalid choice' is not a valid choice for 'Favorite editor'."), ('Birthday', '1909-34-55', "Birthday is not a date"), ('GitHub profile', 'not url', "GitHub profile is not a URL"), ('Mentor', "not list of user ids", "User IDs is not a list"), ] for field_name, field_value, error_msg in invalid_fields: new_profile_data = [] field = CustomProfileField.objects.get(name=field_name, realm=realm) new_profile_data.append({ 'id': field.id, 'value': field_value, }) result = self.client_patch('/json/users/{}'.format(cordelia.id), {'profile_data': ujson.dumps(new_profile_data)}) self.assert_json_error(result, error_msg) def test_non_admin_user_cannot_change_profile_data(self) -> None: self.login(self.example_email("cordelia")) hamlet = self.example_user("hamlet") realm = get_realm("zulip") new_profile_data = [] field = CustomProfileField.objects.get(name="Biography", realm=realm) new_profile_data.append({ 'id': field.id, 'value': "New hamlet Biography", }) result = self.client_patch('/json/users/{}'.format(hamlet.id), {'profile_data': ujson.dumps(new_profile_data)}) self.assert_json_error(result, 'Insufficient permission') result = self.client_patch('/json/users/{}'.format(self.example_user("cordelia").id), {'profile_data': ujson.dumps(new_profile_data)}) self.assert_json_error(result, 'Insufficient permission') class AdminCreateUserTest(ZulipTestCase): def test_create_user_backend(self) -> None: # This test should give us complete coverage on # create_user_backend. It mostly exercises error # conditions, and it also does a basic test of the success # path. admin = self.example_user('hamlet') admin_email = admin.email realm = admin.realm self.login(admin_email) do_change_is_admin(admin, True) result = self.client_post("/json/users", dict()) self.assert_json_error(result, "Missing 'email' argument") result = self.client_post("/json/users", dict( email='romeo@not-zulip.com', )) self.assert_json_error(result, "Missing 'password' argument") result = self.client_post("/json/users", dict( email='romeo@not-zulip.com', password='xxxx', )) self.assert_json_error(result, "Missing 'full_name' argument") result = self.client_post("/json/users", dict( email='romeo@not-zulip.com', password='xxxx', full_name='Romeo Montague', )) self.assert_json_error(result, "Missing 'short_name' argument") result = self.client_post("/json/users", dict( email='broken', password='xxxx', full_name='Romeo Montague', short_name='Romeo', )) self.assert_json_error(result, "Bad name or username") result = self.client_post("/json/users", dict( email='romeo@not-zulip.com', password='xxxx', full_name='Romeo Montague', short_name='Romeo', )) self.assert_json_error(result, "Email 'romeo@not-zulip.com' not allowed in this organization") RealmDomain.objects.create(realm=get_realm('zulip'), domain='zulip.net') valid_params = dict( email='romeo@zulip.net', password='xxxx', full_name='Romeo Montague', short_name='Romeo', ) result = self.client_post("/json/users", valid_params) self.assert_json_success(result) # Romeo is a newly registered user new_user = get_user('romeo@zulip.net', get_realm('zulip')) self.assertEqual(new_user.full_name, 'Romeo Montague') self.assertEqual(new_user.short_name, 'Romeo') # we can't create the same user twice. result = self.client_post("/json/users", valid_params) self.assert_json_error(result, "Email 'romeo@zulip.net' already in use") # Don't allow user to sign up with disposable email. realm.emails_restricted_to_domains = False realm.disallow_disposable_email_addresses = True realm.save() valid_params["email"] = "abc@mailnator.com" result = self.client_post("/json/users", valid_params) self.assert_json_error(result, "Disposable email addresses are not allowed in this organization") # Don't allow creating a user with + in their email address when realm # is restricted to a domain. realm.emails_restricted_to_domains = True realm.save() valid_params["email"] = "iago+label@zulip.com" result = self.client_post("/json/users", valid_params) self.assert_json_error(result, "Email addresses containing + are not allowed.") # Users can be created with + in their email address when realm # is not restricted to a domain. realm.emails_restricted_to_domains = False realm.save() valid_params["email"] = "iago+label@zulip.com" result = self.client_post("/json/users", valid_params) self.assert_json_success(result) class UserProfileTest(ZulipTestCase): def test_get_emails_from_user_ids(self) -> None: hamlet = self.example_user('hamlet') othello = self.example_user('othello') dct = get_emails_from_user_ids([hamlet.id, othello.id]) self.assertEqual(dct[hamlet.id], self.example_email("hamlet")) self.assertEqual(dct[othello.id], self.example_email("othello")) def test_valid_user_id(self) -> None: realm = get_realm("zulip") hamlet = self.example_user('hamlet') othello = self.example_user('othello') bot = self.example_user("welcome_bot") # Invalid user ID invalid_uid = 1000 # type: Any self.assertEqual(check_valid_user_ids(realm.id, invalid_uid), "User IDs is not a list") self.assertEqual(check_valid_user_ids(realm.id, [invalid_uid]), "Invalid user ID: %d" % (invalid_uid)) invalid_uid = "abc" self.assertEqual(check_valid_user_ids(realm.id, [invalid_uid]), "User IDs[0] is not an integer") invalid_uid = str(othello.id) self.assertEqual(check_valid_user_ids(realm.id, [invalid_uid]), "User IDs[0] is not an integer") # User is in different realm self.assertEqual(check_valid_user_ids(get_realm("zephyr").id, [hamlet.id]), "Invalid user ID: %d" % (hamlet.id)) # User is not active hamlet.is_active = False hamlet.save() self.assertEqual(check_valid_user_ids(realm.id, [hamlet.id]), "User with ID %d is deactivated" % (hamlet.id)) self.assertEqual(check_valid_user_ids(realm.id, [hamlet.id], allow_deactivated=True), None) # User is a bot self.assertEqual(check_valid_user_ids(realm.id, [bot.id]), "User with ID %d is a bot" % (bot.id)) # Succesfully get non-bot, active user belong to your realm self.assertEqual(check_valid_user_ids(realm.id, [othello.id]), None) def test_cache_invalidation(self) -> None: hamlet = self.example_user('hamlet') with mock.patch('zerver.lib.cache.delete_display_recipient_cache') as m: hamlet.full_name = 'Hamlet Junior' hamlet.save(update_fields=["full_name"]) self.assertTrue(m.called) with mock.patch('zerver.lib.cache.delete_display_recipient_cache') as m: hamlet.long_term_idle = True hamlet.save(update_fields=["long_term_idle"]) self.assertFalse(m.called) def test_user_ids_to_users(self) -> None: real_user_ids = [ self.example_user('hamlet').id, self.example_user('cordelia').id, ] self.assertEqual(user_ids_to_users([], get_realm("zulip")), []) self.assertEqual(set([user_profile.id for user_profile in user_ids_to_users(real_user_ids, get_realm("zulip"))]), set(real_user_ids)) with self.assertRaises(JsonableError): user_ids_to_users([1234], get_realm("zephyr")) with self.assertRaises(JsonableError): user_ids_to_users(real_user_ids, get_realm("zephyr")) def test_bulk_get_users(self) -> None: from zerver.lib.users import bulk_get_users hamlet = self.example_email("hamlet") cordelia = self.example_email("cordelia") webhook_bot = self.example_email("webhook_bot") result = bulk_get_users([hamlet, cordelia], get_realm("zulip")) self.assertEqual(result[hamlet].email, hamlet) self.assertEqual(result[cordelia].email, cordelia) result = bulk_get_users([hamlet, cordelia, webhook_bot], None, base_query=UserProfile.objects.all()) self.assertEqual(result[hamlet].email, hamlet) self.assertEqual(result[cordelia].email, cordelia) self.assertEqual(result[webhook_bot].email, webhook_bot) def test_get_accounts_for_email(self) -> None: def check_account_present_in_accounts(user: UserProfile, accounts: List[Dict[str, Optional[str]]]) -> None: for account in accounts: realm = user.realm if account["avatar"] == avatar_url(user) and account["full_name"] == user.full_name \ and account["realm_name"] == realm.name and account["string_id"] == realm.string_id: return raise AssertionError("Account not found") lear_realm = get_realm("lear") cordelia_in_zulip = self.example_user("cordelia") cordelia_in_lear = get_user("cordelia@zulip.com", lear_realm) email = "cordelia@zulip.com" accounts = get_accounts_for_email(email) self.assert_length(accounts, 2) check_account_present_in_accounts(cordelia_in_zulip, accounts) check_account_present_in_accounts(cordelia_in_lear, accounts) email = "CORDelia@zulip.com" accounts = get_accounts_for_email(email) self.assert_length(accounts, 2) check_account_present_in_accounts(cordelia_in_zulip, accounts) check_account_present_in_accounts(cordelia_in_lear, accounts) email = "IAGO@ZULIP.COM" accounts = get_accounts_for_email(email) self.assert_length(accounts, 1) check_account_present_in_accounts(self.example_user("iago"), accounts) def test_get_source_profile(self) -> None: iago = get_source_profile("iago@zulip.com", "zulip") assert iago is not None self.assertEqual(iago.email, "iago@zulip.com") self.assertEqual(iago.realm, get_realm("zulip")) iago = get_source_profile("IAGO@ZULIP.com", "zulip") assert iago is not None self.assertEqual(iago.email, "iago@zulip.com") cordelia = get_source_profile("cordelia@zulip.com", "lear") assert cordelia is not None self.assertEqual(cordelia.email, "cordelia@zulip.com") self.assertIsNone(get_source_profile("iagod@zulip.com", "zulip")) self.assertIsNone(get_source_profile("iago@zulip.com", "ZULIP")) self.assertIsNone(get_source_profile("iago@zulip.com", "lear")) def test_copy_user_settings(self) -> None: iago = self.example_user("iago") cordelia = self.example_user("cordelia") hamlet = self.example_user("hamlet") cordelia.default_language = "de" cordelia.emojiset = "apple" cordelia.timezone = "America/Phoenix" cordelia.night_mode = True cordelia.enable_offline_email_notifications = False cordelia.enable_stream_push_notifications = True cordelia.enter_sends = False cordelia.save() UserHotspot.objects.filter(user=cordelia).delete() UserHotspot.objects.filter(user=iago).delete() hotspots_completed = ['intro_reply', 'intro_streams', 'intro_topics'] for hotspot in hotspots_completed: UserHotspot.objects.create(user=cordelia, hotspot=hotspot) copy_user_settings(cordelia, iago) # We verify that cordelia and iago match, but hamlet has the defaults. self.assertEqual(iago.full_name, "Cordelia Lear") self.assertEqual(cordelia.full_name, "Cordelia Lear") self.assertEqual(hamlet.full_name, "King Hamlet") self.assertEqual(iago.default_language, "de") self.assertEqual(cordelia.default_language, "de") self.assertEqual(hamlet.default_language, "en") self.assertEqual(iago.emojiset, "apple") self.assertEqual(cordelia.emojiset, "apple") self.assertEqual(hamlet.emojiset, "google-blob") self.assertEqual(iago.timezone, "America/Phoenix") self.assertEqual(cordelia.timezone, "America/Phoenix") self.assertEqual(hamlet.timezone, "") self.assertEqual(iago.night_mode, True) self.assertEqual(cordelia.night_mode, True) self.assertEqual(hamlet.night_mode, False) self.assertEqual(iago.enable_offline_email_notifications, False) self.assertEqual(cordelia.enable_offline_email_notifications, False) self.assertEqual(hamlet.enable_offline_email_notifications, True) self.assertEqual(iago.enable_stream_push_notifications, True) self.assertEqual(cordelia.enable_stream_push_notifications, True) self.assertEqual(hamlet.enable_stream_push_notifications, False) self.assertEqual(iago.enter_sends, False) self.assertEqual(cordelia.enter_sends, False) self.assertEqual(hamlet.enter_sends, True) hotspots = list(UserHotspot.objects.filter(user=iago).values_list('hotspot', flat=True)) self.assertEqual(hotspots, hotspots_completed) def test_get_user_by_id_in_realm_including_cross_realm(self) -> None: realm = get_realm('zulip') hamlet = self.example_user('hamlet') othello = self.example_user('othello') bot = self.example_user('welcome_bot') # Pass in the ID of a cross-realm bot and a valid realm cross_realm_bot = get_user_by_id_in_realm_including_cross_realm( bot.id, realm) self.assertEqual(cross_realm_bot.email, bot.email) self.assertEqual(cross_realm_bot.id, bot.id) # Pass in the ID of a cross-realm bot but with a invalid realm, # note that the realm should be irrelevant here cross_realm_bot = get_user_by_id_in_realm_including_cross_realm( bot.id, get_realm('invalid')) self.assertEqual(cross_realm_bot.email, bot.email) self.assertEqual(cross_realm_bot.id, bot.id) # Pass in the ID of a non-cross-realm user with a realm user_profile = get_user_by_id_in_realm_including_cross_realm( othello.id, realm) self.assertEqual(user_profile.email, othello.email) self.assertEqual(user_profile.id, othello.id) # If the realm doesn't match, or if the ID is not that of a # cross-realm bot, UserProfile.DoesNotExist is raised with self.assertRaises(UserProfile.DoesNotExist): get_user_by_id_in_realm_including_cross_realm( hamlet.id, get_realm('invalid')) class ActivateTest(ZulipTestCase): def test_basics(self) -> None: user = self.example_user('hamlet') do_deactivate_user(user) self.assertFalse(user.is_active) do_reactivate_user(user) self.assertTrue(user.is_active) def test_api(self) -> None: admin = self.example_user('othello') do_change_is_admin(admin, True) self.login(self.example_email("othello")) user = self.example_user('hamlet') self.assertTrue(user.is_active) result = self.client_delete('/json/users/{}'.format(user.id)) self.assert_json_success(result) user = self.example_user('hamlet') self.assertFalse(user.is_active) result = self.client_post('/json/users/{}/reactivate'.format(user.id)) self.assert_json_success(result) user = self.example_user('hamlet') self.assertTrue(user.is_active) def test_api_with_nonexistent_user(self) -> None: admin = self.example_user('othello') do_change_is_admin(admin, True) self.login(self.example_email("othello")) # Cannot deactivate a user with the bot api result = self.client_delete('/json/bots/{}'.format(self.example_user("hamlet").id)) self.assert_json_error(result, 'No such bot') # Cannot deactivate a nonexistent user. invalid_user_id = 1000 result = self.client_delete('/json/users/{}'.format(invalid_user_id)) self.assert_json_error(result, 'No such user') result = self.client_delete('/json/users/{}'.format(self.example_user("webhook_bot").id)) self.assert_json_error(result, 'No such user') result = self.client_delete('/json/users/{}'.format(self.example_user("iago").id)) self.assert_json_success(result) result = self.client_delete('/json/users/{}'.format(admin.id)) self.assert_json_error(result, 'Cannot deactivate the only organization administrator') # Cannot reactivate a nonexistent user. invalid_user_id = 1000 result = self.client_post('/json/users/{}/reactivate'.format(invalid_user_id)) self.assert_json_error(result, 'No such user') def test_api_with_insufficient_permissions(self) -> None: non_admin = self.example_user('othello') do_change_is_admin(non_admin, False) self.login(self.example_email("othello")) # Cannot deactivate a user with the users api result = self.client_delete('/json/users/{}'.format(self.example_user("hamlet").id)) self.assert_json_error(result, 'Insufficient permission') # Cannot reactivate a user result = self.client_post('/json/users/{}/reactivate'.format(self.example_user("hamlet").id)) self.assert_json_error(result, 'Insufficient permission') def test_clear_scheduled_jobs(self) -> None: user = self.example_user('hamlet') send_future_email('zerver/emails/followup_day1', user.realm, to_user_id=user.id, delay=datetime.timedelta(hours=1)) self.assertEqual(ScheduledEmail.objects.count(), 1) do_deactivate_user(user) self.assertEqual(ScheduledEmail.objects.count(), 0) class RecipientInfoTest(ZulipTestCase): def test_stream_recipient_info(self) -> None: hamlet = self.example_user('hamlet') cordelia = self.example_user('cordelia') othello = self.example_user('othello') realm = hamlet.realm stream_name = 'Test Stream' topic_name = 'test topic' for user in [hamlet, cordelia, othello]: self.subscribe(user, stream_name) stream = get_stream(stream_name, realm) recipient = get_stream_recipient(stream.id) stream_topic = StreamTopicTarget( stream_id=stream.id, topic_name=topic_name, ) sub = get_subscription(stream_name, hamlet) sub.push_notifications = True sub.save() info = get_recipient_info( recipient=recipient, sender_id=hamlet.id, stream_topic=stream_topic, ) all_user_ids = {hamlet.id, cordelia.id, othello.id} expected_info = dict( active_user_ids=all_user_ids, push_notify_user_ids=set(), stream_push_user_ids={hamlet.id}, stream_email_user_ids=set(), um_eligible_user_ids=all_user_ids, long_term_idle_user_ids=set(), default_bot_user_ids=set(), service_bot_tuples=[], ) self.assertEqual(info, expected_info) # Now mute Hamlet to omit him from stream_push_user_ids. add_topic_mute( user_profile=hamlet, stream_id=stream.id, recipient_id=recipient.id, topic_name=topic_name, ) info = get_recipient_info( recipient=recipient, sender_id=hamlet.id, stream_topic=stream_topic, ) self.assertEqual(info['stream_push_user_ids'], set()) # Add a service bot. service_bot = do_create_user( email='service-bot@zulip.com', password='', realm=realm, full_name='', short_name='', bot_type=UserProfile.EMBEDDED_BOT, ) info = get_recipient_info( recipient=recipient, sender_id=hamlet.id, stream_topic=stream_topic, possibly_mentioned_user_ids={service_bot.id} ) self.assertEqual(info['service_bot_tuples'], [ (service_bot.id, UserProfile.EMBEDDED_BOT), ]) # Add a normal bot. normal_bot = do_create_user( email='normal-bot@zulip.com', password='', realm=realm, full_name='', short_name='', bot_type=UserProfile.DEFAULT_BOT, ) info = get_recipient_info( recipient=recipient, sender_id=hamlet.id, stream_topic=stream_topic, possibly_mentioned_user_ids={service_bot.id, normal_bot.id} ) self.assertEqual(info['default_bot_user_ids'], {normal_bot.id}) def test_get_recipient_info_invalid_recipient_type(self) -> None: hamlet = self.example_user('hamlet') realm = hamlet.realm stream = get_stream('Rome', realm) stream_topic = StreamTopicTarget( stream_id=stream.id, topic_name='test topic', ) # Make sure get_recipient_info asserts on invalid recipient types with self.assertRaisesRegex(ValueError, 'Bad recipient type'): invalid_recipient = Recipient(type=999) # 999 is not a valid type get_recipient_info( recipient=invalid_recipient, sender_id=hamlet.id, stream_topic=stream_topic, ) class BulkUsersTest(ZulipTestCase): def test_client_gravatar_option(self) -> None: self.login(self.example_email('cordelia')) hamlet = self.example_user('hamlet') def get_hamlet_avatar(client_gravatar: bool) -> Optional[str]: data = dict(client_gravatar=ujson.dumps(client_gravatar)) result = self.client_get('/json/users', data) self.assert_json_success(result) rows = result.json()['members'] hamlet_data = [ row for row in rows if row['user_id'] == hamlet.id ][0] return hamlet_data['avatar_url'] self.assertEqual( get_hamlet_avatar(client_gravatar=True), None ) ''' The main purpose of this test is to make sure we return None for avatar_url when client_gravatar is set to True. And we do a sanity check for when it's False, but we leave it to other tests to validate the specific URL. ''' self.assertIn( 'gravatar.com', get_hamlet_avatar(client_gravatar=False), ) class GetProfileTest(ZulipTestCase): def common_update_pointer(self, email: str, pointer: int) -> None: self.login(email) result = self.client_post("/json/users/me/pointer", {"pointer": pointer}) self.assert_json_success(result) def common_get_profile(self, user_id: str) -> Dict[str, Any]: # Assumes all users are example users in realm 'zulip' user_profile = self.example_user(user_id) self.send_stream_message(user_profile.email, "Verona", "hello") result = self.api_get(user_profile.email, "/api/v1/users/me") max_id = most_recent_message(user_profile).id self.assert_json_success(result) json = result.json() self.assertIn("client_id", json) self.assertIn("max_message_id", json) self.assertIn("pointer", json) self.assertEqual(json["max_message_id"], max_id) return json def test_get_pointer(self) -> None: email = self.example_email("hamlet") self.login(email) result = self.client_get("/json/users/me/pointer") self.assert_json_success(result) self.assertIn("pointer", result.json()) def test_cache_behavior(self) -> None: """Tests whether fetching a user object the normal way, with `get_user`, makes 1 cache query and 1 database query. """ realm = get_realm("zulip") email = self.example_email("hamlet") with queries_captured() as queries: with simulated_empty_cache() as cache_queries: user_profile = get_user(email, realm) self.assert_length(queries, 1) self.assert_length(cache_queries, 1) self.assertEqual(user_profile.email, email) def test_get_user_profile(self) -> None: self.login(self.example_email("hamlet")) result = ujson.loads(self.client_get('/json/users/me').content) self.assertEqual(result['short_name'], 'hamlet') self.assertEqual(result['email'], self.example_email("hamlet")) self.assertEqual(result['full_name'], 'King Hamlet') self.assertIn("user_id", result) self.assertFalse(result['is_bot']) self.assertFalse(result['is_admin']) self.login(self.example_email("iago")) result = ujson.loads(self.client_get('/json/users/me').content) self.assertEqual(result['short_name'], 'iago') self.assertEqual(result['email'], self.example_email("iago")) self.assertEqual(result['full_name'], 'Iago') self.assertFalse(result['is_bot']) self.assertTrue(result['is_admin']) def test_api_get_empty_profile(self) -> None: """ Ensure GET /users/me returns a max message id and returns successfully """ json = self.common_get_profile("othello") self.assertEqual(json["pointer"], -1) def test_profile_with_pointer(self) -> None: """ Ensure GET /users/me returns a proper pointer id after the pointer is updated """ id1 = self.send_stream_message(self.example_email("othello"), "Verona") id2 = self.send_stream_message(self.example_email("othello"), "Verona") json = self.common_get_profile("hamlet") self.common_update_pointer(self.example_email("hamlet"), id2) json = self.common_get_profile("hamlet") self.assertEqual(json["pointer"], id2) self.common_update_pointer(self.example_email("hamlet"), id1) json = self.common_get_profile("hamlet") self.assertEqual(json["pointer"], id2) # pointer does not move backwards result = self.client_post("/json/users/me/pointer", {"pointer": 99999999}) self.assert_json_error(result, "Invalid message ID") def test_get_all_profiles_avatar_urls(self) -> None: user_profile = self.example_user('hamlet') result = self.api_get(self.example_email("hamlet"), "/api/v1/users") self.assert_json_success(result) for user in result.json()['members']: if user['email'] == self.example_email("hamlet"): self.assertEqual( user['avatar_url'], avatar_url(user_profile), )
[ "Iterable[Dict[K, V]]", "K", "V", "UserProfile", "List[Dict[str, Optional[str]]]", "bool", "str", "int", "str" ]
[ 1696, 1721, 1727, 25666, 25689, 38945, 39949, 39963, 40169 ]
[ 1716, 1722, 1728, 25677, 25719, 38949, 39952, 39966, 40172 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_webhooks_common.py
# -*- coding: utf-8 -*- from django.http import HttpRequest from zerver.decorator import api_key_only_webhook_view from zerver.lib.exceptions import InvalidJSONError, JsonableError from zerver.lib.test_classes import ZulipTestCase, WebhookTestCase from zerver.lib.webhooks.common import \ validate_extract_webhook_http_header, \ MISSING_EVENT_HEADER_MESSAGE, MissingHTTPEventHeader, \ INVALID_JSON_MESSAGE from zerver.models import get_user, get_realm, UserProfile from zerver.lib.users import get_api_key from zerver.lib.send_email import FromAddress from zerver.lib.test_helpers import HostRequestMock class WebhooksCommonTestCase(ZulipTestCase): def test_webhook_http_header_header_exists(self) -> None: webhook_bot = get_user('webhook-bot@zulip.com', get_realm('zulip')) request = HostRequestMock() request.META['HTTP_X_CUSTOM_HEADER'] = 'custom_value' request.user = webhook_bot header_value = validate_extract_webhook_http_header(request, 'X_CUSTOM_HEADER', 'test_webhook') self.assertEqual(header_value, 'custom_value') def test_webhook_http_header_header_does_not_exist(self) -> None: webhook_bot = get_user('webhook-bot@zulip.com', get_realm('zulip')) webhook_bot.last_reminder = None notification_bot = self.notification_bot() request = HostRequestMock() request.user = webhook_bot request.path = 'some/random/path' exception_msg = "Missing the HTTP event header 'X_CUSTOM_HEADER'" with self.assertRaisesRegex(MissingHTTPEventHeader, exception_msg): validate_extract_webhook_http_header(request, 'X_CUSTOM_HEADER', 'test_webhook') msg = self.get_last_message() expected_message = MISSING_EVENT_HEADER_MESSAGE.format( bot_name=webhook_bot.full_name, request_path=request.path, header_name='X_CUSTOM_HEADER', integration_name='test_webhook', support_email=FromAddress.SUPPORT ).rstrip() self.assertEqual(msg.sender.email, notification_bot.email) self.assertEqual(msg.content, expected_message) def test_notify_bot_owner_on_invalid_json(self)-> None: @api_key_only_webhook_view('ClientName', notify_bot_owner_on_invalid_json=False) def my_webhook_raises_exception(request: HttpRequest, user_profile: UserProfile) -> None: raise InvalidJSONError("Malformed JSON") @api_key_only_webhook_view('ClientName', notify_bot_owner_on_invalid_json=True) def my_webhook(request: HttpRequest, user_profile: UserProfile) -> None: raise InvalidJSONError("Malformed JSON") webhook_bot_email = 'webhook-bot@zulip.com' webhook_bot_realm = get_realm('zulip') webhook_bot = get_user(webhook_bot_email, webhook_bot_realm) webhook_bot_api_key = get_api_key(webhook_bot) request = HostRequestMock() request.POST['api_key'] = webhook_bot_api_key request.host = "zulip.testserver" expected_msg = INVALID_JSON_MESSAGE.format(webhook_name='ClientName') last_message_id = self.get_last_message().id with self.assertRaisesRegex(JsonableError, "Malformed JSON"): my_webhook_raises_exception(request) # type: ignore # mypy doesn't seem to apply the decorator # First verify that without the setting, it doesn't send a PM to bot owner. msg = self.get_last_message() self.assertEqual(msg.id, last_message_id) self.assertNotEqual(msg.content, expected_msg.strip()) # Then verify that with the setting, it does send such a message. my_webhook(request) # type: ignore # mypy doesn't seem to apply the decorator msg = self.get_last_message() self.assertNotEqual(msg.id, last_message_id) self.assertEqual(msg.sender.email, self.notification_bot().email) self.assertEqual(msg.content, expected_msg.strip()) class MissingEventHeaderTestCase(WebhookTestCase): STREAM_NAME = 'groove' URL_TEMPLATE = '/api/v1/external/groove?stream={stream}&api_key={api_key}' # This tests the validate_extract_webhook_http_header function with # an actual webhook, instead of just making a mock def test_missing_event_header(self) -> None: self.subscribe(self.test_user, self.STREAM_NAME) result = self.client_post(self.url, self.get_body('ticket_state_changed'), content_type="application/x-www-form-urlencoded") self.assert_json_error(result, "Missing the HTTP event header 'X_GROOVE_EVENT'") webhook_bot = get_user('webhook-bot@zulip.com', get_realm('zulip')) webhook_bot.last_reminder = None notification_bot = self.notification_bot() msg = self.get_last_message() expected_message = MISSING_EVENT_HEADER_MESSAGE.format( bot_name=webhook_bot.full_name, request_path='/api/v1/external/groove', header_name='X_GROOVE_EVENT', integration_name='Groove', support_email=FromAddress.SUPPORT ).rstrip() if msg.sender.email != notification_bot.email: # nocoverage # This block seems to fire occasionally; debug output: print(msg) print(msg.content) self.assertEqual(msg.sender.email, notification_bot.email) self.assertEqual(msg.content, expected_message) def get_body(self, fixture_name: str) -> str: return self.webhook_fixture_data("groove", fixture_name, file_type="json")
[ "HttpRequest", "UserProfile", "HttpRequest", "UserProfile", "str" ]
[ 2462, 2489, 2685, 2712, 5588 ]
[ 2473, 2500, 2696, 2723, 5591 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_widgets.py
import ujson from typing import Dict, Any from zerver.models import SubMessage from zerver.lib.test_classes import ZulipTestCase from zerver.lib.widget import get_widget_data from zerver.lib.validator import check_widget_content class WidgetContentTestCase(ZulipTestCase): def test_validation(self) -> None: def assert_error(obj: object, msg: str) -> None: self.assertEqual(check_widget_content(obj), msg) assert_error(5, 'widget_content is not a dict') assert_error({}, 'widget_type is not in widget_content') assert_error(dict(widget_type='whatever'), 'extra_data is not in widget_content') assert_error(dict(widget_type='zform', extra_data=4), 'extra_data is not a dict') assert_error(dict(widget_type='bogus', extra_data={}), 'unknown widget type: bogus') extra_data = dict() # type: Dict[str, Any] obj = dict(widget_type='zform', extra_data=extra_data) assert_error(obj, 'zform is missing type field') extra_data['type'] = 'bogus' assert_error(obj, 'unknown zform type: bogus') extra_data['type'] = 'choices' assert_error(obj, 'heading key is missing from extra_data') extra_data['heading'] = 'whatever' assert_error(obj, 'choices key is missing from extra_data') extra_data['choices'] = 99 assert_error(obj, 'extra_data["choices"] is not a list') extra_data['choices'] = [99] assert_error(obj, 'extra_data["choices"][0] is not a dict') extra_data['choices'] = [ dict(long_name='foo', reply='bar'), ] assert_error(obj, 'short_name key is missing from extra_data["choices"][0]') extra_data['choices'] = [ dict(short_name='a', long_name='foo', reply='bar'), ] self.assertEqual(check_widget_content(obj), None) def test_message_error_handling(self) -> None: sender_email = self.example_email('cordelia') stream_name = 'Verona' payload = dict( type="stream", to=stream_name, sender=sender_email, client='test suite', topic='whatever', content='whatever', ) payload['widget_content'] = '{{{{{{' # unparsable result = self.api_post(sender_email, "/api/v1/messages", payload) self.assert_json_error_contains(result, 'Widgets: API programmer sent invalid JSON') bogus_data = dict(color='red', foo='bar', x=2) payload['widget_content'] = ujson.dumps(bogus_data) result = self.api_post(sender_email, "/api/v1/messages", payload) self.assert_json_error_contains(result, 'Widgets: widget_type is not in widget_content') def test_get_widget_data_for_non_widget_messages(self) -> None: # This is a pretty important test, despite testing the # "negative" case. We never want widgets to interfere # with normal messages. test_messages = [ '', ' ', 'this is an ordinary message', '/bogus_command', '/me shrugs', 'use /poll', ] for message in test_messages: self.assertEqual(get_widget_data(content=message), (None, None)) # Add a positive check for context self.assertEqual(get_widget_data(content='/tictactoe'), ('tictactoe', None)) def test_explicit_widget_content(self) -> None: # Users can send widget_content directly on messages # using the `widget_content` field. sender_email = self.example_email('cordelia') stream_name = 'Verona' content = 'does-not-matter' zform_data = dict( type='choices', heading='Options:', choices=[], ) widget_content = ujson.dumps( dict( widget_type='zform', extra_data=zform_data, ), ) payload = dict( type="stream", to=stream_name, sender=sender_email, client='test suite', topic='whatever', content=content, widget_content=widget_content, ) result = self.api_post(sender_email, "/api/v1/messages", payload) self.assert_json_success(result) message = self.get_last_message() self.assertEqual(message.content, content) expected_submessage_content = dict( widget_type="zform", extra_data=zform_data, ) submessage = SubMessage.objects.get(message_id=message.id) self.assertEqual(submessage.msg_type, 'widget') self.assertEqual(ujson.loads(submessage.content), expected_submessage_content) def test_tictactoe(self) -> None: # The tictactoe widget is mostly useful as a code sample, # and it also helps us get test coverage that could apply # to future widgets. sender_email = self.example_email('cordelia') stream_name = 'Verona' content = '/tictactoe' payload = dict( type="stream", to=stream_name, sender=sender_email, client='test suite', topic='whatever', content=content, ) result = self.api_post(sender_email, "/api/v1/messages", payload) self.assert_json_success(result) message = self.get_last_message() self.assertEqual(message.content, content) expected_submessage_content = dict( widget_type="tictactoe", extra_data=None, ) submessage = SubMessage.objects.get(message_id=message.id) self.assertEqual(submessage.msg_type, 'widget') self.assertEqual(ujson.loads(submessage.content), expected_submessage_content) def test_poll_command_extra_data(self) -> None: sender_email = self.example_email('cordelia') stream_name = 'Verona' content = '/poll What is your favorite color?' payload = dict( type="stream", to=stream_name, sender=sender_email, client='test suite', topic='whatever', content=content, ) result = self.api_post(sender_email, "/api/v1/messages", payload) self.assert_json_success(result) message = self.get_last_message() self.assertEqual(message.content, content) expected_submessage_content = dict( widget_type="poll", extra_data=dict( question="What is your favorite color?", ), ) submessage = SubMessage.objects.get(message_id=message.id) self.assertEqual(submessage.msg_type, 'widget') self.assertEqual(ujson.loads(submessage.content), expected_submessage_content) # Now don't supply a question. content = '/poll' payload['content'] = content result = self.api_post(sender_email, "/api/v1/messages", payload) self.assert_json_success(result) expected_submessage_content = dict( widget_type="poll", extra_data=dict( question="", ), ) message = self.get_last_message() self.assertEqual(message.content, content) submessage = SubMessage.objects.get(message_id=message.id) self.assertEqual(submessage.msg_type, 'widget') self.assertEqual(ujson.loads(submessage.content), expected_submessage_content) # Now test the feature flag. with self.settings(ALLOW_SUB_MESSAGES=False): result = self.api_post(sender_email, "/api/v1/messages", payload) self.assert_json_success(result) message = self.get_last_message() self.assertEqual(message.content, content) self.assertFalse(SubMessage.objects.filter(message_id=message.id).exists())
[ "object", "str" ]
[ 348, 361 ]
[ 354, 364 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_zcommand.py
# -*- coding: utf-8 -*- from zerver.lib.test_classes import ( ZulipTestCase, ) class ZcommandTest(ZulipTestCase): def test_invalid_zcommand(self) -> None: self.login(self.example_email("hamlet")) payload = dict(command="/boil-ocean") result = self.client_post("/json/zcommand", payload) self.assert_json_error(result, "No such command: boil-ocean") payload = dict(command="boil-ocean") result = self.client_post("/json/zcommand", payload) self.assert_json_error(result, "There should be a leading slash in the zcommand.") def test_ping_zcommand(self) -> None: self.login(self.example_email("hamlet")) payload = dict(command="/ping") result = self.client_post("/json/zcommand", payload) self.assert_json_success(result) def test_night_zcommand(self) -> None: self.login(self.example_email("hamlet")) user = self.example_user('hamlet') user.night_mode = False user.save() payload = dict(command="/night") result = self.client_post("/json/zcommand", payload) self.assert_json_success(result) self.assertIn('Changed to night', result.json()['msg']) result = self.client_post("/json/zcommand", payload) self.assert_json_success(result) self.assertIn('still in night mode', result.json()['msg']) def test_day_zcommand(self) -> None: self.login(self.example_email("hamlet")) user = self.example_user('hamlet') user.night_mode = True user.save() payload = dict(command="/day") result = self.client_post("/json/zcommand", payload) self.assert_json_success(result) self.assertIn('Changed to day', result.json()['msg']) result = self.client_post("/json/zcommand", payload) self.assert_json_success(result) self.assertIn('still in day mode', result.json()['msg'])
[]
[]
[]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/test_zephyr.py
import ujson from django.http import HttpResponse from mock import patch from typing import Any, Dict from zerver.lib.test_classes import ZulipTestCase from zerver.lib.users import get_api_key from zerver.models import get_user, get_realm class ZephyrTest(ZulipTestCase): def test_webathena_kerberos_login(self) -> None: email = self.example_email('hamlet') self.login(email) def post(subdomain: Any, **kwargs: Any) -> HttpResponse: params = {k: ujson.dumps(v) for k, v in kwargs.items()} return self.client_post('/accounts/webathena_kerberos_login/', params, subdomain=subdomain) result = post("zulip") self.assert_json_error(result, 'Could not find Kerberos credential') result = post("zulip", cred='whatever') self.assert_json_error(result, 'Webathena login not enabled') email = str(self.mit_email("starnine")) realm = get_realm('zephyr') user = get_user(email, realm) api_key = get_api_key(user) self.login(email, realm=realm) def ccache_mock(**kwargs: Any) -> Any: return patch('zerver.views.zephyr.make_ccache', **kwargs) def ssh_mock(**kwargs: Any) -> Any: return patch('zerver.views.zephyr.subprocess.check_call', **kwargs) def mirror_mock() -> Any: return self.settings(PERSONAL_ZMIRROR_SERVER='server') def logging_mock() -> Any: return patch('logging.exception') cred = dict(cname=dict(nameString=['starnine'])) with ccache_mock(side_effect=KeyError('foo')): result = post("zephyr", cred=cred) self.assert_json_error(result, 'Invalid Kerberos cache') with \ ccache_mock(return_value=b'1234'), \ ssh_mock(side_effect=KeyError('foo')), \ logging_mock() as log: result = post("zephyr", cred=cred) self.assert_json_error(result, 'We were unable to setup mirroring for you') log.assert_called_with("Error updating the user's ccache") with ccache_mock(return_value=b'1234'), mirror_mock(), ssh_mock() as ssh: result = post("zephyr", cred=cred) self.assert_json_success(result) ssh.assert_called_with([ 'ssh', 'server', '--', '/home/zulip/python-zulip-api/zulip/integrations/zephyr/process_ccache', 'starnine', api_key, 'MTIzNA==']) # Accounts whose Kerberos usernames are known not to match their # zephyr accounts are hardcoded, and should be handled properly. def kerberos_alter_egos_mock() -> Any: return patch( 'zerver.views.zephyr.kerberos_alter_egos', {'kerberos_alter_ego': 'starnine'}) cred = dict(cname=dict(nameString=['kerberos_alter_ego'])) with \ ccache_mock(return_value=b'1234'), \ mirror_mock(), \ ssh_mock() as ssh, \ kerberos_alter_egos_mock(): result = post("zephyr", cred=cred) self.assert_json_success(result) ssh.assert_called_with([ 'ssh', 'server', '--', '/home/zulip/python-zulip-api/zulip/integrations/zephyr/process_ccache', 'starnine', api_key, 'MTIzNA=='])
[ "Any", "Any", "Any", "Any" ]
[ 430, 445, 1136, 1251 ]
[ 433, 448, 1139, 1254 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tests/tests.py
[]
[]
[]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tornado/__init__.py
[]
[]
[]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tornado/application.py
import atexit import tornado.web from django.conf import settings from tornado import ioloop from zerver.tornado import autoreload from zerver.lib.queue import get_queue_client from zerver.tornado.handlers import AsyncDjangoHandler from zerver.tornado.socket import get_sockjs_router def setup_tornado_rabbitmq() -> None: # nocoverage # When tornado is shut down, disconnect cleanly from rabbitmq if settings.USING_RABBITMQ: queue_client = get_queue_client() atexit.register(lambda: queue_client.close()) autoreload.add_reload_hook(lambda: queue_client.close()) def create_tornado_application(port: int) -> tornado.web.Application: urls = ( r"/notify_tornado", r"/json/events", r"/api/v1/events", r"/api/v1/events/internal", ) # Application is an instance of Django's standard wsgi handler. return tornado.web.Application(([(url, AsyncDjangoHandler) for url in urls] + get_sockjs_router(port).urls), debug=settings.DEBUG, autoreload=False, # Disable Tornado's own request logging, since we have our own log_function=lambda x: None)
[ "int" ]
[ 637 ]
[ 640 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tornado/autoreload.py
# Copyright 2009 Facebook # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Automatically restart the server when a source file is modified. Most applications should not access this module directly. Instead, pass the keyword argument ``autoreload=True`` to the `tornado.web.Application` constructor (or ``debug=True``, which enables this setting and several others). This will enable autoreload mode as well as checking for changes to templates and static resources. Note that restarting is a destructive operation and any requests in progress will be aborted when the process restarts. (If you want to disable autoreload while using other debug-mode features, pass both ``debug=True`` and ``autoreload=False``). This module can also be used as a command-line wrapper around scripts such as unit test runners. See the `main` method for details. The command-line wrapper and Application debug modes can be used together. This combination is encouraged as the wrapper catches syntax errors and other import-time failures, while debug mode catches changes once the server has started. This module depends on `.IOLoop`, so it will not work in WSGI applications and Google App Engine. It also will not work correctly when `.HTTPServer`'s multi-process mode is used. Reloading loses any Python interpreter command-line arguments (e.g. ``-u``) because it re-executes Python using ``sys.executable`` and ``sys.argv``. Additionally, modifying these variables will cause reloading to behave incorrectly. """ # Further patched by Zulip check whether the code we're about to # reload actually imports before reloading into it. This fixes a # major development workflow problem, where if one did a `git rebase`, # Tornado would crash itself by auto-reloading into a version of the # code that didn't work. from __future__ import absolute_import, division, print_function import os import sys import functools import importlib import logging import os import pkgutil # type: ignore # upstream import sys import traceback import types import subprocess import weakref from tornado import ioloop from tornado.log import gen_log from tornado import process from tornado.util import exec_in try: import signal except ImportError: signal = None # os.execv is broken on Windows and can't properly parse command line # arguments and executable name if they contain whitespaces. subprocess # fixes that behavior. _has_execv = sys.platform != 'win32' _watched_files = set() _reload_hooks = [] _reload_attempted = False _io_loops = weakref.WeakKeyDictionary() # type: ignore # upstream needs_to_reload = False def start(io_loop=None, check_time=500): """Begins watching source files for changes. .. versionchanged:: 4.1 The ``io_loop`` argument is deprecated. """ io_loop = io_loop or ioloop.IOLoop.current() if io_loop in _io_loops: return _io_loops[io_loop] = True if len(_io_loops) > 1: gen_log.warning("tornado.autoreload started more than once in the same process") modify_times = {} callback = functools.partial(_reload_on_update, modify_times) scheduler = ioloop.PeriodicCallback(callback, check_time, io_loop=io_loop) scheduler.start() def wait(): """Wait for a watched file to change, then restart the process. Intended to be used at the end of scripts like unit test runners, to run the tests again after any source file changes (but see also the command-line interface in `main`) """ io_loop = ioloop.IOLoop() start(io_loop) io_loop.start() def watch(filename): """Add a file to the watch list. All imported modules are watched by default. """ _watched_files.add(filename) def add_reload_hook(fn): """Add a function to be called before reloading the process. Note that for open file and socket handles it is generally preferable to set the ``FD_CLOEXEC`` flag (using `fcntl` or ``tornado.platform.auto.set_close_exec``) instead of using a reload hook to close them. """ _reload_hooks.append(fn) def _reload_on_update(modify_times): global needs_to_reload if _reload_attempted: # We already tried to reload and it didn't work, so don't try again. return if process.task_id() is not None: # We're in a child process created by fork_processes. If child # processes restarted themselves, they'd all restart and then # all call fork_processes again. return for module in list(sys.modules.values()): # Some modules play games with sys.modules (e.g. email/__init__.py # in the standard library), and occasionally this can cause strange # failures in getattr. Just ignore anything that's not an ordinary # module. if not isinstance(module, types.ModuleType): continue path = getattr(module, "__file__", None) if not path: continue if path.endswith(".pyc") or path.endswith(".pyo"): path = path[:-1] result = _check_file(modify_times, module, path) if result is False: # If any files errored, we abort this attempt at reloading. return if result is True: # If any files had actual changes that import properly, # we'll plan to reload the next time we run with no files # erroring. needs_to_reload = True if needs_to_reload: _reload() def _check_file(modify_times, module, path): try: modified = os.stat(path).st_mtime except Exception: return if path not in modify_times: modify_times[path] = modified return if modify_times[path] != modified: gen_log.info("%s modified; restarting server", path) modify_times[path] = modified else: return try: importlib.reload(module) except Exception: gen_log.error("Error importing %s, not reloading" % (path,)) traceback.print_exc() return False return True def _reload(): global _reload_attempted _reload_attempted = True for fn in _reload_hooks: fn() if hasattr(signal, "setitimer"): # Clear the alarm signal set by # ioloop.set_blocking_log_threshold so it doesn't fire # after the exec. signal.setitimer(signal.ITIMER_REAL, 0, 0) # sys.path fixes: see comments at top of file. If sys.path[0] is an empty # string, we were (probably) invoked with -m and the effective path # is about to change on re-exec. Add the current directory to $PYTHONPATH # to ensure that the new process sees the same path we did. path_prefix = '.' + os.pathsep if (sys.path[0] == '' and not os.environ.get("PYTHONPATH", "").startswith(path_prefix)): os.environ["PYTHONPATH"] = (path_prefix + os.environ.get("PYTHONPATH", "")) if not _has_execv: subprocess.Popen([sys.executable] + sys.argv) sys.exit(0) else: try: os.execv(sys.executable, [sys.executable] + sys.argv) except OSError: # Mac OS X versions prior to 10.6 do not support execv in # a process that contains multiple threads. Instead of # re-executing in the current process, start a new one # and cause the current process to exit. This isn't # ideal since the new process is detached from the parent # terminal and thus cannot easily be killed with ctrl-C, # but it's better than not being able to autoreload at # all. # Unfortunately the errno returned in this case does not # appear to be consistent, so we can't easily check for # this error specifically. os.spawnv(os.P_NOWAIT, sys.executable, [sys.executable] + sys.argv) # At this point the IOLoop has been closed and finally # blocks will experience errors if we allow the stack to # unwind, so just exit uncleanly. os._exit(0)
[]
[]
[]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tornado/descriptors.py
from typing import Any, Dict, Optional if False: from zerver.tornado.event_queue import ClientDescriptor descriptors_by_handler_id = {} # type: Dict[int, ClientDescriptor] def get_descriptor_by_handler_id(handler_id: int) -> Optional['ClientDescriptor']: return descriptors_by_handler_id.get(handler_id) def set_descriptor_by_handler_id(handler_id: int, client_descriptor: 'ClientDescriptor') -> None: descriptors_by_handler_id[handler_id] = client_descriptor def clear_descriptor_by_handler_id(handler_id: int, client_descriptor: 'ClientDescriptor') -> None: del descriptors_by_handler_id[handler_id]
[ "int", "int", "'ClientDescriptor'", "int", "'ClientDescriptor'" ]
[ 226, 363, 420, 559, 618 ]
[ 229, 366, 438, 562, 636 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tornado/event_queue.py
# See https://zulip.readthedocs.io/en/latest/subsystems/events-system.html for # high-level documentation on how this system works. from typing import cast, AbstractSet, Any, Callable, Dict, List, \ Mapping, MutableMapping, Optional, Iterable, Sequence, Set, Union from mypy_extensions import TypedDict from django.utils.translation import ugettext as _ from django.conf import settings from collections import deque import os import time import logging import ujson import requests import atexit import sys import signal import tornado.autoreload import tornado.ioloop import random from zerver.models import UserProfile, Client, Realm from zerver.decorator import cachify from zerver.tornado.handlers import clear_handler_by_id, get_handler_by_id, \ finish_handler, handler_stats_string from zerver.lib.utils import statsd from zerver.middleware import async_request_timer_restart from zerver.lib.message import MessageDict from zerver.lib.narrow import build_narrow_filter from zerver.lib.queue import queue_json_publish from zerver.lib.request import JsonableError from zerver.tornado.descriptors import clear_descriptor_by_handler_id, set_descriptor_by_handler_id from zerver.tornado.exceptions import BadEventQueueIdError from zerver.tornado.sharding import get_tornado_uri, get_tornado_port, \ notify_tornado_queue_name, tornado_return_queue_name import copy requests_client = requests.Session() for host in ['127.0.0.1', 'localhost']: if settings.TORNADO_SERVER and host in settings.TORNADO_SERVER: # This seems like the only working solution to ignore proxy in # requests library. requests_client.trust_env = False # The idle timeout used to be a week, but we found that in that # situation, queues from dead browser sessions would grow quite large # due to the accumulation of message data in those queues. IDLE_EVENT_QUEUE_TIMEOUT_SECS = 60 * 10 EVENT_QUEUE_GC_FREQ_MSECS = 1000 * 60 * 5 # Capped limit for how long a client can request an event queue # to live MAX_QUEUE_TIMEOUT_SECS = 7 * 24 * 60 * 60 # The heartbeats effectively act as a server-side timeout for # get_events(). The actual timeout value is randomized for each # client connection based on the below value. We ensure that the # maximum timeout value is 55 seconds, to deal with crappy home # wireless routers that kill "inactive" http connections. HEARTBEAT_MIN_FREQ_SECS = 45 class ClientDescriptor: def __init__(self, user_profile_id: int, user_profile_email: str, realm_id: int, event_queue: 'EventQueue', event_types: Optional[Sequence[str]], client_type_name: str, apply_markdown: bool=True, client_gravatar: bool=True, all_public_streams: bool=False, lifespan_secs: int=0, narrow: Iterable[Sequence[str]]=[]) -> None: # These objects are serialized on shutdown and restored on restart. # If fields are added or semantics are changed, temporary code must be # added to load_event_queues() to update the restored objects. # Additionally, the to_dict and from_dict methods must be updated self.user_profile_id = user_profile_id self.user_profile_email = user_profile_email self.realm_id = realm_id self.current_handler_id = None # type: Optional[int] self.current_client_name = None # type: Optional[str] self.event_queue = event_queue self.queue_timeout = lifespan_secs self.event_types = event_types self.last_connection_time = time.time() self.apply_markdown = apply_markdown self.client_gravatar = client_gravatar self.all_public_streams = all_public_streams self.client_type_name = client_type_name self._timeout_handle = None # type: Any # TODO: should be return type of ioloop.call_later self.narrow = narrow self.narrow_filter = build_narrow_filter(narrow) # Clamp queue_timeout to between minimum and maximum timeouts self.queue_timeout = max(IDLE_EVENT_QUEUE_TIMEOUT_SECS, min(self.queue_timeout, MAX_QUEUE_TIMEOUT_SECS)) def to_dict(self) -> Dict[str, Any]: # If you add a new key to this dict, make sure you add appropriate # migration code in from_dict or load_event_queues to account for # loading event queues that lack that key. return dict(user_profile_id=self.user_profile_id, user_profile_email=self.user_profile_email, realm_id=self.realm_id, event_queue=self.event_queue.to_dict(), queue_timeout=self.queue_timeout, event_types=self.event_types, last_connection_time=self.last_connection_time, apply_markdown=self.apply_markdown, client_gravatar=self.client_gravatar, all_public_streams=self.all_public_streams, narrow=self.narrow, client_type_name=self.client_type_name) def __repr__(self) -> str: return "ClientDescriptor<%s>" % (self.event_queue.id,) @classmethod def from_dict(cls, d: MutableMapping[str, Any]) -> 'ClientDescriptor': if 'user_profile_email' not in d: # Temporary migration for the addition of the new user_profile_email field from zerver.models import get_user_profile_by_id d['user_profile_email'] = get_user_profile_by_id(d['user_profile_id']).email if 'client_type' in d: # Temporary migration for the rename of client_type to client_type_name d['client_type_name'] = d['client_type'] if 'client_gravatar' not in d: # Temporary migration for the addition of the client_gravatar field d['client_gravatar'] = False ret = cls( d['user_profile_id'], d['user_profile_email'], d['realm_id'], EventQueue.from_dict(d['event_queue']), d['event_types'], d['client_type_name'], d['apply_markdown'], d['client_gravatar'], d['all_public_streams'], d['queue_timeout'], d.get('narrow', []) ) ret.last_connection_time = d['last_connection_time'] return ret def prepare_for_pickling(self) -> None: self.current_handler_id = None self._timeout_handle = None def add_event(self, event: Dict[str, Any]) -> None: if self.current_handler_id is not None: handler = get_handler_by_id(self.current_handler_id) async_request_timer_restart(handler._request) self.event_queue.push(event) self.finish_current_handler() def finish_current_handler(self) -> bool: if self.current_handler_id is not None: err_msg = "Got error finishing handler for queue %s" % (self.event_queue.id,) try: finish_handler(self.current_handler_id, self.event_queue.id, self.event_queue.contents(), self.apply_markdown) except Exception: logging.exception(err_msg) finally: self.disconnect_handler() return True return False def accepts_event(self, event: Mapping[str, Any]) -> bool: if self.event_types is not None and event["type"] not in self.event_types: return False if event["type"] == "message": return self.narrow_filter(event) return True # TODO: Refactor so we don't need this function def accepts_messages(self) -> bool: return self.event_types is None or "message" in self.event_types def idle(self, now: float) -> bool: if not hasattr(self, 'queue_timeout'): self.queue_timeout = IDLE_EVENT_QUEUE_TIMEOUT_SECS return (self.current_handler_id is None and now - self.last_connection_time >= self.queue_timeout) def connect_handler(self, handler_id: int, client_name: str) -> None: self.current_handler_id = handler_id self.current_client_name = client_name set_descriptor_by_handler_id(handler_id, self) self.last_connection_time = time.time() def timeout_callback() -> None: self._timeout_handle = None # All clients get heartbeat events self.add_event(dict(type='heartbeat')) ioloop = tornado.ioloop.IOLoop.instance() interval = HEARTBEAT_MIN_FREQ_SECS + random.randint(0, 10) if self.client_type_name != 'API: heartbeat test': self._timeout_handle = ioloop.call_later(interval, timeout_callback) def disconnect_handler(self, client_closed: bool=False) -> None: if self.current_handler_id: clear_descriptor_by_handler_id(self.current_handler_id, None) clear_handler_by_id(self.current_handler_id) if client_closed: logging.info("Client disconnected for queue %s (%s via %s)" % (self.event_queue.id, self.user_profile_email, self.current_client_name)) self.current_handler_id = None self.current_client_name = None if self._timeout_handle is not None: ioloop = tornado.ioloop.IOLoop.instance() ioloop.remove_timeout(self._timeout_handle) self._timeout_handle = None def cleanup(self) -> None: # Before we can GC the event queue, we need to disconnect the # handler and notify the client (or connection server) so that # they can cleanup their own state related to the GC'd event # queue. Finishing the handler before we GC ensures the # invariant that event queues are idle when passed to # `do_gc_event_queues` is preserved. self.finish_current_handler() do_gc_event_queues({self.event_queue.id}, {self.user_profile_id}, {self.realm_id}) def compute_full_event_type(event: Mapping[str, Any]) -> str: if event["type"] == "update_message_flags": if event["all"]: # Put the "all" case in its own category return "all_flags/%s/%s" % (event["flag"], event["operation"]) return "flags/%s/%s" % (event["operation"], event["flag"]) return event["type"] class EventQueue: def __init__(self, id: str) -> None: self.queue = deque() # type: ignore # Should be Deque[Dict[str, Any]], but Deque isn't available in Python 3.4 self.next_event_id = 0 # type: int self.id = id # type: str self.virtual_events = {} # type: Dict[str, Dict[str, Any]] def to_dict(self) -> Dict[str, Any]: # If you add a new key to this dict, make sure you add appropriate # migration code in from_dict or load_event_queues to account for # loading event queues that lack that key. return dict(id=self.id, next_event_id=self.next_event_id, queue=list(self.queue), virtual_events=self.virtual_events) @classmethod def from_dict(cls, d: Dict[str, Any]) -> 'EventQueue': ret = cls(d['id']) ret.next_event_id = d['next_event_id'] ret.queue = deque(d['queue']) ret.virtual_events = d.get("virtual_events", {}) return ret def push(self, event: Dict[str, Any]) -> None: event['id'] = self.next_event_id self.next_event_id += 1 full_event_type = compute_full_event_type(event) if (full_event_type in ["pointer", "restart"] or full_event_type.startswith("flags/")): if full_event_type not in self.virtual_events: self.virtual_events[full_event_type] = copy.deepcopy(event) return # Update the virtual event with the values from the event virtual_event = self.virtual_events[full_event_type] virtual_event["id"] = event["id"] if "timestamp" in event: virtual_event["timestamp"] = event["timestamp"] if full_event_type == "pointer": virtual_event["pointer"] = event["pointer"] elif full_event_type == "restart": virtual_event["server_generation"] = event["server_generation"] elif full_event_type.startswith("flags/"): virtual_event["messages"] += event["messages"] else: self.queue.append(event) # Note that pop ignores virtual events. This is fine in our # current usage since virtual events should always be resolved to # a real event before being given to users. def pop(self) -> Dict[str, Any]: return self.queue.popleft() def empty(self) -> bool: return len(self.queue) == 0 and len(self.virtual_events) == 0 # See the comment on pop; that applies here as well def prune(self, through_id: int) -> None: while len(self.queue) != 0 and self.queue[0]['id'] <= through_id: self.pop() def contents(self) -> List[Dict[str, Any]]: contents = [] # type: List[Dict[str, Any]] virtual_id_map = {} # type: Dict[str, Dict[str, Any]] for event_type in self.virtual_events: virtual_id_map[self.virtual_events[event_type]["id"]] = self.virtual_events[event_type] virtual_ids = sorted(list(virtual_id_map.keys())) # Merge the virtual events into their final place in the queue index = 0 length = len(virtual_ids) for event in self.queue: while index < length and virtual_ids[index] < event["id"]: contents.append(virtual_id_map[virtual_ids[index]]) index += 1 contents.append(event) while index < length: contents.append(virtual_id_map[virtual_ids[index]]) index += 1 self.virtual_events = {} self.queue = deque(contents) return contents # maps queue ids to client descriptors clients = {} # type: Dict[str, ClientDescriptor] # maps user id to list of client descriptors user_clients = {} # type: Dict[int, List[ClientDescriptor]] # maps realm id to list of client descriptors with all_public_streams=True realm_clients_all_streams = {} # type: Dict[int, List[ClientDescriptor]] # list of registered gc hooks. # each one will be called with a user profile id, queue, and bool # last_for_client that is true if this is the last queue pertaining # to this user_profile_id # that is about to be deleted gc_hooks = [] # type: List[Callable[[int, ClientDescriptor, bool], None]] next_queue_id = 0 def clear_client_event_queues_for_testing() -> None: assert(settings.TEST_SUITE) clients.clear() user_clients.clear() realm_clients_all_streams.clear() gc_hooks.clear() global next_queue_id next_queue_id = 0 def add_client_gc_hook(hook: Callable[[int, ClientDescriptor, bool], None]) -> None: gc_hooks.append(hook) def get_client_descriptor(queue_id: str) -> ClientDescriptor: return clients.get(queue_id) def get_client_descriptors_for_user(user_profile_id: int) -> List[ClientDescriptor]: return user_clients.get(user_profile_id, []) def get_client_descriptors_for_realm_all_streams(realm_id: int) -> List[ClientDescriptor]: return realm_clients_all_streams.get(realm_id, []) def add_to_client_dicts(client: ClientDescriptor) -> None: user_clients.setdefault(client.user_profile_id, []).append(client) if client.all_public_streams or client.narrow != []: realm_clients_all_streams.setdefault(client.realm_id, []).append(client) def allocate_client_descriptor(new_queue_data: MutableMapping[str, Any]) -> ClientDescriptor: global next_queue_id queue_id = str(settings.SERVER_GENERATION) + ':' + str(next_queue_id) next_queue_id += 1 new_queue_data["event_queue"] = EventQueue(queue_id).to_dict() client = ClientDescriptor.from_dict(new_queue_data) clients[queue_id] = client add_to_client_dicts(client) return client def do_gc_event_queues(to_remove: AbstractSet[str], affected_users: AbstractSet[int], affected_realms: AbstractSet[int]) -> None: def filter_client_dict(client_dict: MutableMapping[int, List[ClientDescriptor]], key: int) -> None: if key not in client_dict: return new_client_list = [c for c in client_dict[key] if c.event_queue.id not in to_remove] if len(new_client_list) == 0: del client_dict[key] else: client_dict[key] = new_client_list for user_id in affected_users: filter_client_dict(user_clients, user_id) for realm_id in affected_realms: filter_client_dict(realm_clients_all_streams, realm_id) for id in to_remove: for cb in gc_hooks: cb(clients[id].user_profile_id, clients[id], clients[id].user_profile_id not in user_clients) del clients[id] def gc_event_queues(port: int) -> None: start = time.time() to_remove = set() # type: Set[str] affected_users = set() # type: Set[int] affected_realms = set() # type: Set[int] for (id, client) in clients.items(): if client.idle(start): to_remove.add(id) affected_users.add(client.user_profile_id) affected_realms.add(client.realm_id) # We don't need to call e.g. finish_current_handler on the clients # being removed because they are guaranteed to be idle and thus # not have a current handler. do_gc_event_queues(to_remove, affected_users, affected_realms) if settings.PRODUCTION: logging.info(('Tornado %d removed %d idle event queues owned by %d users in %.3fs.' + ' Now %d active queues, %s') % (port, len(to_remove), len(affected_users), time.time() - start, len(clients), handler_stats_string())) statsd.gauge('tornado.active_queues', len(clients)) statsd.gauge('tornado.active_users', len(user_clients)) def persistent_queue_filename(port: int, last: bool=False) -> str: if settings.TORNADO_PROCESSES == 1: # Use non-port-aware, legacy version. if last: return "/var/tmp/event_queues.json.last" return settings.JSON_PERSISTENT_QUEUE_FILENAME_PATTERN % ('',) if last: return "/var/tmp/event_queues.%d.last.json" % (port,) return settings.JSON_PERSISTENT_QUEUE_FILENAME_PATTERN % ('.' + str(port),) def dump_event_queues(port: int) -> None: start = time.time() with open(persistent_queue_filename(port), "w") as stored_queues: ujson.dump([(qid, client.to_dict()) for (qid, client) in clients.items()], stored_queues) logging.info('Tornado %d dumped %d event queues in %.3fs' % (port, len(clients), time.time() - start)) def load_event_queues(port: int) -> None: global clients start = time.time() # ujson chokes on bad input pretty easily. We separate out the actual # file reading from the loading so that we don't silently fail if we get # bad input. try: with open(persistent_queue_filename(port), "r") as stored_queues: json_data = stored_queues.read() try: clients = dict((qid, ClientDescriptor.from_dict(client)) for (qid, client) in ujson.loads(json_data)) except Exception: logging.exception("Tornado %d could not deserialize event queues" % (port,)) except (IOError, EOFError): pass for client in clients.values(): # Put code for migrations due to event queue data format changes here add_to_client_dicts(client) logging.info('Tornado %d loaded %d event queues in %.3fs' % (port, len(clients), time.time() - start)) def send_restart_events(immediate: bool=False) -> None: event = dict(type='restart', server_generation=settings.SERVER_GENERATION) # type: Dict[str, Any] if immediate: event['immediate'] = True for client in clients.values(): if client.accepts_event(event): client.add_event(event.copy()) def setup_event_queue(port: int) -> None: if not settings.TEST_SUITE: load_event_queues(port) atexit.register(dump_event_queues, port) # Make sure we dump event queues even if we exit via signal signal.signal(signal.SIGTERM, lambda signum, stack: sys.exit(1)) tornado.autoreload.add_reload_hook(lambda: dump_event_queues(port)) try: os.rename(persistent_queue_filename(port), persistent_queue_filename(port, last=True)) except OSError: pass # Set up event queue garbage collection ioloop = tornado.ioloop.IOLoop.instance() pc = tornado.ioloop.PeriodicCallback(lambda: gc_event_queues(port), EVENT_QUEUE_GC_FREQ_MSECS, ioloop) pc.start() send_restart_events(immediate=settings.DEVELOPMENT) def fetch_events(query: Mapping[str, Any]) -> Dict[str, Any]: queue_id = query["queue_id"] # type: str dont_block = query["dont_block"] # type: bool last_event_id = query["last_event_id"] # type: int user_profile_id = query["user_profile_id"] # type: int new_queue_data = query.get("new_queue_data") # type: Optional[MutableMapping[str, Any]] user_profile_email = query["user_profile_email"] # type: str client_type_name = query["client_type_name"] # type: str handler_id = query["handler_id"] # type: int try: was_connected = False orig_queue_id = queue_id extra_log_data = "" if queue_id is None: if dont_block: client = allocate_client_descriptor(new_queue_data) queue_id = client.event_queue.id else: raise JsonableError(_("Missing 'queue_id' argument")) else: if last_event_id is None: raise JsonableError(_("Missing 'last_event_id' argument")) client = get_client_descriptor(queue_id) if client is None: raise BadEventQueueIdError(queue_id) if user_profile_id != client.user_profile_id: raise JsonableError(_("You are not authorized to get events from this queue")) client.event_queue.prune(last_event_id) was_connected = client.finish_current_handler() if not client.event_queue.empty() or dont_block: response = dict(events=client.event_queue.contents(), handler_id=handler_id) # type: Dict[str, Any] if orig_queue_id is None: response['queue_id'] = queue_id if len(response["events"]) == 1: extra_log_data = "[%s/%s/%s]" % (queue_id, len(response["events"]), response["events"][0]["type"]) else: extra_log_data = "[%s/%s]" % (queue_id, len(response["events"])) if was_connected: extra_log_data += " [was connected]" return dict(type="response", response=response, extra_log_data=extra_log_data) # After this point, dont_block=False, the queue is empty, and we # have a pre-existing queue, so we wait for new events. if was_connected: logging.info("Disconnected handler for queue %s (%s/%s)" % (queue_id, user_profile_email, client_type_name)) except JsonableError as e: return dict(type="error", exception=e) client.connect_handler(handler_id, client_type_name) return dict(type="async") # The following functions are called from Django # Workaround to support the Python-requests 1.0 transition of .json # from a property to a function requests_json_is_function = callable(requests.Response.json) def extract_json_response(resp: requests.Response) -> Dict[str, Any]: if requests_json_is_function: return resp.json() else: return resp.json # type: ignore # mypy trusts the stub, not the runtime type checking of this fn def request_event_queue(user_profile: UserProfile, user_client: Client, apply_markdown: bool, client_gravatar: bool, queue_lifespan_secs: int, event_types: Optional[Iterable[str]]=None, all_public_streams: bool=False, narrow: Iterable[Sequence[str]]=[]) -> Optional[str]: if settings.TORNADO_SERVER: tornado_uri = get_tornado_uri(user_profile.realm) req = {'dont_block': 'true', 'apply_markdown': ujson.dumps(apply_markdown), 'client_gravatar': ujson.dumps(client_gravatar), 'all_public_streams': ujson.dumps(all_public_streams), 'client': 'internal', 'user_profile_id': user_profile.id, 'user_client': user_client.name, 'narrow': ujson.dumps(narrow), 'secret': settings.SHARED_SECRET, 'lifespan_secs': queue_lifespan_secs} if event_types is not None: req['event_types'] = ujson.dumps(event_types) try: resp = requests_client.post(tornado_uri + '/api/v1/events/internal', data=req) except requests.adapters.ConnectionError: logging.error('Tornado server does not seem to be running, check %s ' 'and %s for more information.' % (settings.ERROR_FILE_LOG_PATH, "tornado.log")) raise requests.adapters.ConnectionError( "Django cannot connect to Tornado server (%s); try restarting" % (tornado_uri,)) resp.raise_for_status() return extract_json_response(resp)['queue_id'] return None def get_user_events(user_profile: UserProfile, queue_id: str, last_event_id: int) -> List[Dict[Any, Any]]: if settings.TORNADO_SERVER: tornado_uri = get_tornado_uri(user_profile.realm) post_data = { 'queue_id': queue_id, 'last_event_id': last_event_id, 'dont_block': 'true', 'user_profile_id': user_profile.id, 'secret': settings.SHARED_SECRET, 'client': 'internal' } # type: Dict[str, Any] resp = requests_client.post(tornado_uri + '/api/v1/events/internal', data=post_data) resp.raise_for_status() return extract_json_response(resp)['events'] return [] # Send email notifications to idle users # after they are idle for 1 hour NOTIFY_AFTER_IDLE_HOURS = 1 def build_offline_notification(user_profile_id: int, message_id: int) -> Dict[str, Any]: return {"user_profile_id": user_profile_id, "message_id": message_id, "timestamp": time.time()} def missedmessage_hook(user_profile_id: int, client: ClientDescriptor, last_for_client: bool) -> None: """The receiver_is_off_zulip logic used to determine whether a user has no active client suffers from a somewhat fundamental race condition. If the client is no longer on the Internet, receiver_is_off_zulip will still return true for IDLE_EVENT_QUEUE_TIMEOUT_SECS, until the queue is garbage-collected. This would cause us to reliably miss push/email notifying users for messages arriving during the IDLE_EVENT_QUEUE_TIMEOUT_SECS after they suspend their laptop (for example). We address this by, when the queue is garbage-collected at the end of those 10 minutes, checking to see if it's the last one, and if so, potentially triggering notifications to the user at that time, resulting in at most a IDLE_EVENT_QUEUE_TIMEOUT_SECS delay in the arrival of their notifications. As Zulip's APIs get more popular and the mobile apps start using long-lived event queues for perf optimization, future versions of this will likely need to replace checking `last_for_client` with something more complicated, so that we only consider clients like web browsers, not the mobile apps or random API scripts. """ # Only process missedmessage hook when the last queue for a # client has been garbage collected if not last_for_client: return for event in client.event_queue.contents(): if event['type'] != 'message': continue assert 'flags' in event flags = event.get('flags') mentioned = 'mentioned' in flags and 'read' not in flags private_message = event['message']['type'] == 'private' # stream_push_notify is set in process_message_event. stream_push_notify = event.get('stream_push_notify', False) stream_email_notify = event.get('stream_email_notify', False) stream_name = None if not private_message: stream_name = event['message']['display_recipient'] # Since one is by definition idle, we don't need to check always_push_notify always_push_notify = False # Since we just GC'd the last event queue, the user is definitely idle. idle = True message_id = event['message']['id'] # Pass on the information on whether a push or email notification was already sent. already_notified = dict( push_notified = event.get("push_notified", False), email_notified = event.get("email_notified", False), ) maybe_enqueue_notifications(user_profile_id, message_id, private_message, mentioned, stream_push_notify, stream_email_notify, stream_name, always_push_notify, idle, already_notified) def receiver_is_off_zulip(user_profile_id: int) -> bool: # If a user has no message-receiving event queues, they've got no open zulip # session so we notify them all_client_descriptors = get_client_descriptors_for_user(user_profile_id) message_event_queues = [client for client in all_client_descriptors if client.accepts_messages()] off_zulip = len(message_event_queues) == 0 return off_zulip def maybe_enqueue_notifications(user_profile_id: int, message_id: int, private_message: bool, mentioned: bool, stream_push_notify: bool, stream_email_notify: bool, stream_name: Optional[str], always_push_notify: bool, idle: bool, already_notified: Dict[str, bool]) -> Dict[str, bool]: """This function has a complete unit test suite in `test_enqueue_notifications` that should be expanded as we add more features here.""" notified = dict() # type: Dict[str, bool] if (idle or always_push_notify) and (private_message or mentioned or stream_push_notify): notice = build_offline_notification(user_profile_id, message_id) if private_message: notice['trigger'] = 'private_message' elif mentioned: notice['trigger'] = 'mentioned' elif stream_push_notify: notice['trigger'] = 'stream_push_notify' else: raise AssertionError("Unknown notification trigger!") notice['stream_name'] = stream_name if not already_notified.get("push_notified"): queue_json_publish("missedmessage_mobile_notifications", notice) notified['push_notified'] = True # Send missed_message emails if a private message or a # mention. Eventually, we'll add settings to allow email # notifications to match the model of push notifications # above. if idle and (private_message or mentioned or stream_email_notify): notice = build_offline_notification(user_profile_id, message_id) if private_message: notice['trigger'] = 'private_message' elif mentioned: notice['trigger'] = 'mentioned' elif stream_email_notify: notice['trigger'] = 'stream_email_notify' else: raise AssertionError("Unknown notification trigger!") notice['stream_name'] = stream_name if not already_notified.get("email_notified"): queue_json_publish("missedmessage_emails", notice, lambda notice: None) notified['email_notified'] = True return notified ClientInfo = TypedDict('ClientInfo', { 'client': ClientDescriptor, 'flags': Optional[Iterable[str]], 'is_sender': bool, }) def get_client_info_for_message_event(event_template: Mapping[str, Any], users: Iterable[Mapping[str, Any]]) -> Dict[str, ClientInfo]: ''' Return client info for all the clients interested in a message. This basically includes clients for users who are recipients of the message, with some nuances for bots that auto-subscribe to all streams, plus users who may be mentioned, etc. ''' send_to_clients = {} # type: Dict[str, ClientInfo] sender_queue_id = event_template.get('sender_queue_id', None) # type: Optional[str] def is_sender_client(client: ClientDescriptor) -> bool: return (sender_queue_id is not None) and client.event_queue.id == sender_queue_id # If we're on a public stream, look for clients (typically belonging to # bots) that are registered to get events for ALL streams. if 'stream_name' in event_template and not event_template.get("invite_only"): realm_id = event_template['realm_id'] for client in get_client_descriptors_for_realm_all_streams(realm_id): send_to_clients[client.event_queue.id] = dict( client=client, flags=[], is_sender=is_sender_client(client) ) for user_data in users: user_profile_id = user_data['id'] # type: int flags = user_data.get('flags', []) # type: Iterable[str] for client in get_client_descriptors_for_user(user_profile_id): send_to_clients[client.event_queue.id] = dict( client=client, flags=flags, is_sender=is_sender_client(client) ) return send_to_clients def process_message_event(event_template: Mapping[str, Any], users: Iterable[Mapping[str, Any]]) -> None: send_to_clients = get_client_info_for_message_event(event_template, users) presence_idle_user_ids = set(event_template.get('presence_idle_user_ids', [])) wide_dict = event_template['message_dict'] # type: Dict[str, Any] sender_id = wide_dict['sender_id'] # type: int message_id = wide_dict['id'] # type: int message_type = wide_dict['type'] # type: str sending_client = wide_dict['client'] # type: str @cachify def get_client_payload(apply_markdown: bool, client_gravatar: bool) -> Dict[str, Any]: dct = copy.deepcopy(wide_dict) MessageDict.finalize_payload(dct, apply_markdown, client_gravatar) return dct # Extra user-specific data to include extra_user_data = {} # type: Dict[int, Any] for user_data in users: user_profile_id = user_data['id'] # type: int flags = user_data.get('flags', []) # type: Iterable[str] # If the recipient was offline and the message was a single or group PM to them # or they were @-notified potentially notify more immediately private_message = message_type == "private" and user_profile_id != sender_id mentioned = 'mentioned' in flags and 'read' not in flags stream_push_notify = user_data.get('stream_push_notify', False) stream_email_notify = user_data.get('stream_email_notify', False) # We first check if a message is potentially mentionable, # since receiver_is_off_zulip is somewhat expensive. if private_message or mentioned or stream_push_notify or stream_email_notify: idle = receiver_is_off_zulip(user_profile_id) or (user_profile_id in presence_idle_user_ids) always_push_notify = user_data.get('always_push_notify', False) stream_name = event_template.get('stream_name') result = maybe_enqueue_notifications(user_profile_id, message_id, private_message, mentioned, stream_push_notify, stream_email_notify, stream_name, always_push_notify, idle, {}) result['stream_push_notify'] = stream_push_notify result['stream_email_notify'] = stream_email_notify extra_user_data[user_profile_id] = result for client_data in send_to_clients.values(): client = client_data['client'] flags = client_data['flags'] is_sender = client_data.get('is_sender', False) # type: bool extra_data = extra_user_data.get(client.user_profile_id, None) # type: Optional[Mapping[str, bool]] if not client.accepts_messages(): # The actual check is the accepts_event() check below; # this line is just an optimization to avoid copying # message data unnecessarily continue message_dict = get_client_payload(client.apply_markdown, client.client_gravatar) # Make sure Zephyr mirroring bots know whether stream is invite-only if "mirror" in client.client_type_name and event_template.get("invite_only"): message_dict = message_dict.copy() message_dict["invite_only_stream"] = True user_event = dict(type='message', message=message_dict, flags=flags) # type: Dict[str, Any] if extra_data is not None: user_event.update(extra_data) if is_sender: local_message_id = event_template.get('local_id', None) if local_message_id is not None: user_event["local_message_id"] = local_message_id if not client.accepts_event(user_event): continue # The below prevents (Zephyr) mirroring loops. if ('mirror' in sending_client and sending_client.lower() == client.client_type_name.lower()): continue client.add_event(user_event) def process_event(event: Mapping[str, Any], users: Iterable[int]) -> None: for user_profile_id in users: for client in get_client_descriptors_for_user(user_profile_id): if client.accepts_event(event): client.add_event(dict(event)) def process_userdata_event(event_template: Mapping[str, Any], users: Iterable[Mapping[str, Any]]) -> None: for user_data in users: user_profile_id = user_data['id'] user_event = dict(event_template) # shallow copy, but deep enough for our needs for key in user_data.keys(): if key != "id": user_event[key] = user_data[key] for client in get_client_descriptors_for_user(user_profile_id): if client.accepts_event(user_event): client.add_event(user_event) def process_message_update_event(event_template: Mapping[str, Any], users: Iterable[Mapping[str, Any]]) -> None: prior_mention_user_ids = set(event_template.get('prior_mention_user_ids', [])) mention_user_ids = set(event_template.get('mention_user_ids', [])) presence_idle_user_ids = set(event_template.get('presence_idle_user_ids', [])) stream_push_user_ids = set(event_template.get('stream_push_user_ids', [])) stream_email_user_ids = set(event_template.get('stream_email_user_ids', [])) push_notify_user_ids = set(event_template.get('push_notify_user_ids', [])) stream_name = event_template.get('stream_name') message_id = event_template['message_id'] for user_data in users: user_profile_id = user_data['id'] user_event = dict(event_template) # shallow copy, but deep enough for our needs for key in user_data.keys(): if key != "id": user_event[key] = user_data[key] maybe_enqueue_notifications_for_message_update( user_profile_id=user_profile_id, message_id=message_id, stream_name=stream_name, prior_mention_user_ids=prior_mention_user_ids, mention_user_ids=mention_user_ids, presence_idle_user_ids=presence_idle_user_ids, stream_push_user_ids=stream_push_user_ids, stream_email_user_ids=stream_email_user_ids, push_notify_user_ids=push_notify_user_ids, ) for client in get_client_descriptors_for_user(user_profile_id): if client.accepts_event(user_event): client.add_event(user_event) def maybe_enqueue_notifications_for_message_update(user_profile_id: UserProfile, message_id: int, stream_name: str, prior_mention_user_ids: Set[int], mention_user_ids: Set[int], presence_idle_user_ids: Set[int], stream_push_user_ids: Set[int], stream_email_user_ids: Set[int], push_notify_user_ids: Set[int]) -> None: private_message = (stream_name is None) if private_message: # We don't do offline notifications for PMs, because # we already notified the user of the original message return if (user_profile_id in prior_mention_user_ids): # Don't spam people with duplicate mentions. This is # especially important considering that most message # edits are simple typo corrections. return stream_push_notify = (user_profile_id in stream_push_user_ids) stream_email_notify = (user_profile_id in stream_email_user_ids) if stream_push_notify or stream_email_notify: # Currently we assume that if this flag is set to True, then # the user already was notified about the earlier message, # so we short circuit. We may handle this more rigorously # in the future by looking at something like an AlreadyNotified # model. return # We can have newly mentioned people in an updated message. mentioned = (user_profile_id in mention_user_ids) always_push_notify = user_profile_id in push_notify_user_ids idle = (user_profile_id in presence_idle_user_ids) or \ receiver_is_off_zulip(user_profile_id) maybe_enqueue_notifications( user_profile_id=user_profile_id, message_id=message_id, private_message=private_message, mentioned=mentioned, stream_push_notify=stream_push_notify, stream_email_notify=stream_email_notify, stream_name=stream_name, always_push_notify=always_push_notify, idle=idle, already_notified={}, ) def process_notification(notice: Mapping[str, Any]) -> None: event = notice['event'] # type: Mapping[str, Any] users = notice['users'] # type: Union[List[int], List[Mapping[str, Any]]] start_time = time.time() if event['type'] == "message": process_message_event(event, cast(Iterable[Mapping[str, Any]], users)) elif event['type'] == "update_message": process_message_update_event(event, cast(Iterable[Mapping[str, Any]], users)) elif event['type'] == "delete_message": process_userdata_event(event, cast(Iterable[Mapping[str, Any]], users)) else: process_event(event, cast(Iterable[int], users)) logging.debug("Tornado: Event %s for %s users took %sms" % ( event['type'], len(users), int(1000 * (time.time() - start_time)))) # Runs in the Django process to send a notification to Tornado. # # We use JSON rather than bare form parameters, so that we can represent # different types and for compatibility with non-HTTP transports. def send_notification_http(realm: Realm, data: Mapping[str, Any]) -> None: if settings.TORNADO_SERVER and not settings.RUNNING_INSIDE_TORNADO: tornado_uri = get_tornado_uri(realm) requests_client.post(tornado_uri + '/notify_tornado', data=dict( data = ujson.dumps(data), secret = settings.SHARED_SECRET)) else: process_notification(data) def send_event(realm: Realm, event: Mapping[str, Any], users: Union[Iterable[int], Iterable[Mapping[str, Any]]]) -> None: """`users` is a list of user IDs, or in the case of `message` type events, a list of dicts describing the users and metadata about the user/message pair.""" port = get_tornado_port(realm) queue_json_publish(notify_tornado_queue_name(port), dict(event=event, users=users), lambda *args, **kwargs: send_notification_http(realm, *args, **kwargs))
[ "int", "str", "int", "'EventQueue'", "Optional[Sequence[str]]", "str", "MutableMapping[str, Any]", "Dict[str, Any]", "Mapping[str, Any]", "float", "int", "str", "Mapping[str, Any]", "str", "Dict[str, Any]", "Dict[str, Any]", "int", "Callable[[int, ClientDescriptor, bool], None]", "str", "int", "int", "ClientDescriptor", "MutableMapping[str, Any]", "AbstractSet[str]", "AbstractSet[int]", "AbstractSet[int]", "MutableMapping[int, List[ClientDescriptor]]", "int", "int", "int", "int", "int", "int", "Mapping[str, Any]", "requests.Response", "UserProfile", "Client", "bool", "bool", "int", "UserProfile", "str", "int", "int", "int", "int", "ClientDescriptor", "bool", "int", "int", "int", "bool", "bool", "bool", "bool", "Optional[str]", "bool", "bool", "Dict[str, bool]", "Mapping[str, Any]", "Iterable[Mapping[str, Any]]", "ClientDescriptor", "Mapping[str, Any]", "Iterable[Mapping[str, Any]]", "bool", "bool", "Mapping[str, Any]", "Iterable[int]", "Mapping[str, Any]", "Iterable[Mapping[str, Any]]", "Mapping[str, Any]", "Iterable[Mapping[str, Any]]", "UserProfile", "int", "str", "Set[int]", "Set[int]", "Set[int]", "Set[int]", "Set[int]", "Set[int]", "Mapping[str, Any]", "Realm", "Mapping[str, Any]", "Realm", "Mapping[str, Any]", "Union[Iterable[int], Iterable[Mapping[str, Any]]]" ]
[ 2486, 2528, 2560, 2578, 2622, 2682, 5307, 6608, 7461, 7892, 8185, 8203, 10206, 10572, 11324, 11572, 13126, 15104, 15223, 15336, 15477, 15597, 15881, 16289, 16323, 16381, 16448, 16498, 17191, 18286, 18728, 19108, 20414, 21232, 24179, 24433, 24459, 24483, 24530, 24557, 26180, 26203, 26223, 27018, 27035, 27224, 27237, 27272, 30079, 30504, 30521, 30543, 30592, 30618, 30677, 30696, 30763, 30775, 30831, 32859, 32923, 33434, 34557, 34583, 35115, 35138, 38524, 38550, 38814, 38840, 39368, 39427, 41066, 41142, 41211, 41291, 41370, 41455, 41538, 41622, 41705, 43396, 44404, 44417, 44789, 44803, 44844 ]
[ 2489, 2531, 2563, 2590, 2645, 2685, 5331, 6622, 7478, 7897, 8188, 8206, 10223, 10575, 11338, 11586, 13129, 15149, 15226, 15339, 15480, 15613, 15905, 16305, 16339, 16397, 16491, 16501, 17194, 18289, 18731, 19111, 20417, 21249, 24196, 24444, 24465, 24487, 24534, 24560, 26191, 26206, 26226, 27021, 27038, 27227, 27253, 27276, 30082, 30507, 30524, 30547, 30596, 30622, 30681, 30709, 30767, 30779, 30846, 32876, 32950, 33450, 34574, 34610, 35119, 35142, 38541, 38563, 38831, 38867, 39385, 39454, 41077, 41145, 41214, 41299, 41378, 41463, 41546, 41630, 41713, 43413, 44409, 44434, 44794, 44820, 44893 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tornado/exceptions.py
from django.utils.translation import ugettext as _ from zerver.lib.exceptions import ErrorCode, JsonableError class BadEventQueueIdError(JsonableError): code = ErrorCode.BAD_EVENT_QUEUE_ID data_fields = ['queue_id'] def __init__(self, queue_id: str) -> None: self.queue_id = queue_id # type: str @staticmethod def msg_format() -> str: return _("Bad event queue id: {queue_id}")
[ "str" ]
[ 261 ]
[ 264 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tornado/handlers.py
import logging import sys import urllib from threading import Lock from typing import Any, Callable, Dict, List, Optional import tornado.web from django import http from django.conf import settings from django.core import exceptions, signals from django.urls import resolvers from django.core.exceptions import MiddlewareNotUsed from django.core.handlers import base from django.core.handlers.exception import convert_exception_to_response from django.core.handlers.wsgi import WSGIRequest, get_script_name from django.urls import set_script_prefix, set_urlconf from django.http import HttpRequest, HttpResponse from django.utils.module_loading import import_string from tornado.wsgi import WSGIContainer from zerver.decorator import RespondAsynchronously from zerver.lib.response import json_response from zerver.lib.types import ViewFuncT from zerver.middleware import async_request_timer_restart, async_request_timer_stop from zerver.tornado.descriptors import get_descriptor_by_handler_id current_handler_id = 0 handlers = {} # type: Dict[int, 'AsyncDjangoHandler'] def get_handler_by_id(handler_id: int) -> 'AsyncDjangoHandler': return handlers[handler_id] def allocate_handler_id(handler: 'AsyncDjangoHandler') -> int: global current_handler_id handlers[current_handler_id] = handler handler.handler_id = current_handler_id current_handler_id += 1 return handler.handler_id def clear_handler_by_id(handler_id: int) -> None: del handlers[handler_id] def handler_stats_string() -> str: return "%s handlers, latest ID %s" % (len(handlers), current_handler_id) def finish_handler(handler_id: int, event_queue_id: str, contents: List[Dict[str, Any]], apply_markdown: bool) -> None: err_msg = "Got error finishing handler for queue %s" % (event_queue_id,) try: # We call async_request_timer_restart here in case we are # being finished without any events (because another # get_events request has supplanted this request) handler = get_handler_by_id(handler_id) request = handler._request async_request_timer_restart(request) if len(contents) != 1: request._log_data['extra'] = "[%s/1]" % (event_queue_id,) else: request._log_data['extra'] = "[%s/1/%s]" % (event_queue_id, contents[0]["type"]) handler.zulip_finish(dict(result='success', msg='', events=contents, queue_id=event_queue_id), request, apply_markdown=apply_markdown) except IOError as e: if str(e) != 'Stream is closed': logging.exception(err_msg) except AssertionError as e: if str(e) != 'Request closed': logging.exception(err_msg) except Exception: logging.exception(err_msg) # Modified version of the base Tornado handler for Django # We mark this for nocoverage, since we only change 1 line of actual code. class AsyncDjangoHandlerBase(tornado.web.RequestHandler, base.BaseHandler): # nocoverage initLock = Lock() def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) # Set up middleware if needed. We couldn't do this earlier, because # settings weren't available. self._request_middleware = None # type: Optional[List[Callable[[HttpRequest], HttpResponse]]] self.initLock.acquire() # Check that middleware is still uninitialised. if self._request_middleware is None: self.load_middleware() self.initLock.release() self._auto_finish = False # Handler IDs are allocated here, and the handler ID map must # be cleared when the handler finishes its response allocate_handler_id(self) def __repr__(self) -> str: descriptor = get_descriptor_by_handler_id(self.handler_id) return "AsyncDjangoHandler<%s, %s>" % (self.handler_id, descriptor) def load_middleware(self) -> None: """ Populate middleware lists from settings.MIDDLEWARE. This is copied from Django. This uses settings.MIDDLEWARE setting with the old business logic. The middleware architecture is not compatible with our asynchronous handlers. The problem occurs when we return None from our handler. The Django middlewares throw exception because they can't handler None, so we can either upgrade the Django middlewares or just override this method to use the new setting with the old logic. The added advantage is that due to this our event system code doesn't change. """ self._request_middleware = [] # type: Optional[List[Callable[[HttpRequest], HttpResponse]]] self._view_middleware = [] # type: List[Callable[[HttpRequest, ViewFuncT, List[str], Dict[str, Any]], Optional[HttpResponse]]] self._template_response_middleware = [] # type: List[Callable[[HttpRequest, HttpResponse], HttpResponse]] self._response_middleware = [] # type: List[Callable[[HttpRequest, HttpResponse], HttpResponse]] self._exception_middleware = [] # type: List[Callable[[HttpRequest, Exception], Optional[HttpResponse]]] handler = convert_exception_to_response(self._legacy_get_response) for middleware_path in settings.MIDDLEWARE: mw_class = import_string(middleware_path) try: mw_instance = mw_class() except MiddlewareNotUsed as exc: if settings.DEBUG: if str(exc): base.logger.debug('MiddlewareNotUsed(%r): %s', middleware_path, exc) else: base.logger.debug('MiddlewareNotUsed: %r', middleware_path) continue if hasattr(mw_instance, 'process_request'): self._request_middleware.append(mw_instance.process_request) if hasattr(mw_instance, 'process_view'): self._view_middleware.append(mw_instance.process_view) if hasattr(mw_instance, 'process_template_response'): self._template_response_middleware.insert(0, mw_instance.process_template_response) if hasattr(mw_instance, 'process_response'): self._response_middleware.insert(0, mw_instance.process_response) if hasattr(mw_instance, 'process_exception'): self._exception_middleware.insert(0, mw_instance.process_exception) # We only assign to this when initialization is complete as it is used # as a flag for initialization being complete. self._middleware_chain = handler def get(self, *args: Any, **kwargs: Any) -> None: environ = WSGIContainer.environ(self.request) environ['PATH_INFO'] = urllib.parse.unquote(environ['PATH_INFO']) request = WSGIRequest(environ) request._tornado_handler = self set_script_prefix(get_script_name(environ)) signals.request_started.send(sender=self.__class__) try: response = self.get_response(request) if not response: return finally: signals.request_finished.send(sender=self.__class__) self.set_status(response.status_code) for h in response.items(): self.set_header(h[0], h[1]) if not hasattr(self, "_new_cookies"): self._new_cookies = [] # type: List[http.cookie.SimpleCookie] self._new_cookies.append(response.cookies) self.write(response.content) self.finish() def head(self, *args: Any, **kwargs: Any) -> None: self.get(*args, **kwargs) def post(self, *args: Any, **kwargs: Any) -> None: self.get(*args, **kwargs) def delete(self, *args: Any, **kwargs: Any) -> None: self.get(*args, **kwargs) def on_connection_close(self) -> None: client_descriptor = get_descriptor_by_handler_id(self.handler_id) if client_descriptor is not None: client_descriptor.disconnect_handler(client_closed=True) # Based on django.core.handlers.base: get_response def get_response(self, request: HttpRequest) -> HttpResponse: "Returns an HttpResponse object for the given HttpRequest" try: try: # Setup default url resolver for this thread. urlconf = settings.ROOT_URLCONF set_urlconf(urlconf) resolver = resolvers.RegexURLResolver(r'^/', urlconf) response = None # Apply request middleware for middleware_method in self._request_middleware: response = middleware_method(request) if response: break if hasattr(request, "urlconf"): # Reset url resolver with a custom urlconf. urlconf = request.urlconf set_urlconf(urlconf) resolver = resolvers.RegexURLResolver(r'^/', urlconf) ### ADDED BY ZULIP request._resolver = resolver ### END ADDED BY ZULIP callback, callback_args, callback_kwargs = resolver.resolve( request.path_info) # Apply view middleware if response is None: for view_middleware_method in self._view_middleware: response = view_middleware_method(request, callback, callback_args, callback_kwargs) if response: break ### THIS BLOCK MODIFIED BY ZULIP if response is None: try: response = callback(request, *callback_args, **callback_kwargs) if response is RespondAsynchronously: async_request_timer_stop(request) return None clear_handler_by_id(self.handler_id) except Exception as e: clear_handler_by_id(self.handler_id) # If the view raised an exception, run it through exception # middleware, and if the exception middleware returns a # response, use that. Otherwise, reraise the exception. for exception_middleware_method in self._exception_middleware: response = exception_middleware_method(request, e) if response: break if response is None: raise if response is None: try: view_name = callback.__name__ except AttributeError: view_name = callback.__class__.__name__ + '.__call__' raise ValueError("The view %s.%s returned None." % (callback.__module__, view_name)) # If the response supports deferred rendering, apply template # response middleware and the render the response if hasattr(response, 'render') and callable(response.render): for template_middleware_method in self._template_response_middleware: response = template_middleware_method(request, response) response = response.render() except http.Http404 as e: if settings.DEBUG: from django.views import debug response = debug.technical_404_response(request, e) else: try: callback, param_dict = resolver.resolve404() response = callback(request, **param_dict) except Exception: try: response = self.handle_uncaught_exception(request, resolver, sys.exc_info()) finally: signals.got_request_exception.send(sender=self.__class__, request=request) except exceptions.PermissionDenied: logging.warning( 'Forbidden (Permission denied): %s', request.path, extra={ 'status_code': 403, 'request': request }) try: callback, param_dict = resolver.resolve403() response = callback(request, **param_dict) except Exception: try: response = self.handle_uncaught_exception(request, resolver, sys.exc_info()) finally: signals.got_request_exception.send( sender=self.__class__, request=request) except SystemExit: # See https://code.djangoproject.com/ticket/4701 raise except Exception: exc_info = sys.exc_info() signals.got_request_exception.send(sender=self.__class__, request=request) return self.handle_uncaught_exception(request, resolver, exc_info) finally: # Reset urlconf on the way out for isolation set_urlconf(None) ### ZULIP CHANGE: The remainder of this function was moved ### into its own function, just below, so we can call it from ### finish(). response = self.apply_response_middleware(request, response, resolver) return response ### Copied from get_response (above in this file) def apply_response_middleware(self, request: HttpRequest, response: HttpResponse, resolver: resolvers.RegexURLResolver) -> HttpResponse: try: # Apply response middleware, regardless of the response for middleware_method in self._response_middleware: response = middleware_method(request, response) if hasattr(self, 'apply_response_fixes'): response = self.apply_response_fixes(request, response) except Exception: # Any exception should be gathered and handled signals.got_request_exception.send(sender=self.__class__, request=request) response = self.handle_uncaught_exception(request, resolver, sys.exc_info()) return response class AsyncDjangoHandler(AsyncDjangoHandlerBase): def zulip_finish(self, response: Dict[str, Any], request: HttpRequest, apply_markdown: bool) -> None: # Make sure that Markdown rendering really happened, if requested. # This is a security issue because it's where we escape HTML. # c.f. ticket #64 # # apply_markdown=True is the fail-safe default. if response['result'] == 'success' and 'messages' in response and apply_markdown: for msg in response['messages']: if msg['content_type'] != 'text/html': self.set_status(500) self.finish('Internal error: bad message format') if response['result'] == 'error': self.set_status(400) # Call the Django response middleware on our object so that # e.g. our own logging code can run; but don't actually use # the headers from that since sending those to Tornado seems # tricky; instead just send the (already json-rendered) # content on to Tornado django_response = json_response(res_type=response['result'], data=response, status=self.get_status()) django_response = self.apply_response_middleware(request, django_response, request._resolver) # Pass through the content-type from Django, as json content should be # served as application/json self.set_header("Content-Type", django_response['Content-Type']) self.finish(django_response.content)
[ "int", "'AsyncDjangoHandler'", "int", "int", "str", "List[Dict[str, Any]]", "bool", "Any", "Any", "Any", "Any", "Any", "Any", "Any", "Any", "Any", "Any", "HttpRequest", "HttpRequest", "HttpResponse", "resolvers.RegexURLResolver", "Dict[str, Any]", "HttpRequest", "bool" ]
[ 1110, 1206, 1448, 1636, 1657, 1691, 1729, 3142, 3157, 6752, 6767, 7681, 7696, 7771, 7786, 7863, 7878, 8247, 14155, 14178, 14236, 14979, 15004, 15054 ]
[ 1113, 1226, 1451, 1639, 1660, 1711, 1733, 3145, 3160, 6755, 6770, 7684, 7699, 7774, 7789, 7866, 7881, 8258, 14166, 14190, 14262, 14993, 15015, 15058 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tornado/ioloop_logging.py
import logging import select import time from typing import Any, Dict, List, Tuple from django.conf import settings from tornado.ioloop import IOLoop, PollIOLoop # There isn't a good way to get at what the underlying poll implementation # will be without actually constructing an IOLoop, so we just assume it will # be epoll. orig_poll_impl = select.epoll # This is used for a somewhat hacky way of passing the port number # into this early-initialized module. logging_data = {} # type: Dict[str, str] class InstrumentedPollIOLoop(PollIOLoop): def initialize(self, **kwargs): # type: ignore # TODO investigate likely buggy monkey patching here super().initialize(impl=InstrumentedPoll(), **kwargs) def instrument_tornado_ioloop() -> None: IOLoop.configure(InstrumentedPollIOLoop) # A hack to keep track of how much time we spend working, versus sleeping in # the event loop. # # Creating a new event loop instance with a custom impl object fails (events # don't get processed), so instead we modify the ioloop module variable holding # the default poll implementation. We need to do this before any Tornado code # runs that might instantiate the default event loop. class InstrumentedPoll: def __init__(self) -> None: self._underlying = orig_poll_impl() self._times = [] # type: List[Tuple[float, float]] self._last_print = 0.0 # Python won't let us subclass e.g. select.epoll, so instead # we proxy every method. __getattr__ handles anything we # don't define elsewhere. def __getattr__(self, name: str) -> Any: return getattr(self._underlying, name) # Call the underlying poll method, and report timing data. def poll(self, timeout: float) -> Any: # Avoid accumulating a bunch of insignificant data points # from short timeouts. if timeout < 1e-3: return self._underlying.poll(timeout) # Record start and end times for the underlying poll t0 = time.time() result = self._underlying.poll(timeout) t1 = time.time() # Log this datapoint and restrict our log to the past minute self._times.append((t0, t1)) while self._times and self._times[0][0] < t1 - 60: self._times.pop(0) # Report (at most once every 5s) the percentage of time spent # outside poll if self._times and t1 - self._last_print >= 5: total = t1 - self._times[0][0] in_poll = sum(b-a for a, b in self._times) if total > 0: percent_busy = 100 * (1 - in_poll / total) if settings.PRODUCTION: logging.info('Tornado %s %5.1f%% busy over the past %4.1f seconds' % (logging_data.get('port', 'unknown'), percent_busy, total)) self._last_print = t1 return result
[ "str", "float" ]
[ 1573, 1725 ]
[ 1576, 1730 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tornado/sharding.py
from django.conf import settings from zerver.models import Realm def get_tornado_port(realm: Realm) -> int: if settings.TORNADO_SERVER is None: return 9993 if settings.TORNADO_PROCESSES == 1: return int(settings.TORNADO_SERVER.split(":")[-1]) return 9993 def get_tornado_uri(realm: Realm) -> str: if settings.TORNADO_PROCESSES == 1: return settings.TORNADO_SERVER port = get_tornado_port(realm) return "http://127.0.0.1:%d" % (port,) def notify_tornado_queue_name(port: int) -> str: if settings.TORNADO_PROCESSES == 1: return "notify_tornado" return "notify_tornado_port_%d" % (port,) def tornado_return_queue_name(port: int) -> str: if settings.TORNADO_PROCESSES == 1: return "tornado_return" return "tornado_return_port_%d" % (port,)
[ "Realm", "Realm", "int", "int" ]
[ 95, 313, 523, 691 ]
[ 100, 318, 526, 694 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tornado/socket.py
from typing import Any, Dict, Mapping, Optional, Union from django.conf import settings from django.utils.timezone import now as timezone_now from django.utils.translation import ugettext as _ from django.contrib.sessions.models import Session as djSession try: from django.middleware.csrf import _compare_salted_tokens except ImportError: # This function was added in Django 1.10. def _compare_salted_tokens(token1: str, token2: str) -> bool: return token1 == token2 import sockjs.tornado from sockjs.tornado.session import ConnectionInfo import tornado.ioloop import ujson import logging import time from zerver.models import UserProfile, get_user_profile_by_id, get_client from zerver.lib.queue import queue_json_publish from zerver.lib.actions import check_send_message, extract_recipients from zerver.decorator import JsonableError from zerver.middleware import record_request_start_data, record_request_stop_data, \ record_request_restart_data, write_log_line, format_timedelta from zerver.lib.redis_utils import get_redis_client from zerver.lib.sessions import get_session_user from zerver.tornado.event_queue import get_client_descriptor from zerver.tornado.exceptions import BadEventQueueIdError from zerver.tornado.sharding import tornado_return_queue_name logger = logging.getLogger('zulip.socket') def get_user_profile(session_id: Optional[str]) -> Optional[UserProfile]: if session_id is None: return None try: djsession = djSession.objects.get(expire_date__gt=timezone_now(), session_key=session_id) except djSession.DoesNotExist: return None try: return get_user_profile_by_id(get_session_user(djsession)) except (UserProfile.DoesNotExist, KeyError): return None connections = dict() # type: Dict[Union[int, str], 'SocketConnection'] def get_connection(id: Union[int, str]) -> Optional['SocketConnection']: return connections.get(id) def register_connection(id: Union[int, str], conn: 'SocketConnection') -> None: # Kill any old connections if they exist if id in connections: connections[id].close() conn.client_id = id connections[conn.client_id] = conn def deregister_connection(conn: 'SocketConnection') -> None: assert conn.client_id is not None del connections[conn.client_id] redis_client = get_redis_client() def req_redis_key(req_id: str) -> str: return 'socket_req_status:%s' % (req_id,) class CloseErrorInfo: def __init__(self, status_code: int, err_msg: str) -> None: self.status_code = status_code self.err_msg = err_msg class SocketConnection(sockjs.tornado.SockJSConnection): client_id = None # type: Optional[Union[int, str]] def on_open(self, info: ConnectionInfo) -> None: log_data = dict(extra='[transport=%s]' % (self.session.transport_name,)) record_request_start_data(log_data) ioloop = tornado.ioloop.IOLoop.instance() self.authenticated = False self.session.user_profile = None self.close_info = None # type: Optional[CloseErrorInfo] self.did_close = False try: self.browser_session_id = info.get_cookie(settings.SESSION_COOKIE_NAME).value self.csrf_token = info.get_cookie(settings.CSRF_COOKIE_NAME).value except AttributeError: # The request didn't contain the necessary cookie values. We can't # close immediately because sockjs-tornado doesn't expect a close # inside on_open(), so do it on the next tick. self.close_info = CloseErrorInfo(403, "Initial cookie lacked required values") ioloop.add_callback(self.close) return def auth_timeout() -> None: self.close_info = CloseErrorInfo(408, "Timeout while waiting for authentication") self.close() self.timeout_handle = ioloop.call_later(10, auth_timeout) write_log_line(log_data, path='/socket/open', method='SOCKET', remote_ip=info.ip, email='unknown', client_name='?') def authenticate_client(self, msg: Dict[str, Any]) -> None: if self.authenticated: self.session.send_message({'req_id': msg['req_id'], 'type': 'response', 'response': {'result': 'error', 'msg': 'Already authenticated'}}) return user_profile = get_user_profile(self.browser_session_id) if user_profile is None: raise JsonableError(_('Unknown or missing session')) self.session.user_profile = user_profile if 'csrf_token' not in msg['request']: # Debugging code to help with understanding #6961 logging.error("CSRF token missing from websockets auth request: %s" % (msg['request'],)) raise JsonableError(_('CSRF token entry missing from request')) if not _compare_salted_tokens(msg['request']['csrf_token'], self.csrf_token): raise JsonableError(_('CSRF token does not match that in cookie')) if 'queue_id' not in msg['request']: raise JsonableError(_("Missing 'queue_id' argument")) queue_id = msg['request']['queue_id'] client = get_client_descriptor(queue_id) if client is None: raise BadEventQueueIdError(queue_id) if user_profile.id != client.user_profile_id: raise JsonableError(_("You are not the owner of the queue with id '%s'") % (queue_id,)) self.authenticated = True register_connection(queue_id, self) response = {'req_id': msg['req_id'], 'type': 'response', 'response': {'result': 'success', 'msg': ''}} status_inquiries = msg['request'].get('status_inquiries') if status_inquiries is not None: results = {} # type: Dict[str, Dict[str, str]] for inquiry in status_inquiries: status = redis_client.hgetall(req_redis_key(inquiry)) # type: Dict[bytes, bytes] if len(status) == 0: result = {'status': 'not_received'} elif b'response' not in status: result = {'status': status[b'status'].decode('utf-8')} else: result = {'status': status[b'status'].decode('utf-8'), 'response': ujson.loads(status[b'response'])} results[str(inquiry)] = result response['response']['status_inquiries'] = results self.session.send_message(response) ioloop = tornado.ioloop.IOLoop.instance() ioloop.remove_timeout(self.timeout_handle) def on_message(self, msg_raw: str) -> None: log_data = dict(extra='[transport=%s' % (self.session.transport_name,)) record_request_start_data(log_data) msg = ujson.loads(msg_raw) if self.did_close: user_email = 'unknown' if self.session.user_profile is not None: user_email = self.session.user_profile.email logger.info("Received message on already closed socket! transport=%s user=%s client_id=%s" % (self.session.transport_name, user_email, self.client_id)) self.session.send_message({'req_id': msg['req_id'], 'type': 'ack'}) if msg['type'] == 'auth': log_data['extra'] += ']' try: self.authenticate_client(msg) # TODO: Fill in the correct client write_log_line(log_data, path='/socket/auth', method='SOCKET', remote_ip=self.session.conn_info.ip, email=self.session.user_profile.email, client_name='?') except JsonableError as e: response = e.to_json() self.session.send_message({'req_id': msg['req_id'], 'type': 'response', 'response': response}) write_log_line(log_data, path='/socket/auth', method='SOCKET', remote_ip=self.session.conn_info.ip, email='unknown', client_name='?', status_code=403, error_content=ujson.dumps(response)) return else: if not self.authenticated: response = {'result': 'error', 'msg': "Not yet authenticated"} self.session.send_message({'req_id': msg['req_id'], 'type': 'response', 'response': response}) write_log_line(log_data, path='/socket/service_request', method='SOCKET', remote_ip=self.session.conn_info.ip, email='unknown', client_name='?', status_code=403, error_content=ujson.dumps(response)) return redis_key = req_redis_key(msg['req_id']) with redis_client.pipeline() as pipeline: pipeline.hmset(redis_key, {'status': 'received'}) pipeline.expire(redis_key, 60 * 60 * 24) pipeline.execute() record_request_stop_data(log_data) request_environ = dict(REMOTE_ADDR=self.session.conn_info.ip) queue_json_publish("message_sender", dict(request=msg['request'], req_id=msg['req_id'], server_meta=dict(user_id=self.session.user_profile.id, client_id=self.client_id, return_queue=tornado_return_queue_name(self.port), log_data=log_data, request_environ=request_environ))) def on_close(self) -> None: log_data = dict(extra='[transport=%s]' % (self.session.transport_name,)) record_request_start_data(log_data) if self.close_info is not None: write_log_line(log_data, path='/socket/close', method='SOCKET', remote_ip=self.session.conn_info.ip, email='unknown', client_name='?', status_code=self.close_info.status_code, error_content=self.close_info.err_msg) else: deregister_connection(self) email = self.session.user_profile.email \ if self.session.user_profile is not None else 'unknown' write_log_line(log_data, path='/socket/close', method='SOCKET', remote_ip=self.session.conn_info.ip, email=email, client_name='?') self.did_close = True def respond_send_message(data: Mapping[str, Any]) -> None: log_data = data['server_meta']['log_data'] record_request_restart_data(log_data) worker_log_data = data['server_meta']['worker_log_data'] forward_queue_delay = worker_log_data['time_started'] - log_data['time_stopped'] return_queue_delay = log_data['time_restarted'] - data['server_meta']['time_request_finished'] service_time = data['server_meta']['time_request_finished'] - worker_log_data['time_started'] log_data['extra'] += ', queue_delay: %s/%s, service_time: %s]' % ( format_timedelta(forward_queue_delay), format_timedelta(return_queue_delay), format_timedelta(service_time)) client_id = data['server_meta']['client_id'] connection = get_connection(client_id) if connection is None: logger.info("Could not find connection to send response to! client_id=%s" % (client_id,)) else: connection.session.send_message({'req_id': data['req_id'], 'type': 'response', 'response': data['response']}) # TODO: Fill in client name # TODO: Maybe fill in the status code correctly write_log_line(log_data, path='/socket/service_request', method='SOCKET', remote_ip=connection.session.conn_info.ip, email=connection.session.user_profile.email, client_name='?') # We disable the eventsource and htmlfile transports because they cannot # securely send us the zulip.com cookie, which we use as part of our # authentication scheme. sockjs_url = '%s/static/third/sockjs/sockjs-0.3.4.js' % (settings.ROOT_DOMAIN_URI,) sockjs_router = sockjs.tornado.SockJSRouter(SocketConnection, "/sockjs", {'sockjs_url': sockjs_url, 'disabled_transports': ['eventsource', 'htmlfile']}) def get_sockjs_router(port: int) -> sockjs.tornado.SockJSRouter: sockjs_router._connection.port = port return sockjs_router
[ "str", "str", "Optional[str]", "Union[int, str]", "Union[int, str]", "'SocketConnection'", "'SocketConnection'", "str", "int", "str", "ConnectionInfo", "Dict[str, Any]", "str", "Mapping[str, Any]", "int" ]
[ 431, 444, 1373, 1909, 2019, 2042, 2271, 2436, 2554, 2568, 2795, 4164, 6786, 10947, 12839 ]
[ 434, 447, 1386, 1924, 2034, 2060, 2289, 2439, 2557, 2571, 2809, 4178, 6789, 10964, 12842 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tornado/views.py
import time from typing import Iterable, List, Optional, Sequence, Union import ujson from django.core.handlers.base import BaseHandler from django.http import HttpRequest, HttpResponse from django.utils.translation import ugettext as _ from zerver.decorator import REQ, RespondAsynchronously, \ _RespondAsynchronously, asynchronous, \ has_request_variables, internal_notify_view, process_client from zerver.lib.response import json_error, json_success from zerver.lib.validator import check_bool, check_list, check_string from zerver.models import Client, UserProfile, get_client, get_user_profile_by_id from zerver.tornado.event_queue import fetch_events, \ get_client_descriptor, process_notification from zerver.tornado.exceptions import BadEventQueueIdError @internal_notify_view(True) def notify(request: HttpRequest) -> HttpResponse: process_notification(ujson.loads(request.POST['data'])) return json_success() @has_request_variables def cleanup_event_queue(request: HttpRequest, user_profile: UserProfile, queue_id: str=REQ()) -> HttpResponse: client = get_client_descriptor(str(queue_id)) if client is None: raise BadEventQueueIdError(queue_id) if user_profile.id != client.user_profile_id: return json_error(_("You are not authorized to access this queue")) request._log_data['extra'] = "[%s]" % (queue_id,) client.cleanup() return json_success() @asynchronous @internal_notify_view(True) @has_request_variables def get_events_internal(request: HttpRequest, handler: BaseHandler, user_profile_id: int=REQ()) -> Union[HttpResponse, _RespondAsynchronously]: user_profile = get_user_profile_by_id(user_profile_id) request._email = user_profile.email process_client(request, user_profile, client_name="internal") return get_events_backend(request, user_profile, handler) @asynchronous def get_events(request: HttpRequest, user_profile: UserProfile, handler: BaseHandler) -> Union[HttpResponse, _RespondAsynchronously]: return get_events_backend(request, user_profile, handler) @has_request_variables def get_events_backend(request: HttpRequest, user_profile: UserProfile, handler: BaseHandler, user_client: Optional[Client]=REQ(converter=get_client, default=None), last_event_id: Optional[int]=REQ(converter=int, default=None), queue_id: Optional[List[str]]=REQ(default=None), apply_markdown: bool=REQ(default=False, validator=check_bool), client_gravatar: bool=REQ(default=False, validator=check_bool), all_public_streams: bool=REQ(default=False, validator=check_bool), event_types: Optional[str]=REQ(default=None, validator=check_list(check_string)), dont_block: bool=REQ(default=False, validator=check_bool), narrow: Iterable[Sequence[str]]=REQ(default=[], validator=check_list(None)), lifespan_secs: int=REQ(default=0, converter=int) ) -> Union[HttpResponse, _RespondAsynchronously]: if user_client is None: valid_user_client = request.client else: valid_user_client = user_client events_query = dict( user_profile_id = user_profile.id, user_profile_email = user_profile.email, queue_id = queue_id, last_event_id = last_event_id, event_types = event_types, client_type_name = valid_user_client.name, all_public_streams = all_public_streams, lifespan_secs = lifespan_secs, narrow = narrow, dont_block = dont_block, handler_id = handler.handler_id) if queue_id is None: events_query['new_queue_data'] = dict( user_profile_id = user_profile.id, realm_id = user_profile.realm_id, user_profile_email = user_profile.email, event_types = event_types, client_type_name = valid_user_client.name, apply_markdown = apply_markdown, client_gravatar = client_gravatar, all_public_streams = all_public_streams, queue_timeout = lifespan_secs, last_connection_time = time.time(), narrow = narrow) result = fetch_events(events_query) if "extra_log_data" in result: request._log_data['extra'] = result["extra_log_data"] if result["type"] == "async": handler._request = request return RespondAsynchronously if result["type"] == "error": raise result["exception"] return json_success(result["response"])
[ "HttpRequest", "HttpRequest", "UserProfile", "HttpRequest", "BaseHandler", "HttpRequest", "UserProfile", "BaseHandler", "HttpRequest", "UserProfile", "BaseHandler" ]
[ 827, 1000, 1027, 1546, 1568, 1947, 1974, 2011, 2190, 2217, 2239 ]
[ 838, 1011, 1038, 1557, 1579, 1958, 1985, 2022, 2201, 2228, 2250 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/tornado/websocket_client.py
import logging import requests import ujson from django.conf import settings from django.contrib.auth import SESSION_KEY, BACKEND_SESSION_KEY, HASH_SESSION_KEY from django.middleware.csrf import _get_new_csrf_token from importlib import import_module from tornado.ioloop import IOLoop from tornado import gen from tornado.httpclient import HTTPRequest from tornado.websocket import websocket_connect, WebSocketClientConnection from urllib.parse import urlparse, urlunparse, urljoin from http.cookies import SimpleCookie from zerver.models import get_system_bot from typing import Any, Callable, Dict, Generator, Iterable, Optional class WebsocketClient: def __init__(self, host_url: str, sockjs_url: str, sender_email: str, run_on_start: Callable[..., None], validate_ssl: bool=True, **run_kwargs: Any) -> None: # NOTE: Callable should take a WebsocketClient & kwargs, but this is not standardised self.validate_ssl = validate_ssl self.auth_email = sender_email self.user_profile = get_system_bot(sender_email) self.request_id_number = 0 self.parsed_host_url = urlparse(host_url) self.sockjs_url = sockjs_url self.cookie_dict = self._login() self.cookie_str = self._get_cookie_header(self.cookie_dict) self.events_data = self._get_queue_events(self.cookie_str) self.ioloop_instance = IOLoop.instance() self.run_on_start = run_on_start self.run_kwargs = run_kwargs self.scheme_dict = {'http': 'ws', 'https': 'wss'} self.ws = None # type: Optional[WebSocketClientConnection] def _login(self) -> Dict[str, str]: # Ideally, we'd migrate this to use API auth instead of # stealing cookies, but this works for now. auth_backend = settings.AUTHENTICATION_BACKENDS[0] session_auth_hash = self.user_profile.get_session_auth_hash() engine = import_module(settings.SESSION_ENGINE) session = engine.SessionStore() # type: ignore # import_module session[SESSION_KEY] = self.user_profile._meta.pk.value_to_string(self.user_profile) session[BACKEND_SESSION_KEY] = auth_backend session[HASH_SESSION_KEY] = session_auth_hash session.save() return { settings.SESSION_COOKIE_NAME: session.session_key, settings.CSRF_COOKIE_NAME: _get_new_csrf_token()} def _get_cookie_header(self, cookies: Dict[Any, Any]) -> str: return ';'.join( ["{}={}".format(name, value) for name, value in cookies.items()]) @gen.coroutine def _websocket_auth(self, queue_events_data: Dict[str, Dict[str, str]], cookies: SimpleCookie) -> Generator[str, str, None]: message = { "req_id": self._get_request_id(), "type": "auth", "request": { "csrf_token": cookies.get(settings.CSRF_COOKIE_NAME), "queue_id": queue_events_data['queue_id'], "status_inquiries": [] } } auth_frame_str = ujson.dumps(message) self.ws.write_message(ujson.dumps([auth_frame_str])) response_ack = yield self.ws.read_message() response_message = yield self.ws.read_message() raise gen.Return([response_ack, response_message]) def _get_queue_events(self, cookies_header: str) -> Dict[str, str]: url = urljoin(self.parsed_host_url.geturl(), '/json/events?dont_block=true') response = requests.get(url, headers={'Cookie': cookies_header}, verify=self.validate_ssl) return response.json() @gen.engine def connect(self) -> Generator[str, WebSocketClientConnection, None]: try: request = HTTPRequest(url=self._get_websocket_url(), validate_cert=self.validate_ssl) request.headers.add('Cookie', self.cookie_str) self.ws = yield websocket_connect(request) yield self.ws.read_message() yield self._websocket_auth(self.events_data, self.cookie_dict) self.run_on_start(self, **self.run_kwargs) except Exception as e: logging.exception(str(e)) IOLoop.instance().stop() IOLoop.instance().stop() @gen.coroutine def send_message(self, client: str, type: str, subject: str, stream: str, private_message_recepient: str, content: str="") -> Generator[str, WebSocketClientConnection, None]: user_message = { "req_id": self._get_request_id(), "type": "request", "request": { "client": client, "type": type, "subject": subject, "stream": stream, "private_message_recipient": private_message_recepient, "content": content, "sender_id": self.user_profile.id, "queue_id": self.events_data['queue_id'], "to": ujson.dumps([private_message_recepient]), "reply_to": self.user_profile.email, "local_id": -1 } } self.ws.write_message(ujson.dumps([ujson.dumps(user_message)])) response_ack = yield self.ws.read_message() response_message = yield self.ws.read_message() raise gen.Return([response_ack, response_message]) def run(self) -> None: self.ioloop_instance.add_callback(self.connect) self.ioloop_instance.start() def _get_websocket_url(self) -> str: return '{}://{}{}'.format(self.scheme_dict[self.parsed_host_url.scheme], self.parsed_host_url.netloc, self.sockjs_url) def _get_request_id(self) -> Iterable[str]: self.request_id_number += 1 return ':'.join((self.events_data['queue_id'], str(self.request_id_number)))
[ "str", "str", "str", "Callable[..., None]", "Any", "Dict[Any, Any]", "Dict[str, Dict[str, str]]", "SimpleCookie", "str", "str", "str", "str", "str", "str" ]
[ 692, 709, 728, 764, 841, 2459, 2655, 2715, 3393, 4313, 4324, 4338, 4351, 4404 ]
[ 695, 712, 731, 783, 844, 2473, 2680, 2727, 3396, 4316, 4327, 4341, 4354, 4407 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/views/__init__.py
[]
[]
[]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/views/alert_words.py
from django.http import HttpResponse, HttpRequest from typing import List from zerver.models import UserProfile from zerver.lib.request import has_request_variables, REQ from zerver.lib.response import json_success from zerver.lib.validator import check_list, check_string from zerver.lib.actions import do_add_alert_words, do_remove_alert_words from zerver.lib.alert_words import user_alert_words def list_alert_words(request: HttpRequest, user_profile: UserProfile) -> HttpResponse: return json_success({'alert_words': user_alert_words(user_profile)}) def clean_alert_words(alert_words: List[str]) -> List[str]: alert_words = [w.strip() for w in alert_words] return [w for w in alert_words if w != ""] @has_request_variables def add_alert_words(request: HttpRequest, user_profile: UserProfile, alert_words: List[str]=REQ(validator=check_list(check_string)) ) -> HttpResponse: do_add_alert_words(user_profile, clean_alert_words(alert_words)) return json_success({'alert_words': user_alert_words(user_profile)}) @has_request_variables def remove_alert_words(request: HttpRequest, user_profile: UserProfile, alert_words: List[str]=REQ(validator=check_list(check_string)) ) -> HttpResponse: do_remove_alert_words(user_profile, alert_words) return json_success({'alert_words': user_alert_words(user_profile)})
[ "HttpRequest", "UserProfile", "List[str]", "HttpRequest", "UserProfile", "HttpRequest", "UserProfile" ]
[ 433, 460, 599, 775, 802, 1135, 1162 ]
[ 444, 471, 608, 786, 813, 1146, 1173 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/views/archive.py
from typing import List from django.http import HttpRequest, HttpResponse from django.shortcuts import render from django.template import loader from zerver.lib.streams import get_stream_by_id from zerver.models import Message, UserProfile, get_stream_recipient from zerver.lib.avatar import get_gravatar_url from zerver.lib.response import json_success from zerver.lib.timestamp import datetime_to_timestamp from zerver.lib.topic import ( get_topic_history_for_web_public_stream, messages_for_topic, ) from zerver.lib.exceptions import JsonableError def archive(request: HttpRequest, stream_id: int, topic_name: str) -> HttpResponse: def get_response(rendered_message_list: List[str], is_web_public: bool, stream_name: str) -> HttpResponse: return render( request, 'zerver/archive/index.html', context={ 'is_web_public': is_web_public, 'message_list': rendered_message_list, 'stream': stream_name, 'topic': topic_name, } ) try: stream = get_stream_by_id(stream_id) except JsonableError: return get_response([], False, '') if not stream.is_web_public: return get_response([], False, '') all_messages = list( messages_for_topic( stream_id=stream_id, topic_name=topic_name, ).select_related('sender').order_by('pub_date') ) if not all_messages: return get_response([], True, stream.name) rendered_message_list = [] prev_sender = None for msg in all_messages: include_sender = False status_message = Message.is_status_message(msg.content, msg.rendered_content) if not prev_sender or prev_sender != msg.sender or status_message: if status_message: prev_sender = None else: prev_sender = msg.sender include_sender = True if status_message: status_message = msg.rendered_content[4+3: -4] context = { 'sender_full_name': msg.sender.full_name, 'timestampstr': datetime_to_timestamp(msg.last_edit_time if msg.last_edit_time else msg.pub_date), 'message_content': msg.rendered_content, 'avatar_url': get_gravatar_url(msg.sender.email, 1), 'include_sender': include_sender, 'status_message': status_message, } rendered_msg = loader.render_to_string('zerver/archive/single_message.html', context) rendered_message_list.append(rendered_msg) return get_response(rendered_message_list, True, stream.name) def get_web_public_topics_backend(request: HttpRequest, stream_id: int) -> HttpResponse: try: stream = get_stream_by_id(stream_id) except JsonableError: return json_success(dict(topics=[])) if not stream.is_web_public: return json_success(dict(topics=[])) recipient = get_stream_recipient(stream.id) result = get_topic_history_for_web_public_stream(recipient=recipient) return json_success(dict(topics=result))
[ "HttpRequest", "int", "str", "List[str]", "bool", "str", "HttpRequest", "int" ]
[ 583, 619, 648, 715, 762, 802, 2877, 2901 ]
[ 594, 622, 651, 724, 766, 805, 2888, 2904 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/views/attachments.py
from django.http import HttpRequest, HttpResponse from zerver.models import UserProfile from zerver.lib.actions import notify_attachment_update from zerver.lib.validator import check_int from zerver.lib.response import json_success from zerver.lib.attachments import user_attachments, remove_attachment, \ access_attachment_by_id def list_by_user(request: HttpRequest, user_profile: UserProfile) -> HttpResponse: return json_success({"attachments": user_attachments(user_profile)}) def remove(request: HttpRequest, user_profile: UserProfile, attachment_id: int) -> HttpResponse: attachment = access_attachment_by_id(user_profile, attachment_id, needs_owner=True) notify_attachment_update(user_profile, "remove", {"id": attachment.id}) remove_attachment(user_profile, attachment) return json_success()
[ "HttpRequest", "UserProfile", "HttpRequest", "UserProfile", "int" ]
[ 363, 390, 515, 542, 570 ]
[ 374, 401, 526, 553, 573 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/views/auth.py
from django.forms import Form from django.conf import settings from django.core.exceptions import ValidationError from django.core.validators import validate_email from django.contrib.auth import authenticate, get_backends from django.contrib.auth.views import login as django_login_page, \ logout_then_login as django_logout_then_login from django.contrib.auth.views import password_reset as django_password_reset from django.urls import reverse from zerver.decorator import authenticated_json_post_view, require_post, \ process_client, do_login, log_view_func from django.http import HttpRequest, HttpResponse, HttpResponseRedirect, \ HttpResponseNotFound from django.template.response import SimpleTemplateResponse from django.middleware.csrf import get_token from django.shortcuts import redirect, render from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_GET from django.utils.translation import ugettext as _ from django.utils.http import is_safe_url from django.core import signing import urllib from typing import Any, Dict, List, Optional, Tuple from confirmation.models import Confirmation, create_confirmation_link from zerver.context_processors import zulip_default_context, get_realm_from_request from zerver.forms import HomepageForm, OurAuthenticationForm, \ WRONG_SUBDOMAIN_ERROR, ZulipPasswordResetForm, AuthenticationTokenForm from zerver.lib.mobile_auth_otp import is_valid_otp, otp_encrypt_api_key from zerver.lib.push_notifications import push_notifications_enabled from zerver.lib.request import REQ, has_request_variables, JsonableError from zerver.lib.response import json_success, json_error from zerver.lib.subdomains import get_subdomain, is_subdomain_root_or_alias from zerver.lib.users import get_api_key from zerver.lib.validator import validate_login_email from zerver.models import PreregistrationUser, UserProfile, remote_user_to_email, Realm, \ get_realm from zerver.signals import email_on_new_login from zproject.backends import password_auth_enabled, dev_auth_enabled, \ github_auth_enabled, google_auth_enabled, ldap_auth_enabled, \ ZulipLDAPConfigurationError, ZulipLDAPAuthBackend, email_auth_enabled, \ remote_auth_enabled from version import ZULIP_VERSION import hashlib import hmac import jwt import logging import requests import time import ujson from two_factor.forms import BackupTokenForm from two_factor.views import LoginView as BaseTwoFactorLoginView ExtraContext = Optional[Dict[str, Any]] def get_safe_redirect_to(url: str, redirect_host: str) -> str: is_url_safe = is_safe_url(url=url, host=redirect_host) if is_url_safe: return urllib.parse.urljoin(redirect_host, url) else: return redirect_host def create_preregistration_user(email: str, request: HttpRequest, realm_creation: bool=False, password_required: bool=True) -> HttpResponse: realm = None if not realm_creation: realm = get_realm(get_subdomain(request)) return PreregistrationUser.objects.create(email=email, realm_creation=realm_creation, password_required=password_required, realm=realm) def maybe_send_to_registration(request: HttpRequest, email: str, full_name: str='', is_signup: bool=False, password_required: bool=True) -> HttpResponse: realm = get_realm(get_subdomain(request)) from_multiuse_invite = False multiuse_obj = None streams_to_subscribe = None multiuse_object_key = request.session.get("multiuse_object_key", None) if multiuse_object_key is not None: from_multiuse_invite = True multiuse_obj = Confirmation.objects.get(confirmation_key=multiuse_object_key).content_object realm = multiuse_obj.realm streams_to_subscribe = multiuse_obj.streams.all() form = HomepageForm({'email': email}, realm=realm, from_multiuse_invite=from_multiuse_invite) if form.is_valid(): # Construct a PreregistrationUser object and send the user over to # the confirmation view. prereg_user = None if settings.ONLY_SSO: try: prereg_user = PreregistrationUser.objects.filter( email__iexact=email, realm=realm).latest("invited_at") except PreregistrationUser.DoesNotExist: prereg_user = create_preregistration_user(email, request, password_required=password_required) else: prereg_user = create_preregistration_user(email, request, password_required=password_required) if multiuse_object_key is not None: del request.session["multiuse_object_key"] request.session.modified = True if streams_to_subscribe is not None: prereg_user.streams.set(streams_to_subscribe) confirmation_link = "".join(( create_confirmation_link(prereg_user, request.get_host(), Confirmation.USER_REGISTRATION), '?full_name=', # urllib does not handle Unicode, so coerece to encoded byte string # Explanation: http://stackoverflow.com/a/5605354/90777 urllib.parse.quote_plus(full_name.encode('utf8')))) if is_signup: return redirect(confirmation_link) context = {'email': email, 'continue_link': confirmation_link} return render(request, 'zerver/confirm_continue_registration.html', context=context) else: url = reverse('register') return render(request, 'zerver/accounts_home.html', context={'form': form, 'current_url': lambda: url, 'from_multiuse_invite': from_multiuse_invite}, ) def redirect_to_subdomain_login_url() -> HttpResponseRedirect: login_url = reverse('django.contrib.auth.views.login') redirect_url = login_url + '?subdomain=1' return HttpResponseRedirect(redirect_url) def redirect_to_config_error(error_type: str) -> HttpResponseRedirect: return HttpResponseRedirect("/config-error/%s" % (error_type,)) def login_or_register_remote_user(request: HttpRequest, remote_username: Optional[str], user_profile: Optional[UserProfile], full_name: str='', invalid_subdomain: bool=False, mobile_flow_otp: Optional[str]=None, is_signup: bool=False, redirect_to: str='') -> HttpResponse: if user_profile is None or user_profile.is_mirror_dummy: # We have verified the user controls an email address # (remote_username) but there's no associated Zulip user # account. Consider sending the request to registration. return maybe_send_to_registration(request, remote_user_to_email(remote_username), full_name, password_required=False, is_signup=is_signup) # Otherwise, the user has successfully authenticated to an # account, and we need to do the right thing depending whether # or not they're using the mobile OTP flow or want a browser session. if mobile_flow_otp is not None: # For the mobile Oauth flow, we send the API key and other # necessary details in a redirect to a zulip:// URI scheme. api_key = get_api_key(user_profile) params = { 'otp_encrypted_api_key': otp_encrypt_api_key(api_key, mobile_flow_otp), 'email': remote_username, 'realm': user_profile.realm.uri, } # We can't use HttpResponseRedirect, since it only allows HTTP(S) URLs response = HttpResponse(status=302) response['Location'] = 'zulip://login?' + urllib.parse.urlencode(params) # Maybe sending 'user_logged_in' signal is the better approach: # user_logged_in.send(sender=user_profile.__class__, request=request, user=user_profile) # Not doing this only because over here we don't add the user information # in the session. If the signal receiver assumes that we do then that # would cause problems. email_on_new_login(sender=user_profile.__class__, request=request, user=user_profile) # Mark this request as having a logged-in user for our server logs. process_client(request, user_profile) request._email = user_profile.email return response do_login(request, user_profile) redirect_to = get_safe_redirect_to(redirect_to, user_profile.realm.uri) return HttpResponseRedirect(redirect_to) @log_view_func @has_request_variables def remote_user_sso(request: HttpRequest, mobile_flow_otp: Optional[str]=REQ(default=None)) -> HttpResponse: try: remote_user = request.META["REMOTE_USER"] except KeyError: # TODO: Arguably the JsonableError values here should be # full-page HTML configuration errors instead. raise JsonableError(_("No REMOTE_USER set.")) # Django invokes authenticate methods by matching arguments, and this # authentication flow will not invoke LDAP authentication because of # this condition of Django so no need to check if LDAP backend is # enabled. validate_login_email(remote_user_to_email(remote_user)) # Here we support the mobile flow for REMOTE_USER_BACKEND; we # validate the data format and then pass it through to # login_or_register_remote_user if appropriate. if mobile_flow_otp is not None: if not is_valid_otp(mobile_flow_otp): raise JsonableError(_("Invalid OTP")) subdomain = get_subdomain(request) realm = get_realm(subdomain) # Since RemoteUserBackend will return None if Realm is None, we # don't need to check whether `get_realm` returned None. return_data = {} # type: Dict[str, Any] user_profile = authenticate(remote_user=remote_user, realm=realm, return_data=return_data) redirect_to = request.GET.get('next', '') return login_or_register_remote_user(request, remote_user, user_profile, invalid_subdomain = bool(return_data.get("invalid_subdomain")), mobile_flow_otp=mobile_flow_otp, redirect_to=redirect_to) @csrf_exempt @log_view_func def remote_user_jwt(request: HttpRequest) -> HttpResponse: subdomain = get_subdomain(request) try: auth_key = settings.JWT_AUTH_KEYS[subdomain] except KeyError: raise JsonableError(_("Auth key for this subdomain not found.")) try: json_web_token = request.POST["json_web_token"] options = {'verify_signature': True} payload = jwt.decode(json_web_token, auth_key, options=options) except KeyError: raise JsonableError(_("No JSON web token passed in request")) except jwt.InvalidTokenError: raise JsonableError(_("Bad JSON web token")) remote_user = payload.get("user", None) if remote_user is None: raise JsonableError(_("No user specified in JSON web token claims")) email_domain = payload.get('realm', None) if email_domain is None: raise JsonableError(_("No organization specified in JSON web token claims")) email = "%s@%s" % (remote_user, email_domain) realm = get_realm(subdomain) if realm is None: raise JsonableError(_("Wrong subdomain")) try: # We do all the authentication we need here (otherwise we'd have to # duplicate work), but we need to call authenticate with some backend so # that the request.backend attribute gets set. return_data = {} # type: Dict[str, bool] user_profile = authenticate(username=email, realm=realm, return_data=return_data, use_dummy_backend=True) except UserProfile.DoesNotExist: user_profile = None return login_or_register_remote_user(request, email, user_profile, remote_user) def google_oauth2_csrf(request: HttpRequest, value: str) -> str: # In Django 1.10, get_token returns a salted token which changes # every time get_token is called. from django.middleware.csrf import _unsalt_cipher_token token = _unsalt_cipher_token(get_token(request)) return hmac.new(token.encode('utf-8'), value.encode("utf-8"), hashlib.sha256).hexdigest() def reverse_on_root(viewname: str, args: List[str]=None, kwargs: Dict[str, str]=None) -> str: return settings.ROOT_DOMAIN_URI + reverse(viewname, args=args, kwargs=kwargs) def oauth_redirect_to_root(request: HttpRequest, url: str, sso_type: str, is_signup: bool=False) -> HttpResponse: main_site_uri = settings.ROOT_DOMAIN_URI + url if settings.SOCIAL_AUTH_SUBDOMAIN is not None and sso_type == 'social': main_site_uri = (settings.EXTERNAL_URI_SCHEME + settings.SOCIAL_AUTH_SUBDOMAIN + "." + settings.EXTERNAL_HOST) + url params = { 'subdomain': get_subdomain(request), 'is_signup': '1' if is_signup else '0', } # mobile_flow_otp is a one-time pad provided by the app that we # can use to encrypt the API key when passing back to the app. mobile_flow_otp = request.GET.get('mobile_flow_otp') if mobile_flow_otp is not None: if not is_valid_otp(mobile_flow_otp): raise JsonableError(_("Invalid OTP")) params['mobile_flow_otp'] = mobile_flow_otp next = request.GET.get('next') if next: params['next'] = next return redirect(main_site_uri + '?' + urllib.parse.urlencode(params)) def start_google_oauth2(request: HttpRequest) -> HttpResponse: url = reverse('zerver.views.auth.send_oauth_request_to_google') if not (settings.GOOGLE_OAUTH2_CLIENT_ID and settings.GOOGLE_OAUTH2_CLIENT_SECRET): return redirect_to_config_error("google") is_signup = bool(request.GET.get('is_signup')) return oauth_redirect_to_root(request, url, 'google', is_signup=is_signup) def start_social_login(request: HttpRequest, backend: str) -> HttpResponse: backend_url = reverse('social:begin', args=[backend]) if (backend == "github") and not (settings.SOCIAL_AUTH_GITHUB_KEY and settings.SOCIAL_AUTH_GITHUB_SECRET): return redirect_to_config_error("github") return oauth_redirect_to_root(request, backend_url, 'social') def start_social_signup(request: HttpRequest, backend: str) -> HttpResponse: backend_url = reverse('social:begin', args=[backend]) return oauth_redirect_to_root(request, backend_url, 'social', is_signup=True) def send_oauth_request_to_google(request: HttpRequest) -> HttpResponse: subdomain = request.GET.get('subdomain', '') is_signup = request.GET.get('is_signup', '') next = request.GET.get('next', '') mobile_flow_otp = request.GET.get('mobile_flow_otp', '0') if ((settings.ROOT_DOMAIN_LANDING_PAGE and subdomain == '') or not Realm.objects.filter(string_id=subdomain).exists()): return redirect_to_subdomain_login_url() google_uri = 'https://accounts.google.com/o/oauth2/auth?' cur_time = str(int(time.time())) csrf_state = '%s:%s:%s:%s:%s' % (cur_time, subdomain, mobile_flow_otp, is_signup, next) # Now compute the CSRF hash with the other parameters as an input csrf_state += ":%s" % (google_oauth2_csrf(request, csrf_state),) params = { 'response_type': 'code', 'client_id': settings.GOOGLE_OAUTH2_CLIENT_ID, 'redirect_uri': reverse_on_root('zerver.views.auth.finish_google_oauth2'), 'scope': 'profile email', 'state': csrf_state, 'prompt': 'select_account', } return redirect(google_uri + urllib.parse.urlencode(params)) @log_view_func def finish_google_oauth2(request: HttpRequest) -> HttpResponse: error = request.GET.get('error') if error == 'access_denied': return redirect('/') elif error is not None: logging.warning('Error from google oauth2 login: %s' % (request.GET.get("error"),)) return HttpResponse(status=400) csrf_state = request.GET.get('state') if csrf_state is None or len(csrf_state.split(':')) != 6: logging.warning('Missing Google oauth2 CSRF state') return HttpResponse(status=400) (csrf_data, hmac_value) = csrf_state.rsplit(':', 1) if hmac_value != google_oauth2_csrf(request, csrf_data): logging.warning('Google oauth2 CSRF error') return HttpResponse(status=400) cur_time, subdomain, mobile_flow_otp, is_signup, next = csrf_data.split(':') if mobile_flow_otp == '0': mobile_flow_otp = None is_signup = bool(is_signup == '1') resp = requests.post( 'https://www.googleapis.com/oauth2/v3/token', data={ 'code': request.GET.get('code'), 'client_id': settings.GOOGLE_OAUTH2_CLIENT_ID, 'client_secret': settings.GOOGLE_OAUTH2_CLIENT_SECRET, 'redirect_uri': reverse_on_root('zerver.views.auth.finish_google_oauth2'), 'grant_type': 'authorization_code', }, ) if resp.status_code == 400: logging.warning('User error converting Google oauth2 login to token: %s' % (resp.text,)) return HttpResponse(status=400) elif resp.status_code != 200: logging.error('Could not convert google oauth2 code to access_token: %s' % (resp.text,)) return HttpResponse(status=400) access_token = resp.json()['access_token'] resp = requests.get( 'https://www.googleapis.com/plus/v1/people/me', params={'access_token': access_token} ) if resp.status_code == 400: logging.warning('Google login failed making info API call: %s' % (resp.text,)) return HttpResponse(status=400) elif resp.status_code != 200: logging.error('Google login failed making API call: %s' % (resp.text,)) return HttpResponse(status=400) body = resp.json() try: full_name = body['name']['formatted'] except KeyError: # Only google+ users have a formatted name. I am ignoring i18n here. full_name = '{} {}'.format( body['name']['givenName'], body['name']['familyName'] ) for email in body['emails']: if email['type'] == 'account': break else: logging.error('Google oauth2 account email not found: %s' % (body,)) return HttpResponse(status=400) email_address = email['value'] try: realm = Realm.objects.get(string_id=subdomain) except Realm.DoesNotExist: # nocoverage return redirect_to_subdomain_login_url() if mobile_flow_otp is not None: # When request was not initiated from subdomain. user_profile, return_data = authenticate_remote_user(realm, email_address) invalid_subdomain = bool(return_data.get('invalid_subdomain')) return login_or_register_remote_user(request, email_address, user_profile, full_name, invalid_subdomain, mobile_flow_otp=mobile_flow_otp, is_signup=is_signup, redirect_to=next) return redirect_and_log_into_subdomain( realm, full_name, email_address, is_signup=is_signup, redirect_to=next) def authenticate_remote_user(realm: Realm, email_address: str) -> Tuple[UserProfile, Dict[str, Any]]: return_data = {} # type: Dict[str, bool] if email_address is None: # No need to authenticate if email address is None. We already # know that user_profile would be None as well. In fact, if we # call authenticate in this case, we might get an exception from # ZulipDummyBackend which doesn't accept a None as a username. logging.warning("Email address was None while trying to authenticate " "remote user.") return None, return_data user_profile = authenticate(username=email_address, realm=realm, use_dummy_backend=True, return_data=return_data) return user_profile, return_data _subdomain_token_salt = 'zerver.views.auth.log_into_subdomain' @log_view_func def log_into_subdomain(request: HttpRequest, token: str) -> HttpResponse: try: data = signing.loads(token, salt=_subdomain_token_salt, max_age=15) except signing.SignatureExpired as e: logging.warning('Subdomain cookie: {}'.format(e)) return HttpResponse(status=400) except signing.BadSignature: logging.warning('Subdomain cookie: Bad signature.') return HttpResponse(status=400) subdomain = get_subdomain(request) if data['subdomain'] != subdomain: logging.warning('Login attempt on invalid subdomain') return HttpResponse(status=400) email_address = data['email'] full_name = data['name'] is_signup = data['is_signup'] redirect_to = data['next'] if is_signup: # If we are signing up, user_profile should be None. In case # email_address already exists, user will get an error message. user_profile = None return_data = {} # type: Dict[str, Any] else: # We can be reasonably confident that this subdomain actually # has a corresponding realm, since it was referenced in a # signed cookie. But we probably should add some error # handling for the case where the realm disappeared in the # meantime. realm = get_realm(subdomain) user_profile, return_data = authenticate_remote_user(realm, email_address) invalid_subdomain = bool(return_data.get('invalid_subdomain')) return login_or_register_remote_user(request, email_address, user_profile, full_name, invalid_subdomain=invalid_subdomain, is_signup=is_signup, redirect_to=redirect_to) def redirect_and_log_into_subdomain(realm: Realm, full_name: str, email_address: str, is_signup: bool=False, redirect_to: str='') -> HttpResponse: data = {'name': full_name, 'email': email_address, 'subdomain': realm.subdomain, 'is_signup': is_signup, 'next': redirect_to} token = signing.dumps(data, salt=_subdomain_token_salt) subdomain_login_uri = (realm.uri + reverse('zerver.views.auth.log_into_subdomain', args=[token])) return redirect(subdomain_login_uri) def get_dev_users(realm: Optional[Realm]=None, extra_users_count: int=10) -> List[UserProfile]: # Development environments usually have only a few users, but # it still makes sense to limit how many extra users we render to # support performance testing with DevAuthBackend. if realm is not None: users_query = UserProfile.objects.select_related().filter(is_bot=False, is_active=True, realm=realm) else: users_query = UserProfile.objects.select_related().filter(is_bot=False, is_active=True) shakespearian_users = users_query.exclude(email__startswith='extrauser').order_by('email') extra_users = users_query.filter(email__startswith='extrauser').order_by('email') # Limit the number of extra users we offer by default extra_users = extra_users[0:extra_users_count] users = list(shakespearian_users) + list(extra_users) return users def redirect_to_misconfigured_ldap_notice(error_type: int) -> HttpResponse: if error_type == ZulipLDAPAuthBackend.REALM_IS_NONE_ERROR: url = reverse('ldap_error_realm_is_none') else: raise AssertionError("Invalid error type") return HttpResponseRedirect(url) def show_deactivation_notice(request: HttpRequest) -> HttpResponse: realm = get_realm_from_request(request) if realm and realm.deactivated: return render(request, "zerver/deactivated.html", context={"deactivated_domain_name": realm.name}) return HttpResponseRedirect(reverse('zerver.views.auth.login_page')) def redirect_to_deactivation_notice() -> HttpResponse: return HttpResponseRedirect(reverse('zerver.views.auth.show_deactivation_notice')) def add_dev_login_context(realm: Realm, context: Dict[str, Any]) -> None: users = get_dev_users(realm) context['current_realm'] = realm context['all_realms'] = Realm.objects.all() context['direct_admins'] = [u for u in users if u.is_realm_admin] context['guest_users'] = [u for u in users if u.is_guest] context['direct_users'] = [u for u in users if not (u.is_realm_admin or u.is_guest)] def update_login_page_context(request: HttpRequest, context: Dict[str, Any]) -> None: for key in ('email', 'subdomain', 'already_registered'): try: context[key] = request.GET[key] except KeyError: pass context['wrong_subdomain_error'] = WRONG_SUBDOMAIN_ERROR class TwoFactorLoginView(BaseTwoFactorLoginView): extra_context = None # type: ExtraContext form_list = ( ('auth', OurAuthenticationForm), ('token', AuthenticationTokenForm), ('backup', BackupTokenForm), ) def __init__(self, extra_context: ExtraContext=None, *args: Any, **kwargs: Any) -> None: self.extra_context = extra_context super().__init__(*args, **kwargs) def get_context_data(self, **kwargs: Any) -> Dict[str, Any]: context = super().get_context_data(**kwargs) if self.extra_context is not None: context.update(self.extra_context) update_login_page_context(self.request, context) realm = get_realm_from_request(self.request) redirect_to = realm.uri if realm else '/' context['next'] = self.request.GET.get('next', redirect_to) return context def done(self, form_list: List[Form], **kwargs: Any) -> HttpResponse: """ Login the user and redirect to the desired page. We need to override this function so that we can redirect to realm.uri instead of '/'. """ realm_uri = self.get_user().realm.uri # This mock.patch business is an unpleasant hack that we'd # ideally like to remove by instead patching the upstream # module to support better configurability of the # LOGIN_REDIRECT_URL setting. But until then, it works. We # import mock.patch here because mock has an expensive import # process involving pbr -> pkgresources (which is really slow). from mock import patch with patch.object(settings, 'LOGIN_REDIRECT_URL', realm_uri): return super().done(form_list, **kwargs) def login_page(request: HttpRequest, **kwargs: Any) -> HttpResponse: if settings.TWO_FACTOR_AUTHENTICATION_ENABLED: if request.user and request.user.is_verified(): return HttpResponseRedirect(request.user.realm.uri) elif request.user.is_authenticated: return HttpResponseRedirect(request.user.realm.uri) if is_subdomain_root_or_alias(request) and settings.ROOT_DOMAIN_LANDING_PAGE: redirect_url = reverse('zerver.views.registration.find_account') return HttpResponseRedirect(redirect_url) realm = get_realm_from_request(request) if realm and realm.deactivated: return redirect_to_deactivation_notice() extra_context = kwargs.pop('extra_context', {}) if dev_auth_enabled(): if 'new_realm' in request.POST: realm = get_realm(request.POST['new_realm']) else: realm = get_realm_from_request(request) add_dev_login_context(realm, extra_context) if realm and 'new_realm' in request.POST: # If we're switching realms, redirect to that realm, but # only if it actually exists. return HttpResponseRedirect(realm.uri) if 'username' in request.POST: extra_context['email'] = request.POST['username'] if settings.TWO_FACTOR_AUTHENTICATION_ENABLED: return start_two_factor_auth(request, extra_context=extra_context, **kwargs) try: template_response = django_login_page( request, authentication_form=OurAuthenticationForm, extra_context=extra_context, **kwargs) except ZulipLDAPConfigurationError as e: assert len(e.args) > 1 return redirect_to_misconfigured_ldap_notice(e.args[1]) if isinstance(template_response, SimpleTemplateResponse): # Only those responses that are rendered using a template have # context_data attribute. This attribute doesn't exist otherwise. It is # added in SimpleTemplateResponse class, which is a derived class of # HttpResponse. See django.template.response.SimpleTemplateResponse, # https://github.com/django/django/blob/master/django/template/response.py#L19. update_login_page_context(request, template_response.context_data) return template_response def start_two_factor_auth(request: HttpRequest, extra_context: ExtraContext=None, **kwargs: Any) -> HttpResponse: two_fa_form_field = 'two_factor_login_view-current_step' if two_fa_form_field not in request.POST: # Here we inject the 2FA step in the request context if it's missing to # force the user to go to the first step of 2FA authentication process. # This seems a bit hackish but simplifies things from testing point of # view. I don't think this can result in anything bad because all the # authentication logic runs after the auth step. # # If we don't do this, we will have to modify a lot of auth tests to # insert this variable in the request. request.POST = request.POST.copy() request.POST.update({two_fa_form_field: 'auth'}) """ This is how Django implements as_view(), so extra_context will be passed to the __init__ method of TwoFactorLoginView. def as_view(cls, **initkwargs): def view(request, *args, **kwargs): self = cls(**initkwargs) ... return view """ two_fa_view = TwoFactorLoginView.as_view(extra_context=extra_context, **kwargs) return two_fa_view(request, **kwargs) @csrf_exempt def dev_direct_login(request: HttpRequest, **kwargs: Any) -> HttpResponse: # This function allows logging in without a password and should only be called # in development environments. It may be called if the DevAuthBackend is included # in settings.AUTHENTICATION_BACKENDS if (not dev_auth_enabled()) or settings.PRODUCTION: # This check is probably not required, since authenticate would fail without # an enabled DevAuthBackend. return HttpResponseRedirect(reverse('dev_not_supported')) email = request.POST['direct_email'] subdomain = get_subdomain(request) realm = get_realm(subdomain) user_profile = authenticate(dev_auth_username=email, realm=realm) if user_profile is None: return HttpResponseRedirect(reverse('dev_not_supported')) do_login(request, user_profile) next = request.GET.get('next', '') redirect_to = get_safe_redirect_to(next, user_profile.realm.uri) return HttpResponseRedirect(redirect_to) @csrf_exempt @require_post @has_request_variables def api_dev_fetch_api_key(request: HttpRequest, username: str=REQ()) -> HttpResponse: """This function allows logging in without a password on the Zulip mobile apps when connecting to a Zulip development environment. It requires DevAuthBackend to be included in settings.AUTHENTICATION_BACKENDS. """ if not dev_auth_enabled() or settings.PRODUCTION: return json_error(_("Dev environment not enabled.")) # Django invokes authenticate methods by matching arguments, and this # authentication flow will not invoke LDAP authentication because of # this condition of Django so no need to check if LDAP backend is # enabled. validate_login_email(username) subdomain = get_subdomain(request) realm = get_realm(subdomain) return_data = {} # type: Dict[str, bool] user_profile = authenticate(dev_auth_username=username, realm=realm, return_data=return_data) if return_data.get("inactive_realm"): return json_error(_("This organization has been deactivated."), data={"reason": "realm deactivated"}, status=403) if return_data.get("inactive_user"): return json_error(_("Your account has been disabled."), data={"reason": "user disable"}, status=403) if user_profile is None: return json_error(_("This user is not registered."), data={"reason": "unregistered"}, status=403) do_login(request, user_profile) api_key = get_api_key(user_profile) return json_success({"api_key": api_key, "email": user_profile.email}) @csrf_exempt def api_dev_list_users(request: HttpRequest) -> HttpResponse: if not dev_auth_enabled() or settings.PRODUCTION: return json_error(_("Dev environment not enabled.")) users = get_dev_users() return json_success(dict(direct_admins=[dict(email=u.email, realm_uri=u.realm.uri) for u in users if u.is_realm_admin], direct_users=[dict(email=u.email, realm_uri=u.realm.uri) for u in users if not u.is_realm_admin])) @csrf_exempt @require_post @has_request_variables def api_fetch_api_key(request: HttpRequest, username: str=REQ(), password: str=REQ()) -> HttpResponse: return_data = {} # type: Dict[str, bool] subdomain = get_subdomain(request) realm = get_realm(subdomain) if username == "google-oauth2-token": # This code path is auth for the legacy Android app user_profile = authenticate(google_oauth2_token=password, realm=realm, return_data=return_data) else: if not ldap_auth_enabled(realm=get_realm_from_request(request)): # In case we don't authenticate against LDAP, check for a valid # email. LDAP backend can authenticate against a non-email. validate_login_email(username) user_profile = authenticate(username=username, password=password, realm=realm, return_data=return_data) if return_data.get("inactive_user"): return json_error(_("Your account has been disabled."), data={"reason": "user disable"}, status=403) if return_data.get("inactive_realm"): return json_error(_("This organization has been deactivated."), data={"reason": "realm deactivated"}, status=403) if return_data.get("password_auth_disabled"): return json_error(_("Password auth is disabled in your team."), data={"reason": "password auth disabled"}, status=403) if user_profile is None: if return_data.get("valid_attestation"): # We can leak that the user is unregistered iff # they present a valid authentication string for the user. return json_error(_("This user is not registered; do so from a browser."), data={"reason": "unregistered"}, status=403) return json_error(_("Your username or password is incorrect."), data={"reason": "incorrect_creds"}, status=403) # Maybe sending 'user_logged_in' signal is the better approach: # user_logged_in.send(sender=user_profile.__class__, request=request, user=user_profile) # Not doing this only because over here we don't add the user information # in the session. If the signal receiver assumes that we do then that # would cause problems. email_on_new_login(sender=user_profile.__class__, request=request, user=user_profile) # Mark this request as having a logged-in user for our server logs. process_client(request, user_profile) request._email = user_profile.email api_key = get_api_key(user_profile) return json_success({"api_key": api_key, "email": user_profile.email}) def get_auth_backends_data(request: HttpRequest) -> Dict[str, Any]: """Returns which authentication methods are enabled on the server""" subdomain = get_subdomain(request) try: realm = Realm.objects.get(string_id=subdomain) except Realm.DoesNotExist: # If not the root subdomain, this is an error if subdomain != Realm.SUBDOMAIN_FOR_ROOT_DOMAIN: raise JsonableError(_("Invalid subdomain")) # With the root subdomain, it's an error or not depending # whether ROOT_DOMAIN_LANDING_PAGE (which indicates whether # there are some realms without subdomains on this server) # is set. if settings.ROOT_DOMAIN_LANDING_PAGE: raise JsonableError(_("Subdomain required")) else: realm = None return { "password": password_auth_enabled(realm), "dev": dev_auth_enabled(realm), "email": email_auth_enabled(realm), "github": github_auth_enabled(realm), "google": google_auth_enabled(realm), "remoteuser": remote_auth_enabled(realm), "ldap": ldap_auth_enabled(realm), } @csrf_exempt def api_get_auth_backends(request: HttpRequest) -> HttpResponse: """Deprecated route; this is to be replaced by api_get_server_settings""" auth_backends = get_auth_backends_data(request) auth_backends['zulip_version'] = ZULIP_VERSION return json_success(auth_backends) @require_GET @csrf_exempt def api_get_server_settings(request: HttpRequest) -> HttpResponse: result = dict( authentication_methods=get_auth_backends_data(request), zulip_version=ZULIP_VERSION, push_notifications_enabled=push_notifications_enabled(), ) context = zulip_default_context(request) # IMPORTANT NOTE: # realm_name, realm_icon, etc. are not guaranteed to appear in the response. # * If they do, that means the server URL has only one realm on it # * If they don't, the server has multiple realms, and it's not clear which is # the requested realm, so we can't send back these data. for settings_item in [ "email_auth_enabled", "require_email_format_usernames", "realm_uri", "realm_name", "realm_icon", "realm_description"]: if context[settings_item] is not None: result[settings_item] = context[settings_item] return json_success(result) @has_request_variables def json_fetch_api_key(request: HttpRequest, user_profile: UserProfile, password: str=REQ(default='')) -> HttpResponse: subdomain = get_subdomain(request) realm = get_realm(subdomain) if password_auth_enabled(user_profile.realm): if not authenticate(username=user_profile.email, password=password, realm=realm): return json_error(_("Your username or password is incorrect.")) api_key = get_api_key(user_profile) return json_success({"api_key": api_key}) @csrf_exempt def api_fetch_google_client_id(request: HttpRequest) -> HttpResponse: if not settings.GOOGLE_CLIENT_ID: return json_error(_("GOOGLE_CLIENT_ID is not configured"), status=400) return json_success({"google_client_id": settings.GOOGLE_CLIENT_ID}) @require_post def logout_then_login(request: HttpRequest, **kwargs: Any) -> HttpResponse: return django_logout_then_login(request, kwargs) def password_reset(request: HttpRequest, **kwargs: Any) -> HttpResponse: realm = get_realm(get_subdomain(request)) if realm is None: # If trying to get to password reset on a subdomain that # doesn't exist, just go to find_account. redirect_url = reverse('zerver.views.registration.find_account') return HttpResponseRedirect(redirect_url) return django_password_reset(request, template_name='zerver/reset.html', password_reset_form=ZulipPasswordResetForm, post_reset_redirect='/accounts/password/reset/done/')
[ "str", "str", "str", "HttpRequest", "HttpRequest", "str", "str", "HttpRequest", "Optional[str]", "Optional[UserProfile]", "HttpRequest", "HttpRequest", "HttpRequest", "str", "str", "HttpRequest", "str", "str", "HttpRequest", "HttpRequest", "str", "HttpRequest", "str", "HttpRequest", "HttpRequest", "Realm", "str", "HttpRequest", "str", "Realm", "str", "str", "int", "HttpRequest", "Realm", "Dict[str, Any]", "HttpRequest", "Dict[str, Any]", "Any", "Any", "Any", "List[Form]", "Any", "HttpRequest", "Any", "HttpRequest", "Any", "HttpRequest", "Any", "HttpRequest", "HttpRequest", "HttpRequest", "HttpRequest", "HttpRequest", "HttpRequest", "HttpRequest", "UserProfile", "HttpRequest", "HttpRequest", "Any", "HttpRequest", "Any" ]
[ 2560, 2580, 2807, 2821, 3354, 3374, 6313, 6455, 6485, 6548, 8960, 10719, 12449, 12469, 12827, 13010, 13028, 13070, 14122, 14523, 14545, 14925, 14947, 15152, 16306, 19922, 19944, 20866, 20886, 22595, 22613, 22633, 24057, 24330, 24820, 24836, 25241, 25263, 25836, 25851, 25992, 26442, 26464, 27298, 27321, 29634, 29743, 30994, 31017, 32049, 33720, 34314, 37105, 38258, 38572, 39570, 39597, 40138, 40404, 40427, 40531, 40554 ]
[ 2563, 2583, 2810, 2832, 3365, 3377, 6316, 6466, 6498, 6569, 8971, 10730, 12460, 12472, 12830, 13021, 13031, 13073, 14133, 14534, 14548, 14936, 14950, 15163, 16317, 19927, 19947, 20877, 20889, 22600, 22616, 22636, 24060, 24341, 24825, 24850, 25252, 25277, 25839, 25854, 25995, 26452, 26467, 27309, 27324, 29645, 29746, 31005, 31020, 32060, 33731, 34325, 37116, 38269, 38583, 39581, 39608, 40149, 40415, 40430, 40542, 40557 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/views/compatibility.py
from django.http import HttpResponse, HttpRequest from typing import Any, List, Dict, Optional from zerver.lib.response import json_error, json_success from zerver.lib.user_agent import parse_user_agent def check_compatibility(request: HttpRequest) -> HttpResponse: user_agent = parse_user_agent(request.META["HTTP_USER_AGENT"]) if user_agent['name'] == "ZulipInvalid": return json_error("Client is too old") return json_success()
[ "HttpRequest" ]
[ 239 ]
[ 250 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/views/custom_profile_fields.py
from typing import Union, List, Dict, Optional, cast import logging import ujson from django.core.exceptions import ValidationError from django.db import IntegrityError, connection from django.http import HttpRequest, HttpResponse from django.utils.translation import ugettext as _ from zerver.decorator import require_realm_admin, human_users_only from zerver.lib.request import has_request_variables, REQ from zerver.lib.actions import (try_add_realm_custom_profile_field, do_remove_realm_custom_profile_field, try_update_realm_custom_profile_field, do_update_user_custom_profile_data, try_reorder_realm_custom_profile_fields, notify_user_update_custom_profile_data) from zerver.lib.response import json_success, json_error from zerver.lib.types import ProfileFieldData from zerver.lib.validator import (check_dict, check_list, check_int, validate_field_data, check_capped_string) from zerver.models import (custom_profile_fields_for_realm, UserProfile, CustomProfileFieldValue, CustomProfileField, custom_profile_fields_for_realm) from zerver.lib.exceptions import JsonableError from zerver.lib.users import validate_user_custom_profile_data def list_realm_custom_profile_fields(request: HttpRequest, user_profile: UserProfile) -> HttpResponse: fields = custom_profile_fields_for_realm(user_profile.realm_id) return json_success({'custom_fields': [f.as_dict() for f in fields]}) hint_validator = check_capped_string(CustomProfileField.HINT_MAX_LENGTH) name_validator = check_capped_string(CustomProfileField.NAME_MAX_LENGTH) def validate_field_name_and_hint(name: str, hint: str) -> None: if not name.strip(): raise JsonableError(_("Name cannot be blank.")) error = hint_validator('hint', hint) if error: raise JsonableError(error) error = name_validator('name', name) if error: raise JsonableError(error) @require_realm_admin @has_request_variables def create_realm_custom_profile_field(request: HttpRequest, user_profile: UserProfile, name: str=REQ(), hint: str=REQ(default=''), field_data: ProfileFieldData=REQ(default={}, converter=ujson.loads), field_type: int=REQ(validator=check_int)) -> HttpResponse: validate_field_name_and_hint(name, hint) field_types = [i[0] for i in CustomProfileField.FIELD_TYPE_CHOICES] if field_type not in field_types: return json_error(_("Invalid field type.")) # Choice type field must have at least have one choice if field_type == CustomProfileField.CHOICE and len(field_data) < 1: return json_error(_("Field must have at least one choice.")) error = validate_field_data(field_data) if error: return json_error(error) try: field = try_add_realm_custom_profile_field( realm=user_profile.realm, name=name, field_data=field_data, field_type=field_type, hint=hint, ) return json_success({'id': field.id}) except IntegrityError: return json_error(_("A field with that name already exists.")) @require_realm_admin def delete_realm_custom_profile_field(request: HttpRequest, user_profile: UserProfile, field_id: int) -> HttpResponse: try: field = CustomProfileField.objects.get(id=field_id) except CustomProfileField.DoesNotExist: return json_error(_('Field id {id} not found.').format(id=field_id)) do_remove_realm_custom_profile_field(realm=user_profile.realm, field=field) return json_success() @require_realm_admin @has_request_variables def update_realm_custom_profile_field(request: HttpRequest, user_profile: UserProfile, field_id: int, name: str=REQ(), hint: str=REQ(default=''), field_data: ProfileFieldData=REQ(default={}, converter=ujson.loads), ) -> HttpResponse: validate_field_name_and_hint(name, hint) error = validate_field_data(field_data) if error: return json_error(error) realm = user_profile.realm try: field = CustomProfileField.objects.get(realm=realm, id=field_id) except CustomProfileField.DoesNotExist: return json_error(_('Field id {id} not found.').format(id=field_id)) try: try_update_realm_custom_profile_field(realm, field, name, hint=hint, field_data=field_data) except IntegrityError: return json_error(_('A field with that name already exists.')) return json_success() @require_realm_admin @has_request_variables def reorder_realm_custom_profile_fields(request: HttpRequest, user_profile: UserProfile, order: List[int]=REQ(validator=check_list( check_int))) -> HttpResponse: try_reorder_realm_custom_profile_fields(user_profile.realm, order) return json_success() @human_users_only @has_request_variables def remove_user_custom_profile_data(request: HttpRequest, user_profile: UserProfile, data: List[int]=REQ(validator=check_list( check_int))) -> HttpResponse: for field_id in data: try: field = CustomProfileField.objects.get(realm=user_profile.realm, id=field_id) except CustomProfileField.DoesNotExist: return json_error(_('Field id {id} not found.').format(id=field_id)) try: field_value = CustomProfileFieldValue.objects.get(field=field, user_profile=user_profile) except CustomProfileFieldValue.DoesNotExist: continue field_value.delete() notify_user_update_custom_profile_data(user_profile, {'id': field_id, 'value': None, 'type': field.field_type}) return json_success() @human_users_only @has_request_variables def update_user_custom_profile_data( request: HttpRequest, user_profile: UserProfile, data: List[Dict[str, Union[int, str, List[int]]]]=REQ(validator=check_list( check_dict([('id', check_int)])))) -> HttpResponse: validate_user_custom_profile_data(user_profile.realm.id, data) do_update_user_custom_profile_data(user_profile, data) # We need to call this explicitly otherwise constraints are not check return json_success()
[ "HttpRequest", "UserProfile", "str", "str", "HttpRequest", "UserProfile", "HttpRequest", "UserProfile", "int", "HttpRequest", "UserProfile", "int", "HttpRequest", "UserProfile", "HttpRequest", "UserProfile", "HttpRequest", "UserProfile" ]
[ 1417, 1444, 1803, 1814, 2183, 2248, 3595, 3622, 3683, 4135, 4162, 4223, 5328, 5355, 5709, 5736, 6757, 6792 ]
[ 1428, 1455, 1806, 1817, 2194, 2259, 3606, 3633, 3686, 4146, 4173, 4226, 5339, 5366, 5720, 5747, 6768, 6803 ]
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip
zerver/views/email_log.py
from django.conf import settings from django.http import HttpRequest, HttpResponse from django.shortcuts import render, redirect from django.views.decorators.http import require_GET from django.views.decorators.csrf import csrf_exempt from zerver.models import get_realm, get_user from zerver.lib.notifications import enqueue_welcome_emails from zerver.lib.response import json_success from zproject.email_backends import ( get_forward_address, set_forward_address, ) import urllib from confirmation.models import Confirmation, confirmation_url import os from typing import List, Dict, Any, Optional import datetime import subprocess ZULIP_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../') def email_page(request: HttpRequest) -> HttpResponse: if request.method == 'POST': set_forward_address(request.POST["forward_address"]) return json_success() try: with open(settings.EMAIL_CONTENT_LOG_PATH, "r+") as f: content = f.read() except FileNotFoundError: content = "" return render(request, 'zerver/email_log.html', {'log': content, 'forward_address': get_forward_address()}) def clear_emails(request: HttpRequest) -> HttpResponse: try: os.remove(settings.EMAIL_CONTENT_LOG_PATH) except FileNotFoundError: # nocoverage pass return redirect(email_page) @require_GET def generate_all_emails(request: HttpRequest) -> HttpResponse: if not settings.TEST_SUITE: # nocoverage # It's really convenient to automatically inline the email CSS # here, since that saves a step when testing out changes to # the email CSS. But we don't run this inside the test suite, # because by role, the tests shouldn't be doing a provision-like thing. subprocess.check_call(["./tools/inline-email-css"]) # We import the Django test client inside the view function, # because it isn't needed in production elsewhere, and not # importing it saves ~50ms of unnecessary manage.py startup time. from django.test import Client client = Client() # write fake data for all variables registered_email = "hamlet@zulip.com" unregistered_email_1 = "new-person@zulip.com" unregistered_email_2 = "new-person-2@zulip.com" realm = get_realm("zulip") host_kwargs = {'HTTP_HOST': realm.host} # Password reset email result = client.post('/accounts/password/reset/', {'email': registered_email}, **host_kwargs) assert result.status_code == 302 # Confirm account email result = client.post('/accounts/home/', {'email': unregistered_email_1}, **host_kwargs) assert result.status_code == 302 # Find account email result = client.post('/accounts/find/', {'emails': registered_email}, **host_kwargs) assert result.status_code == 302 # New login email logged_in = client.login(dev_auth_username=registered_email, realm=realm) assert logged_in # New user invite and reminder emails result = client.post("/json/invites", {"invitee_emails": unregistered_email_2, "stream": ["Denmark"]}, **host_kwargs) assert result.status_code == 200 # Verification for new email result = client.patch('/json/settings', urllib.parse.urlencode({'email': 'hamlets-new@zulip.com'}), **host_kwargs) assert result.status_code == 200 # Email change successful key = Confirmation.objects.filter(type=Confirmation.EMAIL_CHANGE).latest('id').confirmation_key url = confirmation_url(key, realm.host, Confirmation.EMAIL_CHANGE) user_profile = get_user(registered_email, realm) result = client.get(url) assert result.status_code == 200 # Reset the email value so we can run this again user_profile.email = registered_email user_profile.save(update_fields=['email']) # Follow up day1 day2 emails for normal user enqueue_welcome_emails(user_profile) # Follow up day1 day2 emails for admin user enqueue_welcome_emails(get_user("iago@zulip.com", realm), realm_creation=True) return redirect(email_page)
[ "HttpRequest", "HttpRequest", "HttpRequest" ]
[ 749, 1233, 1459 ]
[ 760, 1244, 1470 ]