tests: Use email/delivery_email more explicitly.

We try to use the correct variation of `email`
or `delivery_email`, even though in some
databases they are the same.

(To find the differences, I temporarily hacked
populate_db to use different values for email
and delivery_email, and reduced email visibility
in the zulip realm to admins only.)

In places where we want the "normal" realm
behavior of showing emails (and having `email`
be the same as `delivery_email`), we use
the new `reset_emails_in_zulip_realm` helper.

A couple random things:

    - I fixed any error messages that were leaking
      the wrong email

    - a test that claimed to rely on the order
      of emails no longer does (we sort user_ids
      instead)

    - we now use user_ids in some place where we used
      to use emails

    - for IRC mirrors I just punted and used
      `reset_emails_in_zulip_realm` in most places

    - for MIT-related tests, I didn't fix email
      vs. delivery_email unless it was obvious

I also explicitly reset the realm to a "normal"
realm for a couple tests that I frankly just didn't
have the energy to debug.  (Also, we do want some
coverage on the normal case, even though it is
"easier" for tests to pass if you mix up `email`
and `delivery_email`.)

In particular, I just reset data for the analytics
and corporate tests.
This commit is contained in:
Steve Howell 2020-03-12 13:17:25 +00:00 committed by Tim Abbott
parent b1f8141200
commit 1306239c16
33 changed files with 737 additions and 520 deletions

View File

@ -12,6 +12,7 @@ from analytics.models import FillState, \
RealmCount, UserCount, last_successful_fill
from analytics.views import rewrite_client_arrays, \
sort_by_totals, sort_client_labels
from zerver.lib.test_helpers import reset_emails_in_zulip_realm
from zerver.lib.test_classes import ZulipTestCase
from zerver.lib.timestamp import ceiling_to_day, \
ceiling_to_hour, datetime_to_timestamp
@ -334,6 +335,8 @@ class TestGetChartData(ZulipTestCase):
class TestSupportEndpoint(ZulipTestCase):
def test_search(self) -> None:
reset_emails_in_zulip_realm()
def check_hamlet_user_query_result(result: HttpResponse) -> None:
self.assert_in_success_response(['<span class="label">user</span>\n', '<h3>King Hamlet</h3>',
'<b>Email</b>: hamlet@zulip.com', '<b>Is active</b>: True<br>',

View File

@ -22,6 +22,7 @@ import stripe
from zerver.lib.actions import do_deactivate_user, do_create_user, \
do_activate_user, do_reactivate_user
from zerver.lib.test_classes import ZulipTestCase
from zerver.lib.test_helpers import reset_emails_in_zulip_realm
from zerver.lib.timestamp import timestamp_to_datetime, datetime_to_timestamp
from zerver.models import Realm, UserProfile, get_realm, RealmAuditLog
from corporate.lib.stripe import catch_stripe_errors, attach_discount_to_realm, \
@ -219,6 +220,7 @@ class StripeTestCase(ZulipTestCase):
super().setUp()
# This test suite is not robust to users being added in populate_db. The following
# hack ensures get_latest_seat_count is fixed, even as populate_db changes.
reset_emails_in_zulip_realm()
realm = get_realm('zulip')
seat_count = get_latest_seat_count(realm)
assert(seat_count >= 6)

View File

@ -283,11 +283,11 @@ class ZulipTestCase(TestCase):
def nonreg_user(self, name: str) -> UserProfile:
email = self.nonreg_user_map[name]
return get_user(email, get_realm("zulip"))
return get_user_by_delivery_email(email, get_realm("zulip"))
def example_user(self, name: str) -> UserProfile:
email = self.example_user_map[name]
return get_user(email, get_realm('zulip'))
return get_user_by_delivery_email(email, get_realm('zulip'))
def mit_user(self, name: str) -> UserProfile:
email = self.mit_user_map[name]

View File

@ -13,6 +13,7 @@ from boto.s3.connection import S3Connection
from boto.s3.bucket import Bucket
import zerver.lib.upload
from zerver.lib.actions import do_set_realm_property
from zerver.lib.upload import S3UploadBackend, LocalUploadBackend
from zerver.lib.avatar import avatar_url
from zerver.lib.cache import get_cache_backend
@ -25,9 +26,11 @@ from zerver.lib.integrations import WEBHOOK_INTEGRATIONS
from zerver.views.auth import get_login_data
from zerver.models import (
get_realm,
get_stream,
Client,
Message,
Realm,
Subscription,
UserMessage,
UserProfile,
@ -187,6 +190,11 @@ def stdout_suppressed() -> Iterator[IO[str]]:
yield stdout
sys.stdout = stdout
def reset_emails_in_zulip_realm() -> None:
realm = get_realm('zulip')
do_set_realm_property(realm, 'email_address_visibility',
Realm.EMAIL_ADDRESS_VISIBILITY_EVERYONE)
def get_test_image_file(filename: str) -> IO[Any]:
test_avatar_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '../tests/images'))
return open(os.path.join(test_avatar_dir, filename), 'rb')

View File

@ -78,15 +78,15 @@ class TestRealmAuditLog(ZulipTestCase):
def test_change_email(self) -> None:
now = timezone_now()
user = self.example_user('hamlet')
email = 'test@example.com'
do_change_user_delivery_email(user, email)
new_email = 'test@example.com'
do_change_user_delivery_email(user, new_email)
self.assertEqual(RealmAuditLog.objects.filter(event_type=RealmAuditLog.USER_EMAIL_CHANGED,
event_time__gte=now).count(), 1)
self.assertEqual(email, user.email)
self.assertEqual(new_email, user.delivery_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 %s> %s " % (user.realm, RealmAuditLog.USER_EMAIL_CHANGED)))
self.assertTrue(str(audit_entry).startswith("<RealmAuditLog: <UserProfile: %s %s> %s " % (user.email, user.realm, RealmAuditLog.USER_EMAIL_CHANGED)))
def test_change_avatar_source(self) -> None:
now = timezone_now()

View File

@ -52,8 +52,8 @@ from zerver.lib.test_classes import (
)
from zerver.models import \
get_realm, email_to_username, CustomProfileField, CustomProfileFieldValue, \
UserProfile, PreregistrationUser, Realm, RealmDomain, get_user, MultiuseInvite, \
clear_supported_auth_backends_cache, PasswordTooWeakError
UserProfile, PreregistrationUser, Realm, RealmDomain, MultiuseInvite, \
clear_supported_auth_backends_cache, PasswordTooWeakError, get_user_by_delivery_email
from zerver.signals import JUST_CREATED_THRESHOLD
from confirmation.models import Confirmation, create_confirmation_link
@ -196,7 +196,7 @@ class AuthBackendTest(ZulipTestCase):
return_value=True):
return_data = {} # type: Dict[str, bool]
user = EmailAuthBackend().authenticate(request=mock.MagicMock(),
username=self.example_email('hamlet'),
username=user_profile.delivery_email,
realm=get_realm("zulip"),
password=password,
return_data=return_data)
@ -313,7 +313,7 @@ class AuthBackendTest(ZulipTestCase):
def test_ldap_backend(self) -> None:
self.init_default_ldap_database()
user_profile = self.example_user('hamlet')
email = user_profile.email
email = user_profile.delivery_email
password = self.ldap_password('hamlet')
self.setup_subdomain(user_profile)
@ -387,7 +387,7 @@ class AuthBackendTest(ZulipTestCase):
'token_type': 'bearer'
}
github_email_data = [
dict(email=user.email,
dict(email=user.delivery_email,
verified=True,
primary=True),
dict(email="nonprimary@zulip.com",
@ -395,7 +395,7 @@ class AuthBackendTest(ZulipTestCase):
dict(email="ignored@example.com",
verified=False),
]
google_email_data = dict(email=user.email,
google_email_data = dict(email=user.delivery_email,
name=user.full_name,
email_verified=True)
backends_to_test = {
@ -432,7 +432,7 @@ class AuthBackendTest(ZulipTestCase):
# pipeline when we display an email picker for the GitHub
# authentication backend. We do that here.
def return_email() -> Dict[str, str]:
return {'email': user.email}
return {'email': user.delivery_email}
backend.strategy.request_data = return_email
result = orig_authenticate(backend, **kwargs)
@ -540,7 +540,9 @@ class RateLimitAuthenticationTests(ZulipTestCase):
password=password,
return_data=dict())
self.do_test_auth_rate_limiting(attempt_authentication, user_profile.email, password, 'wrong_password',
self.do_test_auth_rate_limiting(attempt_authentication,
user_profile.delivery_email,
password, 'wrong_password',
user_profile)
@override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',),
@ -557,7 +559,9 @@ class RateLimitAuthenticationTests(ZulipTestCase):
password=password,
return_data=dict())
self.do_test_auth_rate_limiting(attempt_authentication, user_profile.email, password, 'wrong_password',
self.do_test_auth_rate_limiting(attempt_authentication,
user_profile.delivery_email,
password, 'wrong_password',
user_profile)
@override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.EmailAuthBackend',
@ -579,10 +583,12 @@ class RateLimitAuthenticationTests(ZulipTestCase):
password=password,
return_data=dict())
self.do_test_auth_rate_limiting(attempt_authentication, user_profile.email,
self.do_test_auth_rate_limiting(attempt_authentication,
user_profile.delivery_email,
email_password, 'wrong_password',
user_profile)
self.do_test_auth_rate_limiting(attempt_authentication, user_profile.email,
self.do_test_auth_rate_limiting(attempt_authentication,
user_profile.delivery_email,
ldap_password, 'wrong_password',
user_profile)
@ -624,7 +630,7 @@ class DesktopFlowTestingLib(ZulipTestCase):
result = self.client_get(browser_url)
self.assertEqual(result.status_code, 302)
realm = get_realm("zulip")
user_profile = get_user(email, realm)
user_profile = get_user_by_delivery_email(email, realm)
self.assert_logged_in_user_id(user_profile.id)
def verify_desktop_app_url_and_return_key(self, url: str, email: str, desktop_flow_otp: str) -> str:
@ -655,7 +661,7 @@ class SocialAuthBase(DesktopFlowTestingLib, ZulipTestCase):
def setUp(self) -> None:
super().setUp()
self.user_profile = self.example_user('hamlet')
self.email = self.user_profile.email
self.email = self.user_profile.delivery_email
self.name = self.user_profile.full_name
self.backend = self.BACKEND_CLASS
self.backend.strategy = DjangoStrategy(storage=BaseDjangoStorage())
@ -1070,7 +1076,7 @@ class SocialAuthBase(DesktopFlowTestingLib, ZulipTestCase):
self.assertEqual(query_params["realm"], ['http://zulip.testserver'])
self.assertEqual(query_params["email"], [email])
encrypted_api_key = query_params["otp_encrypted_api_key"][0]
user_api_keys = get_all_api_keys(get_user(email, realm))
user_api_keys = get_all_api_keys(get_user_by_delivery_email(email, realm))
self.assertIn(otp_decrypt_api_key(encrypted_api_key, mobile_flow_otp), user_api_keys)
return
elif desktop_flow_otp:
@ -1079,7 +1085,7 @@ class SocialAuthBase(DesktopFlowTestingLib, ZulipTestCase):
else:
self.assertEqual(result.status_code, 302)
user_profile = get_user(email, realm)
user_profile = get_user_by_delivery_email(email, realm)
self.assert_logged_in_user_id(user_profile.id)
self.assertEqual(user_profile.full_name, expected_final_name)
@ -2082,7 +2088,7 @@ class GoogleAuthBackendTest(SocialAuthBase):
'key': confirmation_key,
'terms': True})
self.assertEqual(result.status_code, 302)
new_user = get_user('new@zulip.com', realm)
new_user = get_user_by_delivery_email('new@zulip.com', realm)
new_streams = self.get_streams(new_user)
self.assertEqual(sorted(new_streams), stream_names)
@ -2110,14 +2116,14 @@ class JSONFetchAPIKeyTest(ZulipTestCase):
self.login_user(user)
result = self.client_post("/json/fetch_api_key",
dict(user_profile=user,
password=initial_password(user.email)))
password=initial_password(user.delivery_email)))
self.assert_json_success(result)
def test_not_loggedin(self) -> None:
user = self.example_user('hamlet')
result = self.client_post("/json/fetch_api_key",
dict(user_profile=user,
password=initial_password(user.email)))
password=initial_password(user.delivery_email)))
self.assert_json_error(result,
"Not logged in: API authentication or user session required", 401)
@ -2133,7 +2139,7 @@ class FetchAPIKeyTest(ZulipTestCase):
def setUp(self) -> None:
super().setUp()
self.user_profile = self.example_user('hamlet')
self.email = self.user_profile.email
self.email = self.user_profile.delivery_email
def test_success(self) -> None:
result = self.client_post("/api/v1/fetch_api_key",
@ -2187,7 +2193,7 @@ class DevFetchAPIKeyTest(ZulipTestCase):
def setUp(self) -> None:
super().setUp()
self.user_profile = self.example_user('hamlet')
self.email = self.user_profile.email
self.email = self.user_profile.delivery_email
def test_success(self) -> None:
result = self.client_post("/api/v1/dev_fetch_api_key",
@ -2419,7 +2425,7 @@ class TestTwoFactor(ZulipTestCase):
class TestDevAuthBackend(ZulipTestCase):
def test_login_success(self) -> None:
user_profile = self.example_user('hamlet')
email = user_profile.email
email = user_profile.delivery_email
data = {'direct_email': email}
result = self.client_post('/accounts/login/local/', data)
self.assertEqual(result.status_code, 302)
@ -2428,7 +2434,7 @@ class TestDevAuthBackend(ZulipTestCase):
def test_login_success_with_2fa(self) -> None:
user_profile = self.example_user('hamlet')
self.create_default_device(user_profile)
email = user_profile.email
email = user_profile.delivery_email
data = {'direct_email': email}
with self.settings(TWO_FACTOR_AUTHENTICATION_ENABLED=True):
result = self.client_post('/accounts/login/local/', data)
@ -2461,7 +2467,7 @@ class TestDevAuthBackend(ZulipTestCase):
def test_login_with_subdomain(self) -> None:
user_profile = self.example_user('hamlet')
email = user_profile.email
email = user_profile.delivery_email
data = {'direct_email': email}
result = self.client_post('/accounts/login/local/', data)
@ -2537,7 +2543,7 @@ class TestDevAuthBackend(ZulipTestCase):
class TestZulipRemoteUserBackend(DesktopFlowTestingLib, ZulipTestCase):
def test_login_success(self) -> None:
user_profile = self.example_user('hamlet')
email = user_profile.email
email = user_profile.delivery_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)
@ -2605,7 +2611,7 @@ class TestZulipRemoteUserBackend(DesktopFlowTestingLib, ZulipTestCase):
def test_login_success_under_subdomains(self) -> None:
user_profile = self.example_user('hamlet')
email = user_profile.email
email = user_profile.delivery_email
with mock.patch('zerver.views.auth.get_subdomain', return_value='zulip'):
with self.settings(
AUTHENTICATION_BACKENDS=('zproject.backends.ZulipRemoteUserBackend',)):
@ -2617,7 +2623,7 @@ class TestZulipRemoteUserBackend(DesktopFlowTestingLib, ZulipTestCase):
@override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipRemoteUserBackend',))
def test_login_mobile_flow_otp_success_email(self) -> None:
user_profile = self.example_user('hamlet')
email = user_profile.email
email = user_profile.delivery_email
user_profile.date_joined = timezone_now() - datetime.timedelta(seconds=61)
user_profile.save()
mobile_flow_otp = '1234abcd' * 8
@ -2659,7 +2665,7 @@ class TestZulipRemoteUserBackend(DesktopFlowTestingLib, ZulipTestCase):
@override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipRemoteUserBackend',))
def test_login_mobile_flow_otp_success_username(self) -> None:
user_profile = self.example_user('hamlet')
email = user_profile.email
email = user_profile.delivery_email
remote_user = email_to_username(email)
user_profile.date_joined = timezone_now() - datetime.timedelta(seconds=61)
user_profile.save()
@ -2702,7 +2708,7 @@ class TestZulipRemoteUserBackend(DesktopFlowTestingLib, ZulipTestCase):
'zproject.backends.ZulipDummyBackend'))
def test_login_desktop_flow_otp_success_email(self) -> None:
user_profile = self.example_user('hamlet')
email = user_profile.email
email = user_profile.delivery_email
user_profile.date_joined = timezone_now() - datetime.timedelta(seconds=61)
user_profile.save()
desktop_flow_otp = '1234abcd' * 8
@ -2731,7 +2737,7 @@ class TestZulipRemoteUserBackend(DesktopFlowTestingLib, ZulipTestCase):
'zproject.backends.ZulipDummyBackend'))
def test_login_desktop_flow_otp_success_username(self) -> None:
user_profile = self.example_user('hamlet')
email = user_profile.email
email = user_profile.delivery_email
remote_user = email_to_username(email)
user_profile.date_joined = timezone_now() - datetime.timedelta(seconds=61)
user_profile.save()
@ -2760,7 +2766,7 @@ class TestZulipRemoteUserBackend(DesktopFlowTestingLib, ZulipTestCase):
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
email = user_profile.delivery_email
with self.settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipRemoteUserBackend',)):
result = self.client_post('/accounts/login/sso/?next=' + next, REMOTE_USER=email)
return result
@ -2794,7 +2800,7 @@ class TestJWTLogin(ZulipTestCase):
auth_key = settings.JWT_AUTH_KEYS['zulip']
web_token = jwt.encode(payload, auth_key).decode('utf8')
user_profile = get_user(email, realm)
user_profile = get_user_by_delivery_email(email, realm)
data = {'json_web_token': web_token}
result = self.client_post('/accounts/login/jwt/', data)
self.assertEqual(result.status_code, 302)
@ -2961,7 +2967,7 @@ class DjangoToLDAPUsernameTests(ZulipTestCase):
"""
With AUTH_LDAP_REVERSE_EMAIL_SEARCH configured, django_to_ldap_username
should be able to translate an email to ldap username,
and thus it should be possible to authenticate through user_profile.email.
and thus it should be possible to authenticate through user_profile.delivery_email.
"""
realm = get_realm("zulip")
user_profile = self.example_user("hamlet")
@ -2971,7 +2977,7 @@ class DjangoToLDAPUsernameTests(ZulipTestCase):
with self.settings(LDAP_EMAIL_ATTR='mail'):
self.assertEqual(
authenticate(request=mock.MagicMock(), username=user_profile.email,
authenticate(request=mock.MagicMock(), username=user_profile.delivery_email,
password=self.ldap_password('hamlet'), realm=realm),
user_profile)
@ -3066,7 +3072,7 @@ class TestLDAP(ZulipLDAPTestCase):
realm=get_realm('zulip'))
assert(user_profile is not None)
self.assertEqual(user_profile.email, self.example_email("hamlet"))
self.assertEqual(user_profile.delivery_email, self.example_email("hamlet"))
@override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',))
def test_login_success_with_username(self) -> None:
@ -3114,9 +3120,10 @@ class TestLDAP(ZulipLDAPTestCase):
othello.set_password(password)
othello.save()
self.assertEqual(email_belongs_to_ldap(realm, othello.email), False)
self.assertEqual(email_belongs_to_ldap(realm, othello.delivery_email), False)
user_profile = EmailAuthBackend().authenticate(request=mock.MagicMock(),
username=othello.email, password=password,
username=othello.delivery_email,
password=password,
realm=realm)
self.assertEqual(user_profile, othello)
@ -3162,7 +3169,7 @@ class TestLDAP(ZulipLDAPTestCase):
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)
self.assertEqual(user_profile.delivery_email, email)
@override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',))
def test_get_or_build_user_when_user_does_not_exist(self) -> None:
@ -3176,7 +3183,7 @@ class TestLDAP(ZulipLDAPTestCase):
email = 'newuser@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.delivery_email, email)
self.assertEqual(user_profile.full_name, 'Full Name')
@override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',))
@ -3278,7 +3285,7 @@ class TestLDAP(ZulipLDAPTestCase):
username=self.example_email('hamlet'),
password=self.ldap_password('hamlet'),
realm=get_realm('acme'))
self.assertEqual(user_profile.email, self.example_email('hamlet'))
self.assertEqual(user_profile.delivery_email, self.example_email('hamlet'))
@override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',))
def test_login_success_with_valid_subdomain(self) -> None:
@ -3288,7 +3295,7 @@ class TestLDAP(ZulipLDAPTestCase):
password=self.ldap_password('hamlet'),
realm=get_realm('zulip'))
assert(user_profile is not None)
self.assertEqual(user_profile.email, self.example_email("hamlet"))
self.assertEqual(user_profile.delivery_email, self.example_email("hamlet"))
@override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',))
def test_login_failure_due_to_deactivated_user(self) -> None:
@ -3314,7 +3321,7 @@ class TestLDAP(ZulipLDAPTestCase):
password=self.ldap_password("newuser"),
realm=get_realm('zulip'))
assert(user_profile is not None)
self.assertEqual(user_profile.email, 'newuser@acme.com')
self.assertEqual(user_profile.delivery_email, 'newuser@acme.com')
self.assertEqual(user_profile.full_name, 'New LDAP fullname')
self.assertEqual(user_profile.realm.string_id, 'zulip')
@ -3333,7 +3340,7 @@ class TestLDAP(ZulipLDAPTestCase):
password=self.ldap_password("newuser_splitname"),
realm=get_realm('zulip'))
assert(user_profile is not None)
self.assertEqual(user_profile.email, 'newuser_splitname@zulip.com')
self.assertEqual(user_profile.delivery_email, 'newuser_splitname@zulip.com')
self.assertEqual(user_profile.full_name, 'First Last')
self.assertEqual(user_profile.realm.string_id, 'zulip')
@ -3448,7 +3455,13 @@ class TestZulipLDAPUserPopulator(ZulipLDAPTestCase):
def test_user_in_multiple_realms(self) -> None:
test_realm = do_create_realm('test', 'test', False)
hamlet = self.example_user('hamlet')
hamlet2 = do_create_user(hamlet.email, None, test_realm, hamlet.full_name, hamlet.short_name)
email = hamlet.delivery_email
hamlet2 = do_create_user(
email,
None,
test_realm,
hamlet.full_name,
hamlet.short_name)
self.change_ldap_user_attr('hamlet', 'cn', 'Second Hamlet')
expected_call_args = [hamlet2, 'Second Hamlet', None]
@ -3458,10 +3471,10 @@ class TestZulipLDAPUserPopulator(ZulipLDAPTestCase):
f.assert_called_once_with(*expected_call_args)
# Get the updated model and make sure the full name is changed correctly:
hamlet2 = get_user(hamlet.email, test_realm)
hamlet2 = get_user_by_delivery_email(email, test_realm)
self.assertEqual(hamlet2.full_name, "Second Hamlet")
# Now get the original hamlet and make he still has his name unchanged:
hamlet = get_user(hamlet.email, get_realm("zulip"))
hamlet = self.example_user('hamlet')
self.assertEqual(hamlet.full_name, "King Hamlet")
def test_user_not_found_in_ldap(self) -> None:
@ -3471,7 +3484,8 @@ class TestZulipLDAPUserPopulator(ZulipLDAPTestCase):
othello = self.example_user("othello") # othello isn't in our test directory
mock_logger = mock.MagicMock()
result = sync_user_from_ldap(othello, mock_logger)
mock_logger.warning.assert_called_once_with("Did not find %s in LDAP." % (othello.email,))
mock_logger.warning.assert_called_once_with(
"Did not find %s in LDAP." % (othello.delivery_email,))
self.assertFalse(result)
do_deactivate_user(othello)
@ -3835,16 +3849,17 @@ class EmailValidatorTestCase(ZulipTestCase):
)
self.assertIn('containing + are not allowed', error)
errors = get_existing_user_errors(realm, {cordelia.email})
error, is_deactivated = errors[cordelia.email]
cordelia_email = cordelia.delivery_email
errors = get_existing_user_errors(realm, {cordelia_email})
error, is_deactivated = errors[cordelia_email]
self.assertEqual(False, is_deactivated)
self.assertEqual(error, 'Already has an account.')
cordelia.is_active = False
cordelia.save()
errors = get_existing_user_errors(realm, {cordelia.email})
error, is_deactivated = errors[cordelia.email]
errors = get_existing_user_errors(realm, {cordelia_email})
error, is_deactivated = errors[cordelia_email]
self.assertEqual(True, is_deactivated)
self.assertEqual(error, 'Account has been deactivated.')
@ -3855,8 +3870,12 @@ class LDAPBackendTest(ZulipTestCase):
@override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',))
def test_non_existing_realm(self) -> None:
self.init_default_ldap_database()
email = self.example_email('hamlet')
data = {'username': email, 'password': initial_password(email)}
user = self.example_user('hamlet')
data = dict(
username=user.delivery_email,
password=initial_password(user.delivery_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',

View File

@ -149,6 +149,7 @@ class BotTest(ZulipTestCase, UploadSerializeMixin):
self.assert_length(queries, 3)
def test_add_bot(self) -> None:
hamlet = self.example_user('hamlet')
self.login('hamlet')
self.assert_num_bots_equal(0)
events = [] # type: List[Mapping[str, Any]]
@ -164,18 +165,20 @@ class BotTest(ZulipTestCase, UploadSerializeMixin):
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'))
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=hamlet.email,
),
),
event['event']
)
@ -330,11 +333,12 @@ class BotTest(ZulipTestCase, UploadSerializeMixin):
is sent when add_subscriptions_backend is called in the above api call.
"""
hamlet = self.example_user('hamlet')
iago = self.example_user('iago')
self.login_user(hamlet)
# Normal user i.e. not a bot.
request_data = {
'principals': '["' + self.example_email('iago') + '"]'
'principals': '["' + iago.email + '"]'
}
events = [] # type: List[Mapping[str, Any]]
with tornado_redirected_to_list(events):
@ -391,18 +395,20 @@ class BotTest(ZulipTestCase, UploadSerializeMixin):
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'))
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=user_profile.email,
),
),
event['event']
)
@ -461,18 +467,20 @@ class BotTest(ZulipTestCase, UploadSerializeMixin):
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'))
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=user_profile.email,
),
),
event['event']
)
@ -860,6 +868,8 @@ class BotTest(ZulipTestCase, UploadSerializeMixin):
def test_patch_bot_owner(self) -> None:
self.login('hamlet')
othello = self.example_user('othello')
bot_info = {
'full_name': u'The Bot of Hamlet',
'short_name': u'hambot',
@ -867,14 +877,14 @@ class BotTest(ZulipTestCase, UploadSerializeMixin):
result = self.client_post("/json/bots", bot_info)
self.assert_json_success(result)
bot_info = {
'bot_owner_id': self.example_user('othello').id,
'bot_owner_id': 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.assertEqual(result.json()['bot_owner'], othello.email)
self.login('othello')
bot = self.get_bot()

View File

@ -216,12 +216,12 @@ class BugdownMiscTest(ZulipTestCase):
for row in lst
}
self.assertEqual(by_id.get(fred2.id), dict(
email='fred2@example.com',
email=fred2.email,
full_name='Fred Flintstone',
id=fred2.id
))
self.assertEqual(by_id.get(fred4.id), dict(
email='fred4@example.com',
email=fred4.email,
full_name='Fred Flintstone',
id=fred4.id
))

View File

@ -271,7 +271,7 @@ class GenericBulkCachedFetchTest(ZulipTestCase):
query_function=query_function,
object_ids=[self.example_email("hamlet")]
) # type: Dict[str, UserProfile]
self.assertEqual(result, {hamlet.email: hamlet})
self.assertEqual(result, {hamlet.delivery_email: hamlet})
flush_cache(Mock())
# With the cache flushed, the query_function should get called:

View File

@ -1090,7 +1090,7 @@ class FetchAPIKeyTest(ZulipTestCase):
user = self.example_user("cordelia")
self.login_user(user)
result = self.client_post("/json/fetch_api_key",
dict(password=initial_password(user.email)))
dict(password=initial_password(user.delivery_email)))
self.assert_json_success(result)
def test_fetch_api_key_email_address_visibility(self) -> None:
@ -1100,7 +1100,7 @@ class FetchAPIKeyTest(ZulipTestCase):
self.login_user(user)
result = self.client_post("/json/fetch_api_key",
dict(password=initial_password(user.email)))
dict(password=initial_password(user.delivery_email)))
self.assert_json_success(result)
def test_fetch_api_key_wrong_password(self) -> None:
@ -1150,7 +1150,7 @@ class InactiveUserTest(ZulipTestCase):
"""
user_profile = self.example_user('hamlet')
email = user_profile.email
email = user_profile.delivery_email
test_password = "abcd1234"
user_profile.set_password(test_password)
user_profile.save()
@ -1183,14 +1183,17 @@ class InactiveUserTest(ZulipTestCase):
user_profile.is_mirror_dummy = True
user_profile.save()
password = initial_password(user_profile.email)
password = initial_password(user_profile.delivery_email)
request = mock.MagicMock()
request.get_host.return_value = 'zulip.testserver'
payload = dict(
username=user_profile.delivery_email,
password=password,
)
# Test a mirror-dummy active user.
form = OurAuthenticationForm(request,
data={'username': user_profile.email,
'password': password})
form = OurAuthenticationForm(request, payload)
with self.settings(AUTHENTICATION_BACKENDS=('zproject.backends.EmailAuthBackend',)):
self.assertTrue(form.is_valid())
@ -1198,9 +1201,7 @@ class InactiveUserTest(ZulipTestCase):
do_deactivate_user(user_profile)
user_profile.save()
form = OurAuthenticationForm(request,
data={'username': user_profile.email,
'password': password})
form = OurAuthenticationForm(request, payload)
with self.settings(AUTHENTICATION_BACKENDS=('zproject.backends.EmailAuthBackend',)):
self.assertFalse(form.is_valid())
self.assertIn("Please enter a correct email", str(form.errors))
@ -1209,9 +1210,7 @@ class InactiveUserTest(ZulipTestCase):
user_profile.is_mirror_dummy = False
user_profile.save()
form = OurAuthenticationForm(request,
data={'username': user_profile.email,
'password': password})
form = OurAuthenticationForm(request, payload)
with self.settings(AUTHENTICATION_BACKENDS=('zproject.backends.EmailAuthBackend',)):
self.assertFalse(form.is_valid())
self.assertIn("Your account is no longer active", str(form.errors))
@ -1235,11 +1234,15 @@ class InactiveUserTest(ZulipTestCase):
class TestIncomingWebhookBot(ZulipTestCase):
def test_webhook_bot_permissions(self) -> None:
webhook_bot = self.example_user('webhook_bot')
result = self.api_post(webhook_bot,
"/api/v1/messages", {"type": "private",
"content": "Test message",
"client": "test suite",
"to": self.example_email("othello")})
othello = self.example_user('othello')
payload = dict(
type='private',
content='Test message',
client='test suite',
to=othello.email,
)
result = self.api_post(webhook_bot, "/api/v1/messages", payload)
self.assert_json_success(result)
post_params = {"anchor": 1, "num_before": 1, "num_after": 1}
result = self.api_get(webhook_bot, "/api/v1/messages", dict(post_params))
@ -1449,6 +1452,7 @@ class TestAuthenticatedJsonPostViewDecorator(ZulipTestCase):
def test_authenticated_json_post_view_if_subdomain_is_invalid(self) -> None:
user = self.example_user('hamlet')
email = user.delivery_email
self.login_user(user)
with mock.patch('logging.warning') as mock_warning, \
mock.patch('zerver.decorator.get_subdomain', return_value=''):
@ -1457,7 +1461,7 @@ class TestAuthenticatedJsonPostViewDecorator(ZulipTestCase):
"subdomain")
mock_warning.assert_called_with(
"User {} ({}) attempted to access API on wrong "
"subdomain ({})".format(user.email, 'zulip', ''))
"subdomain ({})".format(email, 'zulip', ''))
with mock.patch('logging.warning') as mock_warning, \
mock.patch('zerver.decorator.get_subdomain', return_value='acme'):
@ -1466,7 +1470,7 @@ class TestAuthenticatedJsonPostViewDecorator(ZulipTestCase):
"subdomain")
mock_warning.assert_called_with(
"User {} ({}) attempted to access API on wrong "
"subdomain ({})".format(user.email, 'zulip', 'acme'))
"subdomain ({})".format(email, 'zulip', 'acme'))
def test_authenticated_json_post_view_if_user_is_incoming_webhook(self) -> None:
bot = self.example_user('webhook_bot')
@ -1502,7 +1506,7 @@ class TestAuthenticatedJsonPostViewDecorator(ZulipTestCase):
class TestAuthenticatedJsonViewDecorator(ZulipTestCase):
def test_authenticated_json_view_if_subdomain_is_invalid(self) -> None:
user = self.example_user('hamlet')
email = user.email
email = user.delivery_email
self.login_user(user)
with mock.patch('logging.warning') as mock_warning, \

View File

@ -188,7 +188,7 @@ class EmailChangeTestCase(ZulipTestCase):
Realm.EMAIL_ADDRESS_VISIBILITY_ADMINS)
self.login_user(user_profile)
old_email = user_profile.email
old_email = user_profile.delivery_email
new_email = 'hamlet-new@zulip.com'
obj = EmailChangeStatus.objects.create(new_email=new_email,
old_email=old_email,

View File

@ -20,6 +20,7 @@ from zerver.models import (
get_system_bot,
MissedMessageEmailAddress,
Recipient,
UserProfile,
)
from zerver.lib.actions import ensure_stream, do_deactivate_realm, do_deactivate_user
@ -695,10 +696,11 @@ class TestMissedMessageEmailMessages(ZulipTestCase):
# have Hamlet send Othello a PM. Othello will reply via email
# Hamlet will receive the message.
self.login('hamlet')
othello = self.example_user('othello')
result = self.client_post("/json/messages", {"type": "private",
"content": "test_receive_missed_message_email_messages",
"client": "test suite",
"to": self.example_email('othello')})
"to": ujson.dumps([othello.id])})
self.assert_json_success(result)
user_profile = self.example_user('othello')
@ -732,11 +734,12 @@ class TestMissedMessageEmailMessages(ZulipTestCase):
# have Othello send Iago and Cordelia a PM. Cordelia will reply via email
# Iago and Othello will receive the message.
self.login('othello')
cordelia = self.example_user('cordelia')
iago = self.example_user('iago')
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')])})
"to": ujson.dumps([cordelia.id, iago.id])})
self.assert_json_success(result)
user_profile = self.example_user('cordelia')
@ -795,9 +798,9 @@ class TestMissedMessageEmailMessages(ZulipTestCase):
incoming_valid_message = MIMEText('TestMissedMessageEmailMessages Body')
incoming_valid_message['Subject'] = 'TestMissedMessageEmailMessages Subject'
incoming_valid_message['From'] = self.example_email('othello')
incoming_valid_message['From'] = user_profile.delivery_email
incoming_valid_message['To'] = mm_address
incoming_valid_message['Reply-to'] = self.example_email('othello')
incoming_valid_message['Reply-to'] = user_profile.delivery_email
process_message(incoming_valid_message)
@ -834,9 +837,9 @@ class TestMissedMessageEmailMessages(ZulipTestCase):
incoming_valid_message = MIMEText('TestMissedMessageEmailMessages Body')
incoming_valid_message['Subject'] = 'TestMissedMessageEmailMessages Subject'
incoming_valid_message['From'] = self.example_email('othello')
incoming_valid_message['From'] = user_profile.delivery_email
incoming_valid_message['To'] = mm_address
incoming_valid_message['Reply-to'] = self.example_email('othello')
incoming_valid_message['Reply-to'] = user_profile.delivery_email
process_message(incoming_valid_message)
@ -871,9 +874,9 @@ class TestMissedMessageEmailMessages(ZulipTestCase):
incoming_valid_message = MIMEText('TestMissedMessageEmailMessages Body')
incoming_valid_message['Subject'] = 'TestMissedMessageEmailMessages Subject'
incoming_valid_message['From'] = self.example_email('othello')
incoming_valid_message['From'] = user_profile.delivery_email
incoming_valid_message['To'] = mm_address
incoming_valid_message['Reply-to'] = self.example_email('othello')
incoming_valid_message['Reply-to'] = user_profile.delivery_email
initial_last_message = self.get_last_message()
process_message(incoming_valid_message)
@ -902,9 +905,9 @@ class TestMissedMessageEmailMessages(ZulipTestCase):
incoming_valid_message = MIMEText('TestMissedMessageEmailMessages Body')
incoming_valid_message['Subject'] = 'TestMissedMessageEmailMessages Subject'
incoming_valid_message['From'] = self.example_email('othello')
incoming_valid_message['From'] = user_profile.delivery_email
incoming_valid_message['To'] = mm_address
incoming_valid_message['Reply-to'] = self.example_email('othello')
incoming_valid_message['Reply-to'] = user_profile.delivery_email
initial_last_message = self.get_last_message()
process_message(incoming_valid_message)
@ -931,9 +934,9 @@ class TestMissedMessageEmailMessages(ZulipTestCase):
incoming_valid_message = MIMEText('TestMissedMessageEmailMessages Body')
incoming_valid_message['Subject'] = 'TestMissedMessageEmailMessages Subject'
incoming_valid_message['From'] = self.example_email('othello')
incoming_valid_message['From'] = user_profile.delivery_email
incoming_valid_message['To'] = mm_address
incoming_valid_message['Reply-to'] = self.example_email('othello')
incoming_valid_message['Reply-to'] = user_profile.delivery_email
for i in range(0, MissedMessageEmailAddress.ALLOWED_USES):
process_missed_message(mm_address, incoming_valid_message)
@ -944,11 +947,15 @@ class TestMissedMessageEmailMessages(ZulipTestCase):
class TestEmptyGatewaySetting(ZulipTestCase):
def test_missed_message(self) -> None:
self.login('othello')
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')])})
cordelia = self.example_user('cordelia')
iago = self.example_user('iago')
payload = dict(
type="private",
content="test_receive_missed_message_email_messages",
client="test suite",
to=ujson.dumps([cordelia.id, iago.id]),
)
result = self.client_post("/json/messages", payload)
self.assert_json_success(result)
user_profile = self.example_user('cordelia')
@ -995,9 +1002,9 @@ class TestReplyExtraction(ZulipTestCase):
incoming_valid_message = MIMEText(text)
incoming_valid_message['Subject'] = 'TestStreamEmailMessages Subject'
incoming_valid_message['From'] = self.example_email('hamlet')
incoming_valid_message['From'] = user_profile.delivery_email
incoming_valid_message['To'] = stream_to_address
incoming_valid_message['Reply-to'] = self.example_email('othello')
incoming_valid_message['Reply-to'] = user_profile.delivery_email
process_message(incoming_valid_message)
@ -1045,9 +1052,9 @@ class TestReplyExtraction(ZulipTestCase):
incoming_valid_message = MIMEText(html, 'html')
incoming_valid_message['Subject'] = 'TestStreamEmailMessages Subject'
incoming_valid_message['From'] = self.example_email('hamlet')
incoming_valid_message['From'] = user_profile.delivery_email
incoming_valid_message['To'] = stream_to_address
incoming_valid_message['Reply-to'] = self.example_email('othello')
incoming_valid_message['Reply-to'] = user_profile.delivery_email
process_message(incoming_valid_message)
@ -1112,13 +1119,15 @@ class TestEmailMirrorTornadoView(ZulipTestCase):
def send_private_message(self) -> str:
self.login('othello')
cordelia = self.example_user('cordelia')
iago = self.example_user('iago')
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')])
"to": ujson.dumps([cordelia.id, iago.id])
})
self.assert_json_success(result)
@ -1127,10 +1136,10 @@ class TestEmailMirrorTornadoView(ZulipTestCase):
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,
def send_offline_message(self, to_address: str, sender: UserProfile,
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)
mail = mail_template.format(stream_to_address=to_address, sender=sender.delivery_email)
def check_queue_json_publish(queue_name: str,
event: Mapping[str, Any],
@ -1156,7 +1165,7 @@ class TestEmailMirrorTornadoView(ZulipTestCase):
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'))
result = self.send_offline_message(stream_to_address, self.example_user('hamlet'))
self.assert_json_success(result)
def test_error_to_stream_with_wrong_address(self) -> None:
@ -1166,7 +1175,7 @@ class TestEmailMirrorTornadoView(ZulipTestCase):
token = decode_email_address(stream_to_address)[0]
stream_to_address = stream_to_address.replace(token, "Wrong_token")
result = self.send_offline_message(stream_to_address, self.example_email('hamlet'))
result = self.send_offline_message(stream_to_address, self.example_user('hamlet'))
self.assert_json_error(
result,
"5.1.1 Bad destination mailbox address: "
@ -1177,21 +1186,21 @@ class TestEmailMirrorTornadoView(ZulipTestCase):
stream_to_address = encode_email_address(stream)
stream_to_address = stream_to_address.replace("denmark", "Wrong_name")
result = self.send_offline_message(stream_to_address, self.example_email('hamlet'))
result = self.send_offline_message(stream_to_address, self.example_user('hamlet'))
self.assert_json_success(result)
def test_success_to_private(self) -> None:
mm_address = self.send_private_message()
result = self.send_offline_message(mm_address, self.example_email('cordelia'))
result = self.send_offline_message(mm_address, self.example_user('cordelia'))
self.assert_json_success(result)
def test_using_mm_address_multiple_times(self) -> None:
mm_address = self.send_private_message()
for i in range(0, MissedMessageEmailAddress.ALLOWED_USES):
result = self.send_offline_message(mm_address, self.example_email('cordelia'))
result = self.send_offline_message(mm_address, self.example_user('cordelia'))
self.assert_json_success(result)
result = self.send_offline_message(mm_address, self.example_email('cordelia'))
result = self.send_offline_message(mm_address, self.example_user('cordelia'))
self.assert_json_error(
result,
"5.1.1 Bad destination mailbox address: Missed message address out of uses.")
@ -1199,7 +1208,7 @@ class TestEmailMirrorTornadoView(ZulipTestCase):
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'))
result = self.send_offline_message(mm_address, self.example_user('cordelia'))
self.assert_json_error(
result,
"5.1.1 Bad destination mailbox address: Missed message address expired or doesn't exist.")
@ -1347,13 +1356,15 @@ class TestEmailMirrorLogAndReport(ZulipTestCase):
self.assertEqual(redacted_message, expected_message)
# Test for a missed message address:
cordelia = self.example_user('cordelia')
iago = self.example_user('iago')
result = self.client_post(
"/json/messages",
{
"type": "private",
"content": "test_redact_email_message",
"client": "test suite",
"to": ujson.dumps([self.example_email('cordelia'), self.example_email('iago')])
"to": ujson.dumps([cordelia.email, iago.email])
})
self.assert_json_success(result)

View File

@ -61,7 +61,7 @@ class TestFollowupEmails(ZulipTestCase):
with self.settings(AUTH_LDAP_USER_ATTR_MAP=ldap_user_attr_map):
self.login_with_return("newuser_email_as_uid@zulip.com",
self.ldap_password("newuser_email_as_uid@zulip.com"))
user = UserProfile.objects.get(email="newuser_email_as_uid@zulip.com")
user = UserProfile.objects.get(delivery_email="newuser_email_as_uid@zulip.com")
scheduled_emails = ScheduledEmail.objects.filter(users=user)
self.assertEqual(len(scheduled_emails), 2)
@ -81,7 +81,7 @@ class TestFollowupEmails(ZulipTestCase):
):
self.login_with_return("newuser@zulip.com", self.ldap_password("newuser"))
user = UserProfile.objects.get(email="newuser@zulip.com")
user = UserProfile.objects.get(delivery_email="newuser@zulip.com")
scheduled_emails = ScheduledEmail.objects.filter(users=user)
self.assertEqual(len(scheduled_emails), 2)
@ -100,7 +100,7 @@ class TestFollowupEmails(ZulipTestCase):
AUTH_LDAP_USER_ATTR_MAP=ldap_user_attr_map,
):
self.login_with_return("newuser_with_email", self.ldap_password("newuser_with_email"))
user = UserProfile.objects.get(email="newuser_email@zulip.com")
user = UserProfile.objects.get(delivery_email="newuser_email@zulip.com")
scheduled_emails = ScheduledEmail.objects.filter(users=user)
self.assertEqual(len(scheduled_emails), 2)

View File

@ -120,7 +120,7 @@ from zerver.lib.message import (
)
from zerver.lib.test_helpers import POSTRequestMock, get_subscription, \
get_test_image_file, stub_event_queue_user_events, queries_captured, \
create_dummy_file, stdout_suppressed
create_dummy_file, stdout_suppressed, reset_emails_in_zulip_realm
from zerver.lib.test_classes import (
ZulipTestCase,
)
@ -1041,6 +1041,8 @@ class EventsRegisterTest(ZulipTestCase):
self.assert_on_error(error)
def test_invitation_accept_invite_event(self) -> None:
reset_emails_in_zulip_realm()
schema_checker = self.check_events_dict([
('type', equals('invites_changed')),
])
@ -1258,7 +1260,7 @@ class EventsRegisterTest(ZulipTestCase):
error = realm_user_add_checker('events[0]', events[0])
self.assert_on_error(error)
new_user_profile = get_user_by_delivery_email("test1@zulip.com", self.user_profile.realm)
self.assertEqual(new_user_profile.email, "test1@zulip.com")
self.assertEqual(new_user_profile.delivery_email, "test1@zulip.com")
def test_register_events_email_address_visibility(self) -> None:
realm_user_add_checker = self.check_events_dict([
@ -1812,6 +1814,13 @@ class EventsRegisterTest(ZulipTestCase):
self.assert_on_error(error)
def test_change_is_admin(self) -> None:
reset_emails_in_zulip_realm()
# Important: We need to refresh from the database here so that
# we don't have a stale UserProfile object with an old value
# for email being passed into this next function.
self.user_profile.refresh_from_db()
schema_checker = self.check_events_dict([
('type', equals('realm_user')),
('op', equals('update')),
@ -1821,6 +1830,7 @@ class EventsRegisterTest(ZulipTestCase):
('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))
@ -3175,14 +3185,9 @@ class GetUnreadMsgsTest(ZulipTestCase):
def test_unread_msgs(self) -> None:
sender = self.example_user('cordelia')
sender_id = sender.id
sender_email = sender.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, user_profile, "hello1")
pm2_message_id = self.send_personal_message(sender, user_profile, "hello2")

View File

@ -496,15 +496,16 @@ class HomeTest(ZulipTestCase):
realm = get_realm('zulip')
self.login_user(hamlet)
bots = {}
for i in range(3):
self.create_bot(
bots[i] = 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(
defunct_user = self.create_non_active_user(
realm=realm,
email='defunct-%d@zulip.com' % (i,),
name='Defunct User %d' % (i,),
@ -543,20 +544,20 @@ class HomeTest(ZulipTestCase):
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']}
active_ids = {p['user_id'] for p in page_params['realm_users']}
non_active_ids = {p['user_id'] for p in page_params['realm_non_active_users']}
bot_ids = {p['user_id'] for p in page_params['realm_bots']}
self.assertIn(hamlet.email, active_emails)
self.assertIn('defunct-1@zulip.com', non_active_emails)
self.assertIn(hamlet.id, active_ids)
self.assertIn(defunct_user.id, non_active_ids)
# Bots can show up in multiple buckets.
self.assertIn('bot-2@zulip.com', bot_emails)
self.assertIn('bot-2@zulip.com', active_emails)
self.assertIn(bots[2].id, bot_ids)
self.assertIn(bots[2].id, active_ids)
# Make sure nobody got mis-bucketed.
self.assertNotIn(hamlet.email, non_active_emails)
self.assertNotIn('defunct-1@zulip.com', active_emails)
self.assertNotIn(hamlet.id, non_active_ids)
self.assertNotIn(defunct_user.id, active_ids)
cross_bots = page_params['cross_realm_bots']
self.assertEqual(len(cross_bots), 3)

View File

@ -46,7 +46,7 @@ class EmailTranslationTestCase(ZulipTestCase):
# Also remove the "nocoverage" from check_translation above.
# check_translation("Viele Grüße", "patch", "/json/settings", {"email": "hamlets-new@zulip.com"})
check_translation("Incrível!", "post", "/accounts/home/", {"email": "new-email@zulip.com"}, HTTP_ACCEPT_LANGUAGE="pt")
check_translation("Danke, dass Du", "post", '/accounts/find/', {'emails': hamlet.email})
check_translation("Danke, dass Du", "post", '/accounts/find/', {'emails': hamlet.delivery_email})
check_translation("Hallo", "post", "/json/invites", {"invitee_emails": "new-email@zulip.com",
"stream_ids": ujson.dumps([stream.id])})

View File

@ -471,7 +471,7 @@ class ImportExportTest(ZulipTestCase):
self.assertEqual(len(data['zerver_userprofile_crossrealm']), 3)
self.assertEqual(len(data['zerver_userprofile_mirrordummy']), 0)
exported_user_emails = self.get_set(data['zerver_userprofile'], 'email')
exported_user_emails = self.get_set(data['zerver_userprofile'], 'delivery_email')
self.assertIn(self.example_email('cordelia'), exported_user_emails)
self.assertIn('default-bot@zulip.com', exported_user_emails)
@ -514,13 +514,13 @@ class ImportExportTest(ZulipTestCase):
data = full_data['realm']
exported_user_emails = self.get_set(data['zerver_userprofile'], 'email')
exported_user_emails = self.get_set(data['zerver_userprofile'], 'delivery_email')
self.assertIn(self.example_email('iago'), 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('cordelia'), exported_user_emails)
dummy_user_emails = self.get_set(data['zerver_userprofile_mirrordummy'], 'email')
dummy_user_emails = self.get_set(data['zerver_userprofile_mirrordummy'], 'delivery_email')
self.assertIn(self.example_email('cordelia'), dummy_user_emails)
self.assertIn(self.example_email('othello'), dummy_user_emails)
self.assertIn('default-bot@zulip.com', dummy_user_emails)
@ -595,7 +595,7 @@ class ImportExportTest(ZulipTestCase):
self.assertEqual(len(data['zerver_userprofile_crossrealm']), 3)
self.assertEqual(len(data['zerver_userprofile_mirrordummy']), 0)
exported_user_emails = self.get_set(data['zerver_userprofile'], 'email')
exported_user_emails = self.get_set(data['zerver_userprofile'], 'delivery_email')
self.assertIn(self.example_email('cordelia'), exported_user_emails)
self.assertIn(self.example_email('hamlet'), exported_user_emails)
self.assertIn(self.example_email('iago'), exported_user_emails)
@ -986,8 +986,7 @@ class ImportExportTest(ZulipTestCase):
# affect how the browser displays the rendered_content so we
# are okay with using bs4 for this. lxml package also has
# similar behavior.
orig_polonius_user = UserProfile.objects.get(email=self.example_email("polonius"),
realm=original_realm)
orig_polonius_user = self.example_user('polonius')
original_msg = Message.objects.get(content=special_characters_message, sender__realm=original_realm)
self.assertEqual(
original_msg.rendered_content,
@ -995,7 +994,7 @@ class ImportExportTest(ZulipTestCase):
'<p><span class="user-mention" data-user-id="%s">@Polonius</span></p>' %
(orig_polonius_user.id,))
)
imported_polonius_user = UserProfile.objects.get(email=self.example_email("polonius"),
imported_polonius_user = UserProfile.objects.get(delivery_email=self.example_email("polonius"),
realm=imported_realm)
imported_msg = Message.objects.get(content=special_characters_message, sender__realm=imported_realm)
self.assertEqual(

View File

@ -59,7 +59,7 @@ class TestZulipBaseCommand(ZulipTestCase):
def test_get_user(self) -> None:
mit_realm = get_realm("zephyr")
user_profile = self.example_user("hamlet")
email = user_profile.email
email = user_profile.delivery_email
self.assertEqual(self.command.get_user(email, self.zulip_realm), user_profile)
self.assertEqual(self.command.get_user(email, None), user_profile)
@ -78,7 +78,7 @@ class TestZulipBaseCommand(ZulipTestCase):
def test_get_user_profile_by_email(self) -> None:
user_profile = self.example_user("hamlet")
email = user_profile.email
email = user_profile.delivery_email
self.assertEqual(get_user_profile_by_email(email), user_profile)
@ -87,16 +87,26 @@ class TestZulipBaseCommand(ZulipTestCase):
user_profiles = self.command.get_users(options, realm, **kwargs)
return sorted(user_profiles, key = lambda x: x.email)
def sorted_users(self, users: List[UserProfile]) -> List[UserProfile]:
return sorted(users, 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")]
expected_user_profiles = self.sorted_users([
self.example_user('hamlet'),
self.example_user('iago'),
])
user_emails = ','.join(u.delivery_email for u in expected_user_profiles)
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")]
expected_user_profiles = self.sorted_users([
self.mit_user('sipbtest'),
self.example_user('iago'),
])
user_emails = ','.join(u.delivery_email for u in expected_user_profiles)
user_profiles = self.get_users_sorted(dict(users=user_emails), None)
self.assertEqual(user_profiles, expected_user_profiles)
error_message = "The realm '%s' does not contain a user with email" % (self.zulip_realm,)
@ -109,8 +119,11 @@ class TestZulipBaseCommand(ZulipTestCase):
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")]
expected_user_profiles = self.sorted_users([
self.example_user('hamlet'),
self.example_user('iago'),
])
user_emails = ','.join(u.delivery_email for u in expected_user_profiles)
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."

View File

@ -60,13 +60,14 @@ from zerver.lib.message import (
)
from zerver.lib.test_helpers import (
get_subscription,
get_user_messages,
make_client,
message_stream_count,
most_recent_message,
most_recent_usermessage,
queries_captured,
get_subscription,
reset_emails_in_zulip_realm,
)
from zerver.lib.test_classes import (
@ -780,14 +781,16 @@ class PersonalMessagesTest(ZulipTestCase):
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 %s>>' % (user_profile.realm,))
self.assertEqual(
str(message),
'<Message: recip / / '
'<UserProfile: {} {}>>'.format(user_profile.email, user_profile.realm))
user_message = most_recent_usermessage(user_profile)
self.assertEqual(str(user_message),
'<UserMessage: recip / test@zulip.com ([])>'
)
self.assertEqual(
str(user_message),
'<UserMessage: recip / {} ([])>'.format(user_profile.email)
)
@slow("checks several profiles")
def test_personal_to_self(self) -> None:
@ -815,20 +818,16 @@ class PersonalMessagesTest(ZulipTestCase):
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:
def assert_personal(self, sender: UserProfile, receiver: UserProfile, 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))
other_user_profiles = UserProfile.objects.filter(~Q(id=sender.id) &
~Q(id=receiver.id))
old_other_messages = []
for user_profile in other_user_profiles:
old_other_messages.append(message_stream_count(user_profile))
@ -857,7 +856,10 @@ class PersonalMessagesTest(ZulipTestCase):
If you send a personal, only you and the recipient see it.
"""
self.login('hamlet')
self.assert_personal(self.example_email("hamlet"), self.example_email("othello"))
self.assert_personal(
sender=self.example_user("hamlet"),
receiver=self.example_user("othello")
)
def test_private_message_policy(self) -> None:
"""
@ -880,7 +882,11 @@ class PersonalMessagesTest(ZulipTestCase):
Sending a PM containing non-ASCII characters succeeds.
"""
self.login('hamlet')
self.assert_personal(self.example_email("hamlet"), self.example_email("othello"), u"hümbüǵ")
self.assert_personal(
sender=self.example_user("hamlet"),
receiver=self.example_user("othello"),
content="hümbüǵ"
)
class StreamMessagesTest(ZulipTestCase):
@ -1036,14 +1042,14 @@ class StreamMessagesTest(ZulipTestCase):
def test_stream_message_unicode(self) -> None:
receiving_user_profile = self.example_user('iago')
sending_user_profile = self.example_user('hamlet')
sender = self.example_user('hamlet')
self.subscribe(receiving_user_profile, "Denmark")
self.send_stream_message(sending_user_profile, "Denmark",
self.send_stream_message(sender, "Denmark",
content="whatever", topic_name="my topic")
message = most_recent_message(receiving_user_profile)
self.assertEqual(str(message),
u'<Message: Denmark / my topic / '
'<UserProfile: hamlet@zulip.com %s>>' % (sending_user_profile.realm,))
'<Message: Denmark / my topic / '
'<UserProfile: {} {}>>'.format(sender.email, sender.realm))
def test_message_mentions(self) -> None:
user_profile = self.example_user('iago')
@ -1705,10 +1711,11 @@ class MessagePOSTTest(ZulipTestCase):
"""
user_profile = self.example_user("hamlet")
self.login_user(user_profile)
othello = self.example_user('othello')
result = self.client_post("/json/messages", {"type": "private",
"content": "Test message",
"client": "test suite",
"to": self.example_email("othello")})
"to": othello.email})
self.assert_json_success(result)
message_id = ujson.loads(result.content.decode())['id']
@ -1716,21 +1723,21 @@ class MessagePOSTTest(ZulipTestCase):
self.assertEqual(len(recent_conversations), 1)
recent_conversation = list(recent_conversations.values())[0]
recipient_id = list(recent_conversations.keys())[0]
self.assertEqual(set(recent_conversation['user_ids']), set([self.example_user("othello").id]))
self.assertEqual(set(recent_conversation['user_ids']), set([othello.id]))
self.assertEqual(recent_conversation['max_message_id'], message_id)
# Now send a message to yourself and see how that interacts with the data structure
result = self.client_post("/json/messages", {"type": "private",
"content": "Test message",
"client": "test suite",
"to": self.example_email("hamlet")})
"to": user_profile.email})
self.assert_json_success(result)
self_message_id = ujson.loads(result.content.decode())['id']
recent_conversations = get_recent_private_conversations(user_profile)
self.assertEqual(len(recent_conversations), 2)
recent_conversation = recent_conversations[recipient_id]
self.assertEqual(set(recent_conversation['user_ids']), set([self.example_user("othello").id]))
self.assertEqual(set(recent_conversation['user_ids']), set([othello.id]))
self.assertEqual(recent_conversation['max_message_id'], message_id)
# Now verify we have the appropriate self-pm data structure
@ -1790,13 +1797,14 @@ class MessagePOSTTest(ZulipTestCase):
Sending a personal message to yourself plus another user is successful,
and counts as a message just to that user.
"""
self.login('hamlet')
hamlet = self.example_user('hamlet')
othello = self.example_user('othello')
self.login_user(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")])})
"to": ujson.dumps([hamlet.id, othello.id])})
self.assert_json_success(result)
msg = self.get_last_message()
# Verify that we're not actually on the "recipient list"
@ -1817,33 +1825,35 @@ class MessagePOSTTest(ZulipTestCase):
"""
Sending a personal message to a deactivated user returns error JSON.
"""
target_user_profile = self.example_user("othello")
do_deactivate_user(target_user_profile)
othello = self.example_user('othello')
cordelia = self.example_user('cordelia')
do_deactivate_user(othello)
self.login('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.")
"to": ujson.dumps([othello.id])})
self.assert_json_error(result, "'{}' is no longer using Zulip.".format(othello.email))
result = self.client_post("/json/messages", {
"type": "private",
"content": "Test message",
"client": "test suite",
"to": ujson.dumps([othello.id, cordelia.id])})
self.assert_json_error(result, "'{}' is no longer using Zulip.".format(othello.email))
def test_invalid_type(self) -> None:
"""
Sending a message of unknown type returns error JSON.
"""
self.login('hamlet')
othello = self.example_user('othello')
result = self.client_post("/json/messages", {"type": "invalid type",
"content": "Test message",
"client": "test suite",
"to": self.example_email("othello")})
"to": othello.email})
self.assert_json_error(result, "Invalid message type")
def test_empty_message(self) -> None:
@ -1851,10 +1861,11 @@ class MessagePOSTTest(ZulipTestCase):
Sending a message that is empty or only whitespace should fail
"""
self.login('hamlet')
othello = self.example_user('othello')
result = self.client_post("/json/messages", {"type": "private",
"content": " ",
"client": "test suite",
"to": self.example_email("othello")})
"to": othello.email})
self.assert_json_error(result, "Message must not be empty")
def test_empty_string_topic(self) -> None:
@ -2137,6 +2148,7 @@ class MessagePOSTTest(ZulipTestCase):
self.assert_json_error(result, "Mirroring not allowed with recipient user IDs")
def test_send_message_irc_mirror(self) -> None:
reset_emails_in_zulip_realm()
self.login('hamlet')
bot_info = {
'full_name': 'IRC bot',
@ -2187,6 +2199,8 @@ class MessagePOSTTest(ZulipTestCase):
self.assertEqual(int(datetime_to_timestamp(msg.date_sent)), int(fake_timestamp))
def test_unsubscribed_api_super_user(self) -> None:
reset_emails_in_zulip_realm()
cordelia = self.example_user('cordelia')
stream_name = 'private_stream'
self.make_stream(stream_name, invite_only=True)
@ -2312,7 +2326,7 @@ class MessagePOSTTest(ZulipTestCase):
email_to_full_name,
)
self.assertEqual(mirror_fred_user.email, email)
self.assertEqual(mirror_fred_user.delivery_email, email)
m.assert_called()
def test_guest_user(self) -> None:
@ -2389,7 +2403,9 @@ class ScheduledMessageTest(ZulipTestCase):
self.assertEqual(message.delivery_type, ScheduledMessage.REMIND)
# Scheduling a private message is successful.
result = self.do_schedule_message('private', self.example_email("othello"),
othello = self.example_user('othello')
hamlet = self.example_user('hamlet')
result = self.do_schedule_message('private', othello.email,
content + ' 3', defer_until_str)
message = self.last_scheduled_message()
self.assert_json_success(result)
@ -2398,14 +2414,14 @@ class ScheduledMessageTest(ZulipTestCase):
self.assertEqual(message.delivery_type, ScheduledMessage.SEND_LATER)
# Setting a reminder in PM's to other users causes a error.
result = self.do_schedule_message('private', self.example_email("othello"),
result = self.do_schedule_message('private', othello.email,
content + ' 4', defer_until_str,
delivery_type='remind')
self.assert_json_error(result, 'Reminders can only be set for streams.')
# Setting a reminder in PM's to ourself is successful.
# Required by reminders from message actions popover caret feature.
result = self.do_schedule_message('private', self.example_email("hamlet"),
result = self.do_schedule_message('private', hamlet.email,
content + ' 5', defer_until_str,
delivery_type='remind')
message = self.last_scheduled_message()
@ -3284,10 +3300,10 @@ class MirroredMessageUsersTest(ZulipTestCase):
self.assertTrue(mirror_sender.is_mirror_dummy)
def test_irc_mirror(self) -> None:
reset_emails_in_zulip_realm()
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')]
@ -3296,7 +3312,7 @@ class MirroredMessageUsersTest(ZulipTestCase):
request = Request(POST = dict(sender=sender.email, type='private'),
client = client)
mirror_sender = create_mirrored_message_users(request, user, recipients)
mirror_sender = create_mirrored_message_users(request, sender, recipients)
self.assertEqual(mirror_sender, sender)
@ -3309,6 +3325,7 @@ class MirroredMessageUsersTest(ZulipTestCase):
self.assertTrue(bob.is_mirror_dummy)
def test_jabber_mirror(self) -> None:
reset_emails_in_zulip_realm()
client = get_client(name='jabber_mirror')
sender = self.example_user('hamlet')
@ -3941,9 +3958,9 @@ class LogDictTest(ZulipTestCase):
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_email'], user.email)
self.assertEqual(dct['sender_full_name'], 'King Hamlet')
self.assertEqual(dct['sender_id'], self.example_user('hamlet').id)
self.assertEqual(dct['sender_id'], user.id)
self.assertEqual(dct['sender_short_name'], 'hamlet')
self.assertEqual(dct['sending_client'], 'test suite')
self.assertEqual(dct[DB_TOPIC_NAME], 'Copenhagen')
@ -3959,7 +3976,7 @@ class CheckMessageTest(ZulipTestCase):
message_content = 'whatever'
addressee = Addressee.for_stream_name(stream_name, topic_name)
ret = check_message(sender, client, addressee, message_content)
self.assertEqual(ret['message'].sender.email, self.example_email("othello"))
self.assertEqual(ret['message'].sender.id, sender.id)
def test_bot_pm_feature(self) -> None:
"""We send a PM to a bot's owner if their bot sends a message to

View File

@ -90,6 +90,8 @@ class NarrowBuilderTest(ZulipTestCase):
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"))
self.hamlet_email = self.example_user('hamlet').email
self.othello_email = self.example_user('othello').email
def test_add_term_using_not_defined_operator(self) -> None:
term = dict(operator='not-defined', operand='any')
@ -247,11 +249,11 @@ class NarrowBuilderTest(ZulipTestCase):
self._do_add_term_test(term, 'WHERE upper(subject) != upper(%(param_1)s)')
def test_add_term_using_sender_operator(self) -> None:
term = dict(operator='sender', operand=self.example_email("othello"))
term = dict(operator='sender', operand=self.othello_email)
self._do_add_term_test(term, 'WHERE sender_id = %(param_1)s')
def test_add_term_using_sender_operator_and_negated(self) -> None: # NEGATED
term = dict(operator='sender', operand=self.example_email("othello"), negated=True)
term = dict(operator='sender', operand=self.othello_email, negated=True)
self._do_add_term_test(term, 'WHERE sender_id != %(param_1)s')
def test_add_term_using_sender_operator_with_non_existing_user_as_operand(
@ -260,38 +262,54 @@ class NarrowBuilderTest(ZulipTestCase):
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"))
term = dict(operator='pm-with', operand=self.othello_email)
self._do_add_term_test(term, 'WHERE sender_id = %(sender_id_1)s AND recipient_id = %(recipient_id_1)s OR sender_id = %(sender_id_2)s AND recipient_id = %(recipient_id_2)s')
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)
term = dict(operator='pm-with', operand=self.othello_email, negated=True)
self._do_add_term_test(term, 'WHERE NOT (sender_id = %(sender_id_1)s AND recipient_id = %(recipient_id_1)s OR sender_id = %(sender_id_2)s AND recipient_id = %(recipient_id_2)s)')
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"))
term = dict(operator='pm-with', operand=self.hamlet_email)
self._do_add_term_test(term, 'WHERE sender_id = %(sender_id_1)s AND recipient_id = %(recipient_id_1)s')
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)
term = dict(operator='pm-with', operand=self.hamlet_email, negated=True)
self._do_add_term_test(term, 'WHERE NOT (sender_id = %(sender_id_1)s AND recipient_id = %(recipient_id_1)s)')
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')
myself_and_other = ','.join([
self.example_user('hamlet').email,
self.example_user('othello').email,
])
term = dict(operator='pm-with', operand=myself_and_other)
self._do_add_term_test(term, 'WHERE sender_id = %(sender_id_1)s AND recipient_id = %(recipient_id_1)s OR sender_id = %(sender_id_2)s AND recipient_id = %(recipient_id_2)s')
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')
two_others = ','.join([
self.example_user('cordelia').email,
self.example_user('othello').email,
])
term = dict(operator='pm-with', operand=two_others)
self._do_add_term_test(term, 'WHERE recipient_id = %(recipient_id_1)s')
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)
myself_and_other = ','.join([
self.example_user('hamlet').email,
self.example_user('othello').email,
])
term = dict(operator='pm-with', operand=myself_and_other, negated=True)
self._do_add_term_test(term, 'WHERE NOT (sender_id = %(sender_id_1)s AND recipient_id = %(recipient_id_1)s OR sender_id = %(sender_id_2)s AND recipient_id = %(recipient_id_2)s)')
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)
two_others = ','.join([
self.example_user('cordelia').email,
self.example_user('othello').email,
])
term = dict(operator='pm-with', operand=two_others, negated=True)
self._do_add_term_test(term, 'WHERE recipient_id != %(recipient_id_1)s')
def test_add_term_using_pm_with_operator_with_comma_noise(self) -> None:
@ -299,7 +317,7 @@ class NarrowBuilderTest(ZulipTestCase):
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')
term = dict(operator='pm-with', operand=self.othello_email + ',non-existing@zulip.com')
self.assertRaises(BadNarrowOperator, self._build_query, term)
def test_add_term_using_id_operator(self) -> None:
@ -319,19 +337,19 @@ class NarrowBuilderTest(ZulipTestCase):
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"))
term = dict(operator='group-pm-with', operand=self.othello_email)
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, [self.example_user("othello"),
self.example_user("cordelia")])
term = dict(operator='group-pm-with', operand=self.example_email("othello"))
term = dict(operator='group-pm-with', operand=self.othello_email)
self._do_add_term_test(term, 'WHERE recipient_id IN (%(recipient_id_1)s)')
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)
term = dict(operator='group-pm-with', operand=self.othello_email, 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:
@ -1151,11 +1169,25 @@ class GetOldMessagesTest(ZulipTestCase):
self.login('hamlet')
self.get_and_check_messages(dict())
othello_email = self.example_user('othello').email
# 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(
[['pm-with', othello_email]]
)
)
)
self.get_and_check_messages(dict(narrow=ujson.dumps([dict(operator='pm-with', operand=self.example_email("othello"))])))
self.get_and_check_messages(
dict(
narrow=ujson.dumps(
[dict(operator='pm-with', operand=othello_email)]
)
)
)
def test_client_avatar(self) -> None:
"""
@ -1164,6 +1196,9 @@ class GetOldMessagesTest(ZulipTestCase):
hamlet = self.example_user('hamlet')
self.login_user(hamlet)
do_set_realm_property(hamlet.realm, "email_address_visibility",
Realm.EMAIL_ADDRESS_VISIBILITY_EVERYONE)
self.send_personal_message(hamlet, self.example_user("iago"))
result = self.get_and_check_messages({})
@ -1243,7 +1278,7 @@ class GetOldMessagesTest(ZulipTestCase):
for i in range(5):
message_ids.append(self.send_personal_message(me, self.example_user("iago")))
narrow = [dict(operator='pm-with', operand=self.example_email("iago"))]
narrow = [dict(operator='pm-with', operand=self.example_user("iago").email)]
self.message_visibility_test(narrow, message_ids, 2)
def test_get_messages_with_narrow_group_pm_with(self) -> None:
@ -1253,57 +1288,48 @@ class GetOldMessagesTest(ZulipTestCase):
"""
me = self.example_user("hamlet")
iago = self.example_user("iago")
cordelia = self.example_user("cordelia")
othello = self.example_user("othello")
matching_message_ids = []
matching_message_ids.append(
self.send_huddle_message(
me,
[
self.example_user("iago"),
self.example_user("cordelia"),
self.example_user("othello"),
],
[iago, cordelia, othello]
),
)
matching_message_ids.append(
self.send_huddle_message(
me,
[
self.example_user("cordelia"),
self.example_user("othello"),
],
[cordelia, othello]
),
)
non_matching_message_ids = []
non_matching_message_ids.append(
self.send_personal_message(me, self.example_user("cordelia")),
self.send_personal_message(me, cordelia),
)
non_matching_message_ids.append(
self.send_huddle_message(
me,
[
self.example_user("iago"),
self.example_user("othello"),
],
[iago, othello]
),
)
non_matching_message_ids.append(
self.send_huddle_message(
self.example_user("cordelia"),
[
self.example_user("iago"),
self.example_user("othello"),
],
[iago, othello],
),
)
self.login_user(me)
test_operands = [self.example_email("cordelia"), self.example_user("cordelia").id]
test_operands = [cordelia.email, cordelia.id]
for operand in test_operands:
narrow = [dict(operator='group-pm-with', operand=operand)]
result = self.get_and_check_messages(dict(narrow=ujson.dumps(narrow)))
@ -1315,37 +1341,31 @@ class GetOldMessagesTest(ZulipTestCase):
me = self.example_user('hamlet')
self.login_user(me)
iago = self.example_user("iago")
cordelia = self.example_user("cordelia")
othello = self.example_user("othello")
message_ids = []
message_ids.append(
self.send_huddle_message(
me,
[
self.example_user("iago"),
self.example_user("cordelia"),
self.example_user("othello"),
],
[iago, cordelia, othello],
),
)
message_ids.append(
self.send_huddle_message(
me,
[
self.example_user("cordelia"),
self.example_user("othello"),
],
[cordelia, othello],
),
)
message_ids.append(
self.send_huddle_message(
me,
[
self.example_user("cordelia"),
self.example_user("iago"),
],
[cordelia, iago],
),
)
narrow = [dict(operator='group-pm-with', operand=self.example_email("cordelia"))]
narrow = [dict(operator='group-pm-with', operand=cordelia.email)]
self.message_visibility_test(narrow, message_ids, 1)
def test_include_history(self) -> None:
@ -1531,20 +1551,25 @@ class GetOldMessagesTest(ZulipTestCase):
messages sent by that person.
"""
self.login('hamlet')
hamlet = self.example_user('hamlet')
othello = self.example_user('othello')
iago = self.example_user('iago')
# 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_user("hamlet"), "Scotland")
self.send_stream_message(self.example_user("othello"), "Scotland")
self.send_personal_message(self.example_user("othello"), self.example_user("hamlet"))
self.send_stream_message(self.example_user("iago"), "Scotland")
self.send_stream_message(hamlet, "Scotland")
self.send_stream_message(othello, "Scotland")
self.send_personal_message(othello, hamlet)
self.send_stream_message(iago, "Scotland")
test_operands = [self.example_email("othello"), self.example_user("othello").id]
test_operands = [othello.email, othello.id]
for operand in test_operands:
narrow = [dict(operator='sender', operand=operand)]
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"))
self.assertEqual(message["sender_id"], othello.id)
def _update_tsvector_index(self) -> None:
# We use brute force here and update our text search index
@ -1611,9 +1636,11 @@ class GetOldMessagesTest(ZulipTestCase):
next_message_id = self.get_last_message().id + 1
cordelia = self.example_user('cordelia')
for topic, content in messages_to_search:
self.send_stream_message(
sender=self.example_user("cordelia"),
sender=cordelia,
stream_name="Verona",
content=content,
topic_name=topic,
@ -1622,7 +1649,7 @@ class GetOldMessagesTest(ZulipTestCase):
self._update_tsvector_index()
narrow = [
dict(operator='sender', operand=self.example_email("cordelia")),
dict(operator='sender', operand=cordelia.email),
dict(operator='search', operand='lunch'),
]
result = self.get_and_check_messages(dict(
@ -1946,9 +1973,12 @@ class GetOldMessagesTest(ZulipTestCase):
returns at most 1 message.
"""
self.login('cordelia')
anchor = self.send_stream_message(self.example_user("cordelia"), "Verona")
narrow = [dict(operator='sender', operand=self.example_email("cordelia"))]
cordelia = self.example_user('cordelia')
anchor = self.send_stream_message(cordelia, "Verona")
narrow = [dict(operator='sender', operand=cordelia.email)]
result = self.get_and_check_messages(dict(narrow=ujson.dumps(narrow),
anchor=anchor, num_before=0,
num_after=0)) # type: Dict[str, Any]
@ -2738,23 +2768,25 @@ recipient_id = %(recipient_id_3)s AND upper(subject) = upper(%(param_2)s))\
def test_get_messages_with_narrow_queries(self) -> None:
query_ids = self.get_query_ids()
hamlet_email = self.example_user('hamlet').email
othello_email = self.example_user('othello').email
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"),)},
'narrow': '[["pm-with", "%s"]]' % (othello_email,)},
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"),)},
'narrow': '[["pm-with", "%s"]]' % (othello_email,)},
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"),)},
'narrow': '[["pm-with", "%s"]]' % (othello_email,)},
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'
@ -2766,7 +2798,7 @@ recipient_id = %(recipient_id_3)s AND upper(subject) = upper(%(param_2)s))\
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"),)},
'narrow': '[["sender", "%s"]]' % (othello_email,)},
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'
@ -2803,7 +2835,7 @@ recipient_id = %(recipient_id_3)s AND upper(subject) = upper(%(param_2)s))\
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"),)},
'narrow': '[["pm-with", "%s"]]' % (hamlet_email,)},
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'
@ -2868,6 +2900,9 @@ WHERE user_profile_id = {hamlet_id} AND (content ILIKE '%jumping%' OR subject IL
def test_get_messages_with_search_using_email(self) -> None:
self.login('cordelia')
othello = self.example_user('othello')
cordelia = self.example_user('cordelia')
messages_to_search = [
('say hello', 'How are you doing, @**Othello, the Moor of Venice**?'),
('lunch plans', 'I am hungry!'),
@ -2876,7 +2911,7 @@ WHERE user_profile_id = {hamlet_id} AND (content ILIKE '%jumping%' OR subject IL
for topic, content in messages_to_search:
self.send_stream_message(
sender=self.example_user("cordelia"),
sender=cordelia,
stream_name="Verona",
content=content,
topic_name=topic,
@ -2885,8 +2920,8 @@ WHERE user_profile_id = {hamlet_id} AND (content ILIKE '%jumping%' OR subject IL
self._update_tsvector_index()
narrow = [
dict(operator='sender', operand=self.example_email("cordelia")),
dict(operator='search', operand=self.example_email("othello")),
dict(operator='sender', operand=cordelia.email),
dict(operator='search', operand=othello.email),
]
result = self.get_and_check_messages(dict(
narrow=ujson.dumps(narrow),
@ -2896,7 +2931,7 @@ WHERE user_profile_id = {hamlet_id} AND (content ILIKE '%jumping%' OR subject IL
self.assertEqual(len(result['messages']), 0)
narrow = [
dict(operator='sender', operand=self.example_email("cordelia")),
dict(operator='sender', operand=cordelia.email),
dict(operator='search', operand='othello'),
]
result = self.get_and_check_messages(dict(
@ -2911,7 +2946,6 @@ WHERE user_profile_id = {hamlet_id} AND (content ILIKE '%jumping%' OR subject IL
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">' +

View File

@ -34,13 +34,18 @@ class SendLoginEmailTest(ZulipTestCase):
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)
password = initial_password(user.delivery_email)
login_info = dict(
username=user.delivery_email,
password=password,
)
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},
self.client_post("/accounts/login/",
info=login_info,
HTTP_USER_AGENT=firefox_windows)
# email is sent and correct subject
@ -55,7 +60,8 @@ class SendLoginEmailTest(ZulipTestCase):
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},
self.client_post("/accounts/login/",
info=login_info,
HTTP_USER_AGENT=firefox_windows)
reference_time = mock_time.astimezone(user_tz).strftime('%A, %B %d, %Y at %H:%M %Z')

View File

@ -13,13 +13,13 @@ from zerver.lib.statistics import seconds_usage_between
from zerver.lib.test_helpers import (
make_client,
queries_captured,
reset_emails_in_zulip_realm,
)
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,
@ -161,53 +161,55 @@ class UserPresenceTests(ZulipTestCase):
def test_set_idle(self) -> None:
client = 'website'
user = self.example_user("hamlet")
email = user.email
self.login_user(user)
hamlet = self.example_user('hamlet')
othello = self.example_user('othello')
self.login_user(hamlet)
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']
self.assertEqual(json['presences'][hamlet.email][client]['status'], 'idle')
self.assertIn('timestamp', json['presences'][hamlet.email][client])
self.assertIsInstance(json['presences'][hamlet.email][client]['timestamp'], int)
self.assertEqual(list(json['presences'].keys()), [hamlet.email])
timestamp = json['presences'][hamlet.email][client]['timestamp']
user = self.example_user("othello")
email = user.email
self.login_user(user)
self.login_user(othello)
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.assertEqual(json['presences'][othello.email][client]['status'], 'idle')
self.assertEqual(json['presences'][hamlet.email][client]['status'], 'idle')
self.assertEqual(set(json['presences'].keys()), {hamlet.email, othello.email})
newer_timestamp = json['presences'][othello.email][client]['timestamp']
self.assertGreaterEqual(newer_timestamp, timestamp)
def test_set_active(self) -> None:
self.login('hamlet')
hamlet = self.example_user('hamlet')
othello = self.example_user('othello')
self.login_user(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')
self.assertEqual(result.json()['presences'][hamlet.email][client]['status'], 'idle')
email = self.example_email("othello")
self.login('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')
self.assertEqual(json['presences'][othello.email][client]['status'], 'idle')
self.assertEqual(json['presences'][hamlet.email][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')
self.assertEqual(json['presences'][othello.email][client]['status'], 'active')
self.assertEqual(json['presences'][hamlet.email][client]['status'], 'idle')
@mock.patch("stripe.Customer.list", return_value=[])
def test_new_user_input(self, unused_mock: mock.Mock) -> None:
@ -347,14 +349,16 @@ class UserPresenceTests(ZulipTestCase):
self.logout()
# Ensure we don't see hamlet@zulip.com information leakage
self.login('hamlet')
hamlet = self.example_user('hamlet')
self.login_user(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')
self.assertEqual(json['presences'][hamlet.email]["website"]['status'], 'idle')
self.assertEqual(
json['presences'].keys(),
{hamlet.email}
)
class SingleUserPresenceTests(ZulipTestCase):
def test_email_access(self) -> None:
@ -378,6 +382,7 @@ class SingleUserPresenceTests(ZulipTestCase):
self.assert_json_error(result, 'No presence data for email@zulip.com')
def test_single_user_get(self) -> None:
reset_emails_in_zulip_realm()
# First, we setup the test with some data
user = self.example_user("othello")
@ -431,7 +436,6 @@ class SingleUserPresenceTests(ZulipTestCase):
class UserPresenceAggregationTests(ZulipTestCase):
def _send_presence_for_aggregated_tests(self, user: UserProfile, status: str,
validate_time: datetime.datetime) -> Dict[str, Dict[str, Any]]:
email = user.email
self.login_user(user)
timezone_util = 'zerver.views.presence.timezone_now'
with mock.patch(timezone_util, return_value=validate_time - datetime.timedelta(seconds=5)):
@ -444,14 +448,15 @@ class UserPresenceAggregationTests(ZulipTestCase):
HTTP_USER_AGENT="ZulipIOS/1.0")
latest_result_dict = latest_result.json()
self.assertDictEqual(
latest_result_dict['presences'][email]['aggregated'],
latest_result_dict['presences'][user.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,))
result = self.client_get("/json/users/{}/presence".format(user.email))
return result.json()
def test_aggregated_info(self) -> None:

View File

@ -167,16 +167,16 @@ class PushBouncerNotificationTest(BouncerTestCase):
result = self.uuid_post(self.server_uuid, endpoint, {'user_id': user_id, 'token': token, 'token_kind': 17})
self.assert_json_error(result, "Invalid token type")
hamlet = self.example_user('hamlet')
result = self.api_post(
self.example_user("hamlet"),
hamlet,
endpoint,
dict(user_id=user_id, token_kin=token_kind, token=token),
)
self.assert_json_error(result, "Account is not associated with this subdomain",
status_code=401)
hamlet = self.example_user('hamlet')
# 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")
@ -1222,12 +1222,11 @@ class TestGetAPNsPayload(PushNotificationTest):
def test_get_message_payload_apns_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 = get_message_payload_apns(user_profile, message)
payload = get_message_payload_apns(self.sender, message)
expected = {
'alert': {
'title': '#Verona > Test Topic',
@ -1247,7 +1246,7 @@ class TestGetAPNsPayload(PushNotificationTest):
'server': settings.EXTERNAL_HOST,
'realm_id': self.sender.realm.id,
'realm_uri': self.sender.realm.uri,
"user_id": user_profile.id,
"user_id": self.sender.id,
}
}
}
@ -1364,10 +1363,10 @@ class TestGetGCMPayload(PushNotificationTest):
message.save()
message.trigger = 'mentioned'
user_profile = self.example_user('hamlet')
payload, gcm_options = get_message_payload_gcm(user_profile, message)
hamlet = self.example_user('hamlet')
payload, gcm_options = get_message_payload_gcm(hamlet, message)
self.assertDictEqual(payload, {
"user_id": user_profile.id,
"user_id": hamlet.id,
"event": "message",
"alert": "New mention from King Hamlet",
"zulip_message_id": message.id,
@ -1375,10 +1374,10 @@ class TestGetGCMPayload(PushNotificationTest):
"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"),
"realm_id": hamlet.realm.id,
"realm_uri": hamlet.realm.uri,
"sender_id": hamlet.id,
"sender_email": hamlet.email,
"sender_full_name": "King Hamlet",
"sender_avatar_url": absolute_avatar_url(message.sender),
"recipient_type": "stream",
@ -1392,10 +1391,10 @@ class TestGetGCMPayload(PushNotificationTest):
def test_get_message_payload_gcm_personal(self) -> None:
message = self.get_message(Recipient.PERSONAL, 1)
message.trigger = 'private_message'
user_profile = self.example_user('hamlet')
payload, gcm_options = get_message_payload_gcm(user_profile, message)
hamlet = self.example_user('hamlet')
payload, gcm_options = get_message_payload_gcm(hamlet, message)
self.assertDictEqual(payload, {
"user_id": user_profile.id,
"user_id": hamlet.id,
"event": "message",
"alert": "New private message from King Hamlet",
"zulip_message_id": message.id,
@ -1403,10 +1402,10 @@ class TestGetGCMPayload(PushNotificationTest):
"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"),
"realm_id": hamlet.realm.id,
"realm_uri": hamlet.realm.uri,
"sender_id": hamlet.id,
"sender_email": hamlet.email,
"sender_full_name": "King Hamlet",
"sender_avatar_url": absolute_avatar_url(message.sender),
"recipient_type": "private",
@ -1419,10 +1418,10 @@ class TestGetGCMPayload(PushNotificationTest):
message = self.get_message(Recipient.STREAM, 1)
message.trigger = 'stream_push_notify'
message.stream_name = 'Denmark'
user_profile = self.example_user('hamlet')
payload, gcm_options = get_message_payload_gcm(user_profile, message)
hamlet = self.example_user('hamlet')
payload, gcm_options = get_message_payload_gcm(hamlet, message)
self.assertDictEqual(payload, {
"user_id": user_profile.id,
"user_id": hamlet.id,
"event": "message",
"alert": "New stream message from King Hamlet in Denmark",
"zulip_message_id": message.id,
@ -1430,10 +1429,10 @@ class TestGetGCMPayload(PushNotificationTest):
"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"),
"realm_id": hamlet.realm.id,
"realm_uri": hamlet.realm.uri,
"sender_id": hamlet.id,
"sender_email": hamlet.email,
"sender_full_name": "King Hamlet",
"sender_avatar_url": absolute_avatar_url(message.sender),
"recipient_type": "stream",
@ -1449,10 +1448,10 @@ class TestGetGCMPayload(PushNotificationTest):
message = self.get_message(Recipient.STREAM, 1)
message.trigger = 'stream_push_notify'
message.stream_name = 'Denmark'
user_profile = self.example_user('hamlet')
payload, gcm_options = get_message_payload_gcm(user_profile, message)
hamlet = self.example_user('hamlet')
payload, gcm_options = get_message_payload_gcm(hamlet, message)
self.assertDictEqual(payload, {
"user_id": user_profile.id,
"user_id": hamlet.id,
"event": "message",
"alert": "New stream message from King Hamlet in Denmark",
"zulip_message_id": message.id,
@ -1460,10 +1459,10 @@ class TestGetGCMPayload(PushNotificationTest):
"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"),
"realm_id": hamlet.realm.id,
"realm_uri": hamlet.realm.uri,
"sender_id": hamlet.id,
"sender_email": hamlet.email,
"sender_full_name": "King Hamlet",
"sender_avatar_url": absolute_avatar_url(message.sender),
"recipient_type": "stream",

View File

@ -216,13 +216,13 @@ class ReactionMessageIDTest(ZulipTestCase):
Reacting to a inaccessible (for instance, private) message fails
"""
pm_sender = self.example_user("hamlet")
pm_recipient = self.example_email("othello")
pm_recipient = self.example_user("othello")
reaction_sender = self.example_user("iago")
result = self.api_post(pm_sender,
"/api/v1/messages", {"type": "private",
"content": "Test message",
"to": pm_recipient})
"to": pm_recipient.email})
self.assert_json_success(result)
pm_id = result.json()['id']
reaction_info = {

View File

@ -23,7 +23,10 @@ from confirmation.models import create_confirmation_link, Confirmation
from zerver.lib.realm_description import get_realm_rendered_description, get_realm_text_description
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_helpers import (
reset_emails_in_zulip_realm,
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, \
@ -241,7 +244,7 @@ class RealmTest(ZulipTestCase):
self.assertIn('Reactivate your Zulip organization', outbox[0].subject)
self.assertIn('Dear former administrators', outbox[0].body)
admins = realm.get_human_admin_users()
confirmation_url = self.get_confirmation_url_from_outbox(admins[0].email)
confirmation_url = self.get_confirmation_url_from_outbox(admins[0].delivery_email)
response = self.client_get(confirmation_url)
self.assert_in_success_response(['Your organization has been successfully reactivated'], response)
realm = get_realm('zulip')
@ -392,8 +395,9 @@ class RealmTest(ZulipTestCase):
result = self.client_patch('/json/realm', req)
self.assert_json_error(result, 'Invalid email_address_visibility')
reset_emails_in_zulip_realm()
realm = get_realm("zulip")
self.assertEqual(realm.email_address_visibility, Realm.EMAIL_ADDRESS_VISIBILITY_EVERYONE)
req = dict(email_address_visibility = ujson.dumps(Realm.EMAIL_ADDRESS_VISIBILITY_ADMINS))
result = self.client_patch('/json/realm', req)
self.assert_json_success(result)

View File

@ -125,7 +125,7 @@ class TestReport(ZulipTestCase):
self.assertEqual(report[k], params[k])
self.assertEqual(report['more_info'], dict(foo='bar', draft_content="'**xxxxx**'"))
self.assertEqual(report['user_email'], user.email)
self.assertEqual(report['user_email'], user.delivery_email)
# Teset with no more_info
del params['more_info']

View File

@ -70,7 +70,7 @@ class ChangeSettingsTest(ZulipTestCase):
"/json/settings",
dict(
full_name='Foo Bar',
old_password=initial_password(user.email),
old_password=initial_password(user.delivery_email),
new_password='foobar1',
))
self.assert_json_success(json_result)
@ -86,7 +86,7 @@ class ChangeSettingsTest(ZulipTestCase):
# with as few moving parts as possible).
self.assertTrue(
self.client.login(
username=user.email,
username=user.delivery_email,
password='foobar1',
realm=user.realm
)

View File

@ -11,7 +11,11 @@ from django.utils.timezone import now as timezone_now
from django.core.exceptions import ValidationError
from mock import patch, MagicMock
from zerver.lib.test_helpers import get_test_image_file, avatar_disk_path
from zerver.lib.test_helpers import (
avatar_disk_path,
get_test_image_file,
reset_emails_in_zulip_realm,
)
from confirmation.models import Confirmation, create_confirmation_link, MultiuseInvite, \
generate_key, confirmation_url, get_object_from_key, ConfirmationKeyException, \
@ -219,7 +223,7 @@ class PasswordResetTest(ZulipTestCase):
def test_password_reset(self) -> None:
user = self.example_user("hamlet")
email = user.email
email = user.delivery_email
old_password = initial_password(email)
self.login_user(user)
@ -310,7 +314,7 @@ class PasswordResetTest(ZulipTestCase):
def test_password_reset_for_deactivated_user(self) -> None:
user_profile = self.example_user("hamlet")
email = user_profile.email
email = user_profile.delivery_email
do_deactivate_user(user_profile)
# start the password reset process by supplying an email address
@ -338,7 +342,7 @@ class PasswordResetTest(ZulipTestCase):
def test_password_reset_with_deactivated_realm(self) -> None:
user_profile = self.example_user("hamlet")
email = user_profile.email
email = user_profile.delivery_email
do_deactivate_realm(user_profile.realm)
# start the password reset process by supplying an email address
@ -361,7 +365,7 @@ class PasswordResetTest(ZulipTestCase):
@override_settings(RATE_LIMITING=True)
def test_rate_limiting(self) -> None:
user_profile = self.example_user("hamlet")
email = user_profile.email
email = user_profile.delivery_email
from django.core.mail import outbox
add_ratelimit_rule(10, 2, domain='password_reset_form_by_email')
@ -523,15 +527,24 @@ class LoginTest(ZulipTestCase):
self.assert_logged_in_user_id(None)
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)
user = self.example_user("hamlet")
password = "wrongpassword"
result = self.login_with_return(user.delivery_email, password=password)
self.assert_in_success_response([user.delivery_email], result)
self.assert_logged_in_user_id(None)
# Parallel test to confirm that the right password works using the
# same login code, which verifies our failing test isn't broken
# for some other reason.
password = initial_password(user.delivery_email)
result = self.login_with_return(user.delivery_email, password=password)
self.assertEqual(result.status_code, 302)
self.assert_logged_in_user_id(user.id)
@override_settings(RATE_LIMITING_AUTHENTICATE=True)
def test_login_bad_password_rate_limiter(self) -> None:
user_profile = self.example_user("hamlet")
email = user_profile.email
email = user_profile.delivery_email
add_ratelimit_rule(10, 2, domain='authenticate_by_username')
start_time = time.time()
@ -576,6 +589,8 @@ class LoginTest(ZulipTestCase):
self.assert_logged_in_user_id(None)
def test_register(self) -> None:
reset_emails_in_zulip_realm()
realm = get_realm("zulip")
stream_names = ["stream_{}".format(i) for i in range(40)]
for stream_name in stream_names:
@ -1074,7 +1089,9 @@ class InviteUserTest(InviteUserBase):
# 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"))
self.assertTrue(second_msg.content.startswith(
"alice_zulip.com <`{}`> accepted your".format(invitee_profile.email)
))
# The second, from welcome-bot to the user who was invited.
third_msg = last_3_messages[2]
@ -1477,10 +1494,13 @@ class InvitationsTestCase(InviteUserBase):
referred_by=user_profile, status=active_value)
prereg_user_three.save()
multiuse_invite_one = MultiuseInvite.objects.create(referred_by=self.example_user("hamlet"), realm=realm)
hamlet = self.example_user('hamlet')
othello = self.example_user('othello')
multiuse_invite_one = MultiuseInvite.objects.create(referred_by=hamlet, realm=realm)
create_confirmation_link(multiuse_invite_one, realm.host, Confirmation.MULTIUSE_INVITE)
multiuse_invite_two = MultiuseInvite.objects.create(referred_by=self.example_user("othello"), realm=realm)
multiuse_invite_two = MultiuseInvite.objects.create(referred_by=othello, realm=realm)
create_confirmation_link(multiuse_invite_two, realm.host, Confirmation.MULTIUSE_INVITE)
confirmation = Confirmation.objects.last()
confirmation.date_sent = expired_datetime
@ -1488,8 +1508,12 @@ class InvitationsTestCase(InviteUserBase):
result = self.client_get("/json/invites")
self.assertEqual(result.status_code, 200)
self.assert_in_success_response(["TestOne@zulip.com", "hamlet@zulip.com"], result)
self.assert_not_in_success_response(["TestTwo@zulip.com", "TestThree@zulip.com", "othello@zulip.com"], result)
self.assert_in_success_response(
["TestOne@zulip.com", hamlet.email],
result)
self.assert_not_in_success_response(
["TestTwo@zulip.com", "TestThree@zulip.com", "othello@zulip.com", othello.email],
result)
def test_successful_delete_invitation(self) -> None:
"""
@ -2269,7 +2293,7 @@ class UserSignUpTest(InviteUserBase):
self.assertEqual(result.status_code, 302)
get_user(email, realm)
self.assertEqual(UserProfile.objects.filter(email=email).count(), 2)
self.assertEqual(UserProfile.objects.filter(delivery_email=email).count(), 2)
def test_signup_invalid_name(self) -> None:
"""
@ -2484,8 +2508,8 @@ class UserSignUpTest(InviteUserBase):
result = self.submit_reg_form_for_user(email,
password,
full_name="New Guy")
user_profile = UserProfile.objects.get(email=email)
self.assertEqual(user_profile.email, email)
user_profile = UserProfile.objects.get(delivery_email=email)
self.assertEqual(user_profile.delivery_email, email)
# Now try to to register using the first confirmation url:
result = self.client_get(first_confirmation_url)
@ -2542,13 +2566,13 @@ class UserSignUpTest(InviteUserBase):
"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')
hamlet_in_zulip = self.example_user('hamlet')
email = hamlet_in_zulip.delivery_email
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"
@ -2577,16 +2601,16 @@ class UserSignUpTest(InviteUserBase):
self.assertEqual(hamlet.tutorial_status, UserProfile.TUTORIAL_WAITING)
def test_signup_with_user_settings_from_another_realm(self) -> None:
email = self.example_email('hamlet')
hamlet_in_zulip = self.example_user('hamlet')
email = hamlet_in_zulip.delivery_email
password = "newpassword"
subdomain = "lear"
lear_realm = get_realm("lear")
zulip_realm = get_realm("zulip")
self.login('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.refresh_from_db()
hamlet_in_zulip.left_side_userlist = True
hamlet_in_zulip.default_language = "de"
hamlet_in_zulip.emojiset = "twitter"
@ -2616,7 +2640,7 @@ class UserSignUpTest(InviteUserBase):
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)
hamlet_in_lear = get_user(email, 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")
@ -2624,9 +2648,14 @@ class UserSignUpTest(InviteUserBase):
self.assertEqual(hamlet_in_lear.enter_sends, True)
self.assertEqual(hamlet_in_lear.enable_stream_audible_notifications, 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())
lear_path_id = avatar_disk_path(hamlet_in_lear)
zulip_avatar_bits = open(zulip_path_id, 'rb').read()
lear_avatar_bits = open(lear_path_id, 'rb').read()
self.assertTrue(len(zulip_avatar_bits) > 500)
self.assertEqual(zulip_avatar_bits, lear_avatar_bits)
def test_signup_invalid_subdomain(self) -> None:
"""
@ -2913,7 +2942,7 @@ class UserSignUpTest(InviteUserBase):
HTTP_HOST=subdomain + ".testserver")
# Didn't create an account
with self.assertRaises(UserProfile.DoesNotExist):
user_profile = UserProfile.objects.get(email=email)
user_profile = UserProfile.objects.get(delivery_email=email)
self.assertEqual(result.status_code, 302)
self.assertEqual(result.url, "/accounts/login/?email=newuser%40zulip.com")
@ -2923,7 +2952,7 @@ class UserSignUpTest(InviteUserBase):
full_name=full_name,
# Pass HTTP_HOST for the target subdomain
HTTP_HOST=subdomain + ".testserver")
user_profile = UserProfile.objects.get(email=email)
user_profile = UserProfile.objects.get(delivery_email=email)
# Name comes from form which was set by LDAP.
self.assertEqual(user_profile.full_name, full_name)
# Short name comes from LDAP.
@ -2966,7 +2995,7 @@ class UserSignUpTest(InviteUserBase):
full_name="Ignore",
# Pass HTTP_HOST for the target subdomain
HTTP_HOST=subdomain + ".testserver")
user_profile = UserProfile.objects.get(email=email)
user_profile = UserProfile.objects.get(delivery_email=email)
# Name comes from form which was set by LDAP.
self.assertEqual(user_profile.full_name, "First Last")
# Short name comes from LDAP.
@ -3003,7 +3032,7 @@ class UserSignUpTest(InviteUserBase):
self.login_with_return(email, password,
HTTP_HOST=subdomain + ".testserver")
user_profile = UserProfile.objects.get(email=email)
user_profile = UserProfile.objects.get(delivery_email=email)
# Name comes from form which was set by LDAP.
self.assertEqual(user_profile.full_name, full_name)
self.assertEqual(user_profile.short_name, 'shortname')
@ -3035,8 +3064,8 @@ class UserSignUpTest(InviteUserBase):
self.login_with_return(email, password,
HTTP_HOST=subdomain + ".testserver")
user_profile = UserProfile.objects.get(email=email, realm=get_realm('zulip'))
self.assertEqual(user_profile.email, email)
user_profile = UserProfile.objects.get(
delivery_email=email, realm=get_realm('zulip'))
self.logout()
# Test registration in another realm works.
@ -3044,8 +3073,9 @@ class UserSignUpTest(InviteUserBase):
self.login_with_return(email, password,
HTTP_HOST=subdomain + ".testserver")
user_profile = UserProfile.objects.get(email=email, realm=get_realm('test'))
self.assertEqual(user_profile.email, email)
user_profile = UserProfile.objects.get(
delivery_email=email, realm=get_realm('test'))
self.assertEqual(user_profile.delivery_email, email)
@override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',
'zproject.backends.ZulipDummyBackend'))
@ -3086,7 +3116,7 @@ class UserSignUpTest(InviteUserBase):
password,
# Pass HTTP_HOST for the target subdomain
HTTP_HOST=subdomain + ".testserver")
user_profile = UserProfile.objects.get(email=email)
user_profile = UserProfile.objects.get(delivery_email=email)
# Name comes from LDAP session.
self.assertEqual(user_profile.full_name, 'New LDAP fullname')
@ -3133,7 +3163,7 @@ class UserSignUpTest(InviteUserBase):
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())
self.assertFalse(UserProfile.objects.filter(delivery_email=email).exists())
# For the rest of the test we delete the user from ldap.
del self.mock_ldap.directory["uid=newuser,ou=users,dc=zulip,dc=com"]
@ -3154,7 +3184,7 @@ class UserSignUpTest(InviteUserBase):
# We get redirected back to the login page because emails matching LDAP_APPEND_DOMAIN,
# aren't allowed to create non-ldap accounts.
self.assertEqual(result.url, "/accounts/login/?email=newuser%40zulip.com")
self.assertFalse(UserProfile.objects.filter(email=email).exists())
self.assertFalse(UserProfile.objects.filter(delivery_email=email).exists())
# If the email is outside of LDAP_APPEND_DOMAIN, we succesfully create a non-ldap account,
# with the password managed in the zulip database.
@ -3180,7 +3210,7 @@ class UserSignUpTest(InviteUserBase):
HTTP_HOST=subdomain + ".testserver")
self.assertEqual(result.status_code, 302)
self.assertEqual(result.url, "http://zulip.testserver/")
user_profile = UserProfile.objects.get(email=email)
user_profile = UserProfile.objects.get(delivery_email=email)
# Name comes from the POST request, not LDAP
self.assertEqual(user_profile.full_name, 'Non-LDAP Full Name')
@ -3227,7 +3257,7 @@ class UserSignUpTest(InviteUserBase):
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_email%40zulip.com")
self.assertFalse(UserProfile.objects.filter(email=email).exists())
self.assertFalse(UserProfile.objects.filter(delivery_email=email).exists())
# If the user's email is not in the LDAP directory , though, we
# successfully create an account with a password in the Zulip
@ -3266,7 +3296,7 @@ class UserSignUpTest(InviteUserBase):
HTTP_HOST=subdomain + ".testserver")
self.assertEqual(result.status_code, 302)
self.assertEqual(result.url, "http://zulip.testserver/")
user_profile = UserProfile.objects.get(email=email)
user_profile = UserProfile.objects.get(delivery_email=email)
# Name comes from the POST request, not LDAP
self.assertEqual(user_profile.full_name, 'Non-LDAP Full Name')
@ -3310,14 +3340,16 @@ class UserSignUpTest(InviteUserBase):
'zproject.backends.EmailAuthBackend'))
def test_ldap_invite_user_as_admin(self) -> None:
self.ldap_invite_and_signup_as(PreregistrationUser.INVITE_AS['REALM_ADMIN'])
user_profile = UserProfile.objects.get(email=self.nonreg_email('newuser'))
user_profile = UserProfile.objects.get(
delivery_email=self.nonreg_email('newuser'))
self.assertTrue(user_profile.is_realm_admin)
@override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',
'zproject.backends.EmailAuthBackend'))
def test_ldap_invite_user_as_guest(self) -> None:
self.ldap_invite_and_signup_as(PreregistrationUser.INVITE_AS['GUEST_USER'])
user_profile = UserProfile.objects.get(email=self.nonreg_email('newuser'))
user_profile = UserProfile.objects.get(
delivery_email=self.nonreg_email('newuser'))
self.assertTrue(user_profile.is_guest)
@override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend',
@ -3333,7 +3365,7 @@ class UserSignUpTest(InviteUserBase):
# Invite user.
self.ldap_invite_and_signup_as(PreregistrationUser.INVITE_AS['REALM_ADMIN'], streams=[stream_name])
user_profile = UserProfile.objects.get(email=self.nonreg_email('newuser'))
user_profile = UserProfile.objects.get(delivery_email=self.nonreg_email('newuser'))
self.assertTrue(user_profile.is_realm_admin)
sub = get_stream_subscriptions_for_user(user_profile).filter(recipient__type_id=stream.id)
self.assertEqual(len(sub), 1)
@ -3361,7 +3393,7 @@ class UserSignUpTest(InviteUserBase):
full_name="New Name",
# Pass HTTP_HOST for the target subdomain
HTTP_HOST=subdomain + ".testserver")
user_profile = UserProfile.objects.get(email=email)
user_profile = UserProfile.objects.get(delivery_email=email)
# 'New Name' comes from POST data; not from LDAP session.
self.assertEqual(user_profile.full_name, 'New Name')
@ -3425,7 +3457,7 @@ class UserSignUpTest(InviteUserBase):
password = "test"
subdomain = "zephyr"
user_profile = self.mit_user("sipbtest")
email = user_profile.email
email = user_profile.delivery_email
user_profile.is_mirror_dummy = True
user_profile.is_active = False
user_profile.save()
@ -3486,7 +3518,7 @@ class UserSignUpTest(InviteUserBase):
raise an AssertionError.
"""
user_profile = self.mit_user("sipbtest")
email = user_profile.email
email = user_profile.delivery_email
user_profile.is_mirror_dummy = True
user_profile.is_active = True
user_profile.save()
@ -3505,7 +3537,7 @@ class UserSignUpTest(InviteUserBase):
user_profile = UserProfile.objects.all().order_by("id").last()
self.assertEqual(result.status_code, 302)
self.assertEqual(user_profile.email, email)
self.assertEqual(user_profile.delivery_email, email)
self.assertEqual(result['Location'], "http://zulip.testserver/")
self.assert_logged_in_user_id(user_profile.id)

View File

@ -10,7 +10,8 @@ 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
get_subscription, queries_captured, tornado_redirected_to_list,
reset_emails_in_zulip_realm
)
from zerver.lib.test_classes import (
@ -240,6 +241,10 @@ class TestCreateStreams(ZulipTestCase):
self.assertFalse(stream.history_public_to_subscribers)
def test_auto_mark_stream_created_message_as_read_for_stream_creator(self) -> None:
# This test relies on email == delivery_email for
# convenience.
reset_emails_in_zulip_realm()
realm = Realm.objects.get(name='Zulip Dev')
iago = self.example_user('iago')
hamlet = self.example_user('hamlet')
@ -679,9 +684,11 @@ class StreamAdminTest(ZulipTestCase):
def test_realm_admin_can_update_unsub_private_stream(self) -> None:
iago = self.example_user('iago')
hamlet = self.example_user('hamlet')
self.login_user(iago)
result = self.common_subscribe_to_streams(iago, ["private_stream"],
dict(principals=ujson.dumps([self.example_email("hamlet")])),
dict(principals=ujson.dumps([hamlet.email])),
invite_only=True)
self.assert_json_success(result)
@ -2654,13 +2661,16 @@ class SubscriptionAPITest(ZulipTestCase):
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")]
othello = self.example_user('othello')
cordelia = self.example_user('cordelia')
iago = self.example_user('iago')
orig_emails_to_subscribe = [self.test_email, othello.email]
self.common_subscribe_to_streams(
self.test_user,
streams_to_sub,
dict(principals=ujson.dumps(orig_emails_to_subscribe)))
new_emails_to_subscribe = [self.example_email("iago"), self.example_email("cordelia")]
new_emails_to_subscribe = [iago.email, cordelia.email]
events = [] # type: List[Mapping[str, Any]]
with tornado_redirected_to_list(events):
self.common_subscribe_to_streams(
@ -2826,15 +2836,18 @@ class SubscriptionAPITest(ZulipTestCase):
You can't subscribe deactivated people to streams.
"""
target_profile = self.example_user("cordelia")
result = self.common_subscribe_to_streams(self.test_user, "Verona",
{"principals": ujson.dumps([target_profile.email])})
post_data = dict(
principals=ujson.dumps([target_profile.email])
)
result = self.common_subscribe_to_streams(self.test_user, "Verona", post_data)
self.assert_json_success(result)
do_deactivate_user(target_profile)
result = self.common_subscribe_to_streams(self.test_user, "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)
result = self.common_subscribe_to_streams(self.test_user, "Denmark", post_data)
self.assert_json_error(
result,
"User not authorized to execute queries on behalf of '{}'".format(target_profile.email),
status_code=403)
def test_subscriptions_add_for_principal_invite_only(self) -> None:
"""
@ -2851,7 +2864,8 @@ class SubscriptionAPITest(ZulipTestCase):
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üǵ"])
iago = self.example_user('iago')
self.assert_adding_subscriptions_for_principal(iago.email, get_realm('zulip'), [u"hümbüǵ"])
def test_subscription_add_invalid_principal(self) -> None:
"""
@ -3447,29 +3461,26 @@ class InviteOnlyStreamTest(ZulipTestCase):
@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
hamlet = self.example_user('hamlet')
othello = self.example_user('othello')
stream_name = "Saxony"
result = self.common_subscribe_to_streams(user_profile, [stream_name], invite_only=True)
result = self.common_subscribe_to_streams(hamlet, [stream_name], invite_only=True)
self.assert_json_success(result)
json = result.json()
self.assertEqual(json["subscribed"], {email: [stream_name]})
self.assertEqual(json["subscribed"], {hamlet.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_user(user_profile)
result = self.common_subscribe_to_streams(user_profile, [stream_name])
self.login_user(othello)
result = self.common_subscribe_to_streams(othello, [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_user(user_profile)
result = self.common_subscribe_to_streams(user_profile, [stream_name],
self.login_user(othello)
result = self.common_subscribe_to_streams(othello, [stream_name],
extra_post_data={'authorization_errors_fatal': ujson.dumps(False)})
self.assert_json_success(result)
json = result.json()
@ -3478,31 +3489,29 @@ class InviteOnlyStreamTest(ZulipTestCase):
self.assertEqual(json["already_subscribed"], {})
# Inviting another user to an invite-only stream is allowed
user_profile = self.example_user('hamlet')
self.login_user(user_profile)
self.login_user(hamlet)
result = self.common_subscribe_to_streams(
user_profile, [stream_name],
extra_post_data={'principals': ujson.dumps([self.example_email("othello")])})
hamlet, [stream_name],
extra_post_data={'principals': ujson.dumps([othello.email])})
self.assert_json_success(result)
json = result.json()
self.assertEqual(json["subscribed"], {self.example_email("othello"): [stream_name]})
self.assertEqual(json["subscribed"], {othello.email: [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(user_profile, "/api/v1/streams/%d/members" % (stream_id,))
stream_id = get_stream(stream_name, hamlet.realm).id
result = self.api_get(hamlet, "/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'])
self.assertTrue(othello.email in json['subscribers'])
self.assertTrue(hamlet.email in json['subscribers'])
class GetSubscribersTest(ZulipTestCase):
def setUp(self) -> None:
super().setUp()
self.user_profile = self.example_user('hamlet')
self.email = self.user_profile.email
self.login_user(self.user_profile)
def assert_user_got_subscription_notification(self, expected_msg: str) -> None:
@ -3562,7 +3571,11 @@ class GetSubscribersTest(ZulipTestCase):
for stream_name in streams:
self.make_stream(stream_name)
users_to_subscribe = [self.email, self.example_email("othello"), self.example_email("cordelia")]
users_to_subscribe = [
self.user_profile.email,
self.example_user("othello").email,
self.example_user("cordelia").email,
]
ret = self.common_subscribe_to_streams(
self.user_profile,
streams,
@ -3591,7 +3604,7 @@ class GetSubscribersTest(ZulipTestCase):
ret = self.common_subscribe_to_streams(
self.user_profile,
["stream_invite_only_1"],
dict(principals=ujson.dumps([self.email])),
dict(principals=ujson.dumps([self.user_profile.email])),
invite_only=True)
self.assert_json_success(ret)
@ -3626,8 +3639,8 @@ class GetSubscribersTest(ZulipTestCase):
"""
realm = get_realm("zulip")
users_to_subscribe = [
self.example_email("othello"),
self.example_email("cordelia"),
self.example_user("othello").email,
self.example_user("cordelia").email,
]
public_streams = [

View File

@ -289,16 +289,17 @@ class UnreadCountTests(ZulipTestCase):
differences = [key for key in expected if expected[key] != event[key]]
self.assertTrue(len(differences) == 0)
hamlet = self.example_user('hamlet')
um = list(UserMessage.objects.filter(message=message_id))
for msg in um:
if msg.user_profile.email == self.example_email("hamlet"):
if msg.user_profile.email == hamlet.email:
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"):
if msg.user_profile.email == hamlet.email:
self.assertFalse(msg.flags.read)
def test_mark_all_in_invalid_stream_read(self) -> None:
@ -347,12 +348,12 @@ class UnreadCountTests(ZulipTestCase):
um = list(UserMessage.objects.filter(message=message_id))
for msg in um:
if msg.user_profile.email == self.example_email("hamlet"):
if msg.user_profile_id == user_profile.id:
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"):
if msg.user_profile_id == user_profile.id:
self.assertFalse(msg.flags.read)
def test_mark_all_in_invalid_topic_read(self) -> None:

View File

@ -27,7 +27,7 @@ from zerver.lib.upload import sanitize_name, S3UploadBackend, \
DEFAULT_AVATAR_SIZE, DEFAULT_EMOJI_SIZE, exif_rotate, \
upload_export_tarball, delete_export_tarball
import zerver.lib.upload
from zerver.models import Attachment, get_user, \
from zerver.models import Attachment, get_user_by_delivery_email, \
Message, UserProfile, Realm, \
RealmDomain, RealmEmoji, get_realm, get_system_bot, \
validate_attachment_request
@ -453,7 +453,7 @@ class FileUploadTest(UploadSerializeMixin, ZulipTestCase):
password = initial_password(email)
if password is not None:
self.register(email, password, subdomain=realm_id)
return get_user(email, get_realm(realm_id))
return get_user_by_delivery_email(email, get_realm(realm_id))
test_subdomain = "uploadtest.example.com"
user1_email = 'user1@uploadtest.example.com'
@ -476,11 +476,11 @@ class FileUploadTest(UploadSerializeMixin, ZulipTestCase):
uri = result.json()['uri']
fp_path_id = re.sub('/user_uploads/', '', uri)
body = "First message ...[zulip.txt](http://{}/user_uploads/".format(host) + fp_path_id + ")"
with self.settings(CROSS_REALM_BOT_EMAILS = set((user2_email, user3_email))):
with self.settings(CROSS_REALM_BOT_EMAILS = set((user_2.email, user_3.email))):
internal_send_private_message(
realm=r1,
sender=get_system_bot(user2_email),
recipient_user=get_user(user1_email, r1),
sender=get_system_bot(user_2.email),
recipient_user=user_1,
content=body,
)
@ -850,6 +850,8 @@ class AvatarTest(UploadSerializeMixin, ZulipTestCase):
def test_get_gravatar_avatar(self) -> None:
self.login('hamlet')
cordelia = self.example_user('cordelia')
cordelia.email = cordelia.delivery_email
cordelia.save()
cordelia.avatar_source = UserProfile.AVATAR_FROM_GRAVATAR
cordelia.save()
@ -867,6 +869,9 @@ class AvatarTest(UploadSerializeMixin, ZulipTestCase):
hamlet = self.example_user("hamlet")
self.login_user(hamlet)
cordelia = self.example_user('cordelia')
cordelia.email = cordelia.delivery_email
cordelia.save()
cross_realm_bot = get_system_bot(settings.WELCOME_BOT)
cordelia.avatar_source = UserProfile.AVATAR_FROM_USER
@ -911,6 +916,8 @@ class AvatarTest(UploadSerializeMixin, ZulipTestCase):
hamlet = self.example_user("hamlet")
self.login_user(hamlet)
cordelia = self.example_user('cordelia')
cordelia.email = cordelia.delivery_email
cordelia.save()
cordelia.avatar_source = UserProfile.AVATAR_FROM_USER
cordelia.save()

View File

@ -6,9 +6,12 @@ from typing import (Any, Dict, Iterable, List, Mapping,
Optional, TypeVar, Union)
from zerver.lib.test_helpers import (
queries_captured, simulated_empty_cache,
tornado_redirected_to_list, get_subscription,
get_subscription,
most_recent_message,
queries_captured,
reset_emails_in_zulip_realm,
simulated_empty_cache,
tornado_redirected_to_list,
)
from zerver.lib.test_classes import (
ZulipTestCase,
@ -16,7 +19,7 @@ from zerver.lib.test_classes import (
from zerver.models import UserProfile, Recipient, Realm, \
RealmDomain, UserHotspot, get_client, \
get_user, get_realm, get_stream, \
get_user, get_user_by_delivery_email, get_realm, get_stream, \
get_source_profile, get_system_bot, \
ScheduledEmail, check_valid_user_ids, \
get_user_by_id_in_realm_including_cross_realm, CustomProfileField, \
@ -127,43 +130,47 @@ class PermissionTest(ZulipTestCase):
def test_admin_api(self) -> None:
self.login('hamlet')
admin = self.example_user('hamlet')
user = self.example_user('othello')
realm = admin.realm
do_change_is_admin(admin, True)
hamlet = self.example_user('hamlet')
othello = self.example_user('othello')
iago = self.example_user('iago')
realm = hamlet.realm
# Make hamlet an additional admin
do_change_is_admin(hamlet, 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'])
hamlet_dict = find_dict(members, 'email', hamlet.email)
self.assertTrue(hamlet_dict['is_admin'])
othello_dict = find_dict(members, 'email', othello.email)
self.assertFalse(othello_dict['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)
result = self.client_patch('/json/users/{}'.format(othello.id), req)
self.assert_json_success(result)
admin_users = realm.get_human_admin_users()
self.assertTrue(user in admin_users)
self.assertTrue(othello in admin_users)
person = events[0]['event']['person']
self.assertEqual(person['email'], self.example_email("othello"))
self.assertEqual(person['email'], othello.email)
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)
result = self.client_patch('/json/users/{}'.format(othello.id), req)
self.assert_json_success(result)
admin_users = realm.get_human_admin_users()
self.assertFalse(user in admin_users)
self.assertFalse(othello in admin_users)
person = events[0]['event']['person']
self.assertEqual(person['email'], self.example_email("othello"))
self.assertEqual(person['email'], othello.email)
self.assertEqual(person['is_admin'], False)
# Cannot take away from last admin
@ -171,23 +178,25 @@ class PermissionTest(ZulipTestCase):
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)
result = self.client_patch('/json/users/{}'.format(hamlet.id), req)
self.assert_json_success(result)
admin_users = realm.get_human_admin_users()
self.assertFalse(admin in admin_users)
self.assertFalse(hamlet in admin_users)
person = events[0]['event']['person']
self.assertEqual(person['email'], self.example_email("hamlet"))
self.assertEqual(person['email'], hamlet.email)
self.assertEqual(person['is_admin'], False)
with tornado_redirected_to_list([]):
result = self.client_patch('/json/users/{}'.format(self.example_user("iago").id), req)
result = self.client_patch('/json/users/{}'.format(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('othello')
result = self.client_patch('/json/users/{}'.format(self.example_user("hamlet").id), req)
result = self.client_patch('/json/users/{}'.format(hamlet.id), req)
self.assert_json_error(result, 'Insufficient permission')
def test_admin_api_hide_emails(self) -> None:
reset_emails_in_zulip_realm()
user = self.example_user('hamlet')
admin = self.example_user('iago')
self.login_user(user)
@ -642,7 +651,7 @@ class AdminCreateUserTest(ZulipTestCase):
self.assert_json_success(result)
# Romeo is a newly registered user
new_user = get_user('romeo@zulip.net', get_realm('zulip'))
new_user = get_user_by_delivery_email('romeo@zulip.net', get_realm('zulip'))
self.assertEqual(new_user.full_name, 'Romeo Montague')
self.assertEqual(new_user.short_name, 'Romeo')
@ -687,8 +696,8 @@ class UserProfileTest(ZulipTestCase):
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"))
self.assertEqual(dct[hamlet.id], hamlet.email)
self.assertEqual(dct[othello.id], othello.email)
def test_valid_user_id(self) -> None:
realm = get_realm("zulip")
@ -759,20 +768,28 @@ class UserProfileTest(ZulipTestCase):
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)
hamlet = self.example_user("hamlet")
cordelia = self.example_user("cordelia")
webhook_bot = self.example_user("webhook_bot")
result = bulk_get_users(
[hamlet.email, cordelia.email],
get_realm("zulip")
)
self.assertEqual(result[hamlet.email].email, hamlet.email)
self.assertEqual(result[cordelia.email].email, cordelia.email)
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)
result = bulk_get_users(
[hamlet.email, cordelia.email, webhook_bot.email],
None,
base_query=UserProfile.objects.all()
)
self.assertEqual(result[hamlet.email].email, hamlet.email)
self.assertEqual(result[cordelia.email].email, cordelia.email)
self.assertEqual(result[webhook_bot.email].email, webhook_bot.email)
def test_get_accounts_for_email(self) -> None:
reset_emails_in_zulip_realm()
def check_account_present_in_accounts(user: UserProfile, accounts: List[Dict[str, Optional[str]]]) -> None:
for account in accounts:
realm = user.realm
@ -783,7 +800,7 @@ class UserProfileTest(ZulipTestCase):
lear_realm = get_realm("lear")
cordelia_in_zulip = self.example_user("cordelia")
cordelia_in_lear = get_user("cordelia@zulip.com", lear_realm)
cordelia_in_lear = get_user_by_delivery_email("cordelia@zulip.com", lear_realm)
email = "cordelia@zulip.com"
accounts = get_accounts_for_email(email)
@ -803,6 +820,7 @@ class UserProfileTest(ZulipTestCase):
check_account_present_in_accounts(self.example_user("iago"), accounts)
def test_get_source_profile(self) -> None:
reset_emails_in_zulip_realm()
iago = get_source_profile("iago@zulip.com", "zulip")
assert iago is not None
self.assertEqual(iago.email, "iago@zulip.com")
@ -1241,6 +1259,7 @@ class RecipientInfoTest(ZulipTestCase):
class BulkUsersTest(ZulipTestCase):
def test_client_gravatar_option(self) -> None:
reset_emails_in_zulip_realm()
self.login('cordelia')
hamlet = self.example_user('hamlet')
@ -1311,7 +1330,7 @@ class GetProfileTest(ZulipTestCase):
`get_user`, makes 1 cache query and 1 database query.
"""
realm = get_realm("zulip")
email = self.example_email("hamlet")
email = self.example_user("hamlet").email
with queries_captured() as queries:
with simulated_empty_cache() as cache_queries:
user_profile = get_user(email, realm)
@ -1321,18 +1340,22 @@ class GetProfileTest(ZulipTestCase):
self.assertEqual(user_profile.email, email)
def test_get_user_profile(self) -> None:
hamlet = self.example_user('hamlet')
iago = self.example_user('iago')
self.login('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['email'], hamlet.email)
self.assertEqual(result['full_name'], 'King Hamlet')
self.assertIn("user_id", result)
self.assertFalse(result['is_bot'])
self.assertFalse(result['is_admin'])
self.assertFalse('delivery_email' in result)
self.login('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['email'], iago.email)
self.assertEqual(result['full_name'], 'Iago')
self.assertFalse(result['is_bot'])
self.assertTrue(result['is_admin'])

View File

@ -13,8 +13,9 @@ class YoHookTests(WebhookTestCase):
"""
Yo App sends notification whenever user receives a new Yo from another user.
"""
cordelia = self.example_user('cordelia')
self.url = self.build_webhook_url(
email="cordelia@zulip.com",
email=cordelia.email,
username="IAGO",
user_ip="127.0.0.1"
)