Hey @Nonexistent User
') self.assertEqual(msg.mentions_user_ids, set()) - def create_user_group_for_test(self, user_group_name: Text) -> UserGroup: + def create_user_group_for_test(self, user_group_name: str) -> UserGroup: othello = self.example_user('othello') return create_user_group(user_group_name, [othello], get_realm('zulip')) @@ -961,7 +961,7 @@ class BugdownTest(ZulipTestCase): self.assertEqual(msg.mentions_user_group_ids, set([user_group.id])) def test_possible_user_group_mentions(self) -> None: - def assert_mentions(content: Text, names: Set[Text]) -> None: + def assert_mentions(content: str, names: Set[str]) -> None: self.assertEqual(possible_user_group_mentions(content), names) assert_mentions('', set()) diff --git a/zerver/tests/test_custom_profile_data.py b/zerver/tests/test_custom_profile_data.py index 585d677a2a..e14f8af97e 100644 --- a/zerver/tests/test_custom_profile_data.py +++ b/zerver/tests/test_custom_profile_data.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- -from typing import Union, List, Dict, Text, Any +from typing import Union, List, Dict, Any from mock import patch from zerver.lib.actions import get_realm, try_add_realm_custom_profile_field, \ @@ -410,7 +410,7 @@ class CustomProfileFieldTest(ZulipTestCase): user_profile = self.example_user('iago') realm = user_profile.realm field = CustomProfileField.objects.get(name="Phone number", realm=realm) - data = [{'id': field.id, 'value': u'123456'}] # type: List[Dict[str, Union[int, Text]]] + data = [{'id': field.id, 'value': u'123456'}] # type: List[Dict[str, Union[int, str]]] do_update_user_custom_profile_data(user_profile, data) self.assertEqual(len(custom_profile_fields_for_realm(realm.id)), self.original_count) diff --git a/zerver/tests/test_decorators.py b/zerver/tests/test_decorators.py index d8e52d3e88..57ca2bed08 100644 --- a/zerver/tests/test_decorators.py +++ b/zerver/tests/test_decorators.py @@ -5,7 +5,7 @@ import re import os from collections import defaultdict -from typing import Any, Dict, Iterable, List, Optional, Text, Tuple +from typing import Any, Dict, Iterable, List, Optional, Tuple from django.test import TestCase, override_settings from django.http import HttpResponse, HttpRequest from django.test.client import RequestFactory @@ -236,7 +236,7 @@ class DecoratorTestCase(TestCase): def test_api_key_only_webhook_view(self) -> None: @api_key_only_webhook_view('ClientName') - def my_webhook(request: HttpRequest, user_profile: UserProfile) -> Text: + def my_webhook(request: HttpRequest, user_profile: UserProfile) -> str: return user_profile.email @api_key_only_webhook_view('ClientName') @@ -1286,13 +1286,13 @@ class TestAuthenticatedJsonPostViewDecorator(ZulipTestCase): self.assert_json_error_contains(self._do_test(user_email), "This organization has been deactivated") do_reactivate_realm(user_profile.realm) - def _do_test(self, user_email: Text) -> HttpResponse: + def _do_test(self, user_email: str) -> HttpResponse: stream_name = "stream name" self.common_subscribe_to_streams(user_email, [stream_name]) data = {"password": initial_password(user_email), "stream": stream_name} return self.client_post(r'/json/subscriptions/exists', data) - def _login(self, user_email: Text, user_realm: Realm, password: str=None) -> None: + def _login(self, user_email: str, user_realm: Realm, password: str=None) -> None: if password: user_profile = get_user(user_email, user_realm) user_profile.set_password(password) @@ -1439,13 +1439,13 @@ class CacheTestCase(ZulipTestCase): def test_cachify_is_per_call(self) -> None: - def test_greetings(greeting: Text) -> Tuple[List[Text], List[Text]]: + def test_greetings(greeting: str) -> Tuple[List[str], List[str]]: - result_log = [] # type: List[Text] - work_log = [] # type: List[Text] + result_log = [] # type: List[str] + work_log = [] # type: List[str] @cachify - def greet(first_name: Text, last_name: Text) -> Text: + def greet(first_name: str, last_name: str) -> str: msg = '%s %s %s' % (greeting, first_name, last_name) work_log.append(msg) return msg diff --git a/zerver/tests/test_events.py b/zerver/tests/test_events.py index 75c29c4b2c..b715eb6cc2 100644 --- a/zerver/tests/test_events.py +++ b/zerver/tests/test_events.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- # See https://zulip.readthedocs.io/en/latest/subsystems/events-system.html for # high-level documentation on how this system works. -from typing import Any, Callable, Dict, List, Optional, Set, Text, Tuple, Union +from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union import os import shutil import sys @@ -1265,7 +1265,7 @@ class EventsRegisterTest(ZulipTestCase): if property_type is bool: validator = check_bool vals = bool_tests - elif property_type is Text: + elif property_type is str: validator = check_string elif property_type is int: validator = check_int @@ -1440,7 +1440,7 @@ class EventsRegisterTest(ZulipTestCase): property_type = UserProfile.property_types[setting_name] if property_type is bool: validator = check_bool - elif property_type is Text: + elif property_type is str: validator = check_string else: raise AssertionError("Unexpected property type %s" % (property_type,)) @@ -2219,8 +2219,8 @@ class GetUnreadMsgsTest(ZulipTestCase): subscription.in_home_view = False subscription.save() - def mute_topic(self, user_profile: UserProfile, stream_name: Text, - topic_name: Text) -> None: + def mute_topic(self, user_profile: UserProfile, stream_name: str, + topic_name: str) -> None: realm = user_profile.realm stream = get_stream(stream_name, realm) recipient = get_stream_recipient(stream.id) diff --git a/zerver/tests/test_external.py b/zerver/tests/test_external.py index 54c49d58ab..ff79441ff3 100644 --- a/zerver/tests/test_external.py +++ b/zerver/tests/test_external.py @@ -22,7 +22,6 @@ import mock import time import urllib -from typing import Text class MITNameTest(ZulipTestCase): def test_valid_hesiod(self) -> None: @@ -57,7 +56,7 @@ class RateLimitTests(ZulipTestCase): settings.RATE_LIMITING = False remove_ratelimit_rule(1, 5) - def send_api_message(self, email: Text, content: Text) -> HttpResponse: + def send_api_message(self, email: str, content: str) -> HttpResponse: return self.api_post(email, "/api/v1/messages", {"type": "stream", "to": "Verona", "client": "test suite", diff --git a/zerver/tests/test_home.py b/zerver/tests/test_home.py index 2ea2d182b6..e471d2f95c 100644 --- a/zerver/tests/test_home.py +++ b/zerver/tests/test_home.py @@ -8,7 +8,7 @@ from django.http import HttpResponse from django.test import override_settings from mock import MagicMock, patch import urllib -from typing import Any, Dict, List, Text +from typing import Any, Dict, List from zerver.lib.actions import do_create_user from zerver.lib.test_classes import ZulipTestCase @@ -388,7 +388,7 @@ class HomeTest(ZulipTestCase): page_params = self._get_page_params(result) self.assertEqual(page_params['realm_notifications_stream_id'], get_stream('Denmark', realm).id) - def create_bot(self, owner: UserProfile, bot_email: Text, bot_name: Text) -> UserProfile: + def create_bot(self, owner: UserProfile, bot_email: str, bot_name: str) -> UserProfile: user = do_create_user( email=bot_email, password='123', @@ -400,7 +400,7 @@ class HomeTest(ZulipTestCase): ) return user - def create_non_active_user(self, realm: Realm, email: Text, name: Text) -> UserProfile: + def create_non_active_user(self, realm: Realm, email: str, name: str) -> UserProfile: user = do_create_user( email=email, password='123', diff --git a/zerver/tests/test_message_edit_notifications.py b/zerver/tests/test_message_edit_notifications.py index 588a7194a5..f0020d11a0 100644 --- a/zerver/tests/test_message_edit_notifications.py +++ b/zerver/tests/test_message_edit_notifications.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- -from typing import Any, Dict, Generator, Mapping, Text, Union +from typing import Any, Dict, Generator, Mapping, Union import mock @@ -26,7 +26,7 @@ from zerver.tornado.event_queue import ( ) class EditMessageSideEffectsTest(ZulipTestCase): - def _assert_update_does_not_notify_anybody(self, message_id: int, content: Text) -> None: + def _assert_update_does_not_notify_anybody(self, message_id: int, content: str) -> None: url = '/json/messages/' + str(message_id) request = dict( @@ -57,7 +57,7 @@ class EditMessageSideEffectsTest(ZulipTestCase): content='now we mention @**Cordelia Lear**', ) - def _login_and_send_original_stream_message(self, content: Text) -> int: + def _login_and_send_original_stream_message(self, content: str) -> int: ''' Note our conventions here: @@ -80,7 +80,7 @@ class EditMessageSideEffectsTest(ZulipTestCase): return message_id - def _get_queued_data_for_message_update(self, message_id: int, content: Text, + def _get_queued_data_for_message_update(self, message_id: int, content: str, expect_short_circuit: bool=False) -> Dict[str, Any]: ''' This function updates a message with a post to diff --git a/zerver/tests/test_messages.py b/zerver/tests/test_messages.py index 387a1b4f81..76f5edeaba 100644 --- a/zerver/tests/test_messages.py +++ b/zerver/tests/test_messages.py @@ -83,7 +83,7 @@ import DNS import mock import time import ujson -from typing import Any, Dict, List, Optional, Set, Text +from typing import Any, Dict, List, Optional, Set from collections import namedtuple @@ -246,12 +246,12 @@ class TopicHistoryTest(ZulipTestCase): class TestCrossRealmPMs(ZulipTestCase): - def make_realm(self, domain: Text) -> Realm: + def make_realm(self, domain: str) -> Realm: realm = Realm.objects.create(string_id=domain, invite_required=False) RealmDomain.objects.create(realm=realm, domain=domain) return realm - def create_user(self, email: Text) -> UserProfile: + def create_user(self, email: str) -> UserProfile: subdomain = email.split("@")[1] self.register(email, 'test', subdomain=subdomain) return get_user(email, get_realm(subdomain)) @@ -436,7 +436,7 @@ 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: Text, receiver_email: Text, content: Text="testcontent") -> None: + def assert_personal(self, sender_email: str, receiver_email: str, content: str="testcontent") -> None: """ Send a private message from `sender_email` to `receiver_email` and check that only those two parties actually received the message. @@ -489,8 +489,8 @@ class PersonalMessagesTest(ZulipTestCase): class StreamMessagesTest(ZulipTestCase): - def assert_stream_message(self, stream_name: Text, topic_name: Text="test topic", - content: Text="test content") -> None: + def assert_stream_message(self, stream_name: str, topic_name: str="test topic", + content: str="test content") -> None: """ Check that messages sent to a stream reach all subscribers to that stream. """ @@ -657,7 +657,7 @@ class StreamMessagesTest(ZulipTestCase): message = most_recent_message(user_profile) assert(UserMessage.objects.get(user_profile=user_profile, message=message).flags.mentioned.is_set) - def _send_stream_message(self, email: Text, stream_name: Text, content: Text) -> Set[int]: + def _send_stream_message(self, email: str, stream_name: str, content: str) -> Set[int]: with mock.patch('zerver.lib.actions.send_event') as m: self.send_stream_message( email, @@ -1548,8 +1548,8 @@ class ScheduledMessageTest(ZulipTestCase): self.assert_json_error(result, 'Missing deliver_at in a request for delayed message delivery') class EditMessageTest(ZulipTestCase): - def check_message(self, msg_id: int, subject: Optional[Text]=None, - content: Optional[Text]=None) -> Message: + def check_message(self, msg_id: int, subject: Optional[str]=None, + content: Optional[str]=None) -> Message: msg = Message.objects.get(id=msg_id) cached = MessageDict.wide_dict(msg) MessageDict.finalize_payload(cached, apply_markdown=False, client_gravatar=False) @@ -1952,7 +1952,7 @@ class EditMessageTest(ZulipTestCase): }) self.assert_json_success(result) - def do_edit_message_assert_success(id_: int, unique_str: Text, topic_only: bool=False) -> None: + def do_edit_message_assert_success(id_: int, unique_str: str, topic_only: bool=False) -> None: new_subject = 'subject' + unique_str new_content = 'content' + unique_str params_dict = {'message_id': id_, 'subject': new_subject} @@ -1965,7 +1965,7 @@ class EditMessageTest(ZulipTestCase): else: self.check_message(id_, subject=new_subject, content=new_content) - def do_edit_message_assert_error(id_: int, unique_str: Text, error: Text, + def do_edit_message_assert_error(id_: int, unique_str: str, error: str, topic_only: bool=False) -> None: message = Message.objects.get(id=id_) old_subject = message.topic_name() @@ -2023,7 +2023,7 @@ class EditMessageTest(ZulipTestCase): self.assert_json_success(result) def do_edit_message_assert_success(id_, unique_str): - # type: (int, Text) -> None + # type: (int, str) -> None new_subject = 'subject' + unique_str params_dict = {'message_id': id_, 'subject': new_subject} result = self.client_patch("/json/messages/" + str(id_), params_dict) @@ -2031,7 +2031,7 @@ class EditMessageTest(ZulipTestCase): self.check_message(id_, subject=new_subject) def do_edit_message_assert_error(id_, unique_str, error): - # type: (int, Text, Text) -> None + # type: (int, str, str) -> None message = Message.objects.get(id=id_) old_subject = message.topic_name() old_content = message.content @@ -2136,7 +2136,7 @@ class EditMessageTest(ZulipTestCase): class MirroredMessageUsersTest(ZulipTestCase): def test_invalid_sender(self) -> None: user = self.example_user('hamlet') - recipients = [] # type: List[Text] + recipients = [] # type: List[str] Request = namedtuple('Request', ['POST']) request = Request(POST=dict()) # no sender @@ -2153,7 +2153,7 @@ class MirroredMessageUsersTest(ZulipTestCase): user = self.example_user('hamlet') sender = user - recipients = [] # type: List[Text] + recipients = [] # type: List[str] Request = namedtuple('Request', ['POST', 'client']) request = Request(POST = dict(sender=sender.email, type='private'), @@ -2545,7 +2545,7 @@ class MissedMessageTest(ZulipTestCase): ) self.assertEqual(sorted(user_ids), sorted(presence_idle_user_ids)) - def set_presence(user_id: int, client_name: Text, ago: int) -> None: + def set_presence(user_id: int, client_name: str, ago: int) -> None: when = timezone_now() - datetime.timedelta(seconds=ago) UserPresence.objects.create( user_profile_id=user_id, @@ -2970,7 +2970,7 @@ class SoftDeactivationMessageTest(ZulipTestCase): user_messages = get_user_messages(user) self.assertEqual(len(user_messages), count) - def assert_last_um_content(user: UserProfile, content: Text, negate: bool=False) -> None: + def assert_last_um_content(user: UserProfile, content: str, negate: bool=False) -> None: user_messages = get_user_messages(user) if negate: self.assertNotEqual(user_messages[-1].content, content) diff --git a/zerver/tests/test_notifications.py b/zerver/tests/test_notifications.py index 1edf623ea7..45bc4e701c 100644 --- a/zerver/tests/test_notifications.py +++ b/zerver/tests/test_notifications.py @@ -10,7 +10,7 @@ from django.http import HttpResponse from django.test import override_settings from email.utils import formataddr from mock import patch, MagicMock -from typing import Any, Dict, List, Text, Optional +from typing import Any, Dict, List, Optional from zerver.lib.notifications import fix_emojis, \ handle_missedmessage_emails, relative_to_full_url @@ -29,7 +29,7 @@ from zerver.models import ( from zerver.lib.test_helpers import get_test_image_file class TestMissedMessages(ZulipTestCase): - def normalize_string(self, s: Text) -> Text: + def normalize_string(self, s: str) -> str: s = s.strip() return re.sub(r'\s+', ' ', s) diff --git a/zerver/tests/test_outgoing_webhook_system.py b/zerver/tests/test_outgoing_webhook_system.py index 69b212494f..4d64f63c75 100644 --- a/zerver/tests/test_outgoing_webhook_system.py +++ b/zerver/tests/test_outgoing_webhook_system.py @@ -8,7 +8,7 @@ import requests from builtins import object from django.test import override_settings from requests import Response -from typing import Any, Dict, Tuple, Text, Optional +from typing import Any, Dict, Tuple, Optional from zerver.lib.outgoing_webhook import do_rest_call, OutgoingWebhookServiceInterface from zerver.lib.test_classes import ZulipTestCase @@ -27,7 +27,7 @@ def timeout_error(http_method: Any, final_url: Any, data: Any, **request_kwargs: raise requests.exceptions.Timeout("Time is up!") class MockServiceHandler(OutgoingWebhookServiceInterface): - def process_success(self, response: Response, event: Dict[Text, Any]) -> Tuple[Optional[str], Optional[str]]: + def process_success(self, response: Response, event: Dict[str, Any]) -> Tuple[Optional[str], Optional[str]]: return "Success!", None service_handler = MockServiceHandler(None, None, None, None) @@ -134,7 +134,7 @@ class TestOutgoingWebhookMessaging(ZulipTestCase): self.assertEqual(last_message.content, "Success! Hidley ho, I'm a webhook responding!") self.assertEqual(last_message.sender_id, self.bot_profile.id) display_recipient = get_display_recipient(last_message.recipient) - # The next two lines error on mypy because the display_recipient is of type Union[Text, List[Dict[str, Any]]]. + # The next two lines error on mypy because the display_recipient is of type Union[str, List[Dict[str, Any]]]. # In this case, we know that display_recipient will be of type List[Dict[str, Any]]. # Otherwise this test will error, which is wanted behavior anyway. self.assert_length(display_recipient, 1) # type: ignore diff --git a/zerver/tests/test_push_notifications.py b/zerver/tests/test_push_notifications.py index 7015101197..9397a941d9 100644 --- a/zerver/tests/test_push_notifications.py +++ b/zerver/tests/test_push_notifications.py @@ -5,7 +5,7 @@ import requests import mock from mock import call import time -from typing import Any, Dict, List, Optional, Union, SupportsInt, Text +from typing import Any, Dict, List, Optional, Union, SupportsInt import base64 import gcm @@ -77,7 +77,7 @@ class BouncerTestCase(ZulipTestCase): raise AssertionError("Unsupported method for bounce_request") return result - def get_generic_payload(self, method: Text='register') -> Dict[str, Any]: + def get_generic_payload(self, method: str='register') -> Dict[str, Any]: user_id = 10 token = "111222" token_kind = PushDeviceToken.GCM @@ -1109,7 +1109,7 @@ class GCMCanonicalTest(GCMTest): res['canonical'] = {t1: t2} mock_send.return_value = res - def get_count(hex_token: Text) -> int: + def get_count(hex_token: str) -> int: token = apn.hex_to_b64(hex_token) return PushDeviceToken.objects.filter( token=token, kind=PushDeviceToken.GCM).count() @@ -1137,7 +1137,7 @@ class GCMCanonicalTest(GCMTest): res['canonical'] = {old_token: new_token} mock_send.return_value = res - def get_count(hex_token: Text) -> int: + def get_count(hex_token: str) -> int: token = apn.hex_to_b64(hex_token) return PushDeviceToken.objects.filter( token=token, kind=PushDeviceToken.GCM).count() @@ -1162,7 +1162,7 @@ class GCMNotRegisteredTest(GCMTest): res['errors'] = {'NotRegistered': [token]} mock_send.return_value = res - def get_count(hex_token: Text) -> int: + def get_count(hex_token: str) -> int: token = apn.hex_to_b64(hex_token) return PushDeviceToken.objects.filter( token=token, kind=PushDeviceToken.GCM).count() diff --git a/zerver/tests/test_realm.py b/zerver/tests/test_realm.py index 4fb799c67b..baaa2db702 100644 --- a/zerver/tests/test_realm.py +++ b/zerver/tests/test_realm.py @@ -4,7 +4,7 @@ import ujson from django.http import HttpResponse from mock import patch -from typing import Any, Dict, List, Text, Union, Mapping +from typing import Any, Dict, List, Union, Mapping from zerver.lib.actions import ( do_change_is_admin, @@ -21,7 +21,7 @@ from zerver.models import get_realm, Realm, UserProfile, ScheduledEmail, get_str class RealmTest(ZulipTestCase): def assert_user_profile_cache_gets_new_name(self, user_profile: UserProfile, - new_realm_name: Text) -> None: + new_realm_name: str) -> None: self.assertEqual(user_profile.realm.name, new_realm_name) def test_do_set_realm_name_caching(self) -> None: diff --git a/zerver/tests/test_signup.py b/zerver/tests/test_signup.py index 6077eaaf45..ae91aacec0 100644 --- a/zerver/tests/test_signup.py +++ b/zerver/tests/test_signup.py @@ -64,7 +64,7 @@ import re import smtplib import ujson -from typing import Any, Dict, List, Optional, Set, Text +from typing import Any, Dict, List, Optional, Set import urllib import os @@ -126,7 +126,7 @@ class AddNewUserHistoryTest(ZulipTestCase): stream_dict = { "Denmark": {"description": "A Scandinavian country", "invite_only": False}, "Verona": {"description": "A city in Italy", "invite_only": False} - } # type: Dict[Text, Dict[Text, Any]] + } # type: Dict[str, Dict[str, Any]] realm = get_realm('zulip') set_default_streams(realm, stream_dict) with patch("zerver.lib.actions.add_new_user_history"): @@ -351,7 +351,7 @@ class LoginTest(ZulipTestCase): def test_register(self) -> None: realm = get_realm("zulip") stream_dict = {"stream_"+str(i): {"description": "stream_%s_description" % i, "invite_only": False} - for i in range(40)} # type: Dict[Text, Dict[Text, Any]] + for i in range(40)} # type: Dict[str, Dict[str, Any]] for stream_name in stream_dict.keys(): self.make_stream(stream_name, realm=realm) @@ -455,7 +455,7 @@ class LoginTest(ZulipTestCase): self.assertEqual(response["Location"], "http://zulip.testserver") class InviteUserBase(ZulipTestCase): - def check_sent_emails(self, correct_recipients: List[Text], + def check_sent_emails(self, correct_recipients: List[str], custom_from_name: Optional[str]=None) -> None: from django.core.mail import outbox self.assertEqual(len(outbox), len(correct_recipients)) @@ -469,7 +469,7 @@ class InviteUserBase(ZulipTestCase): self.assertIn(FromAddress.NOREPLY, outbox[0].from_email) - def invite(self, users: Text, streams: List[Text], body: str='', + def invite(self, users: str, streams: List[str], body: str='', invite_as_admin: str="false") -> HttpResponse: """ Invites the specified users to Zulip with the specified streams. @@ -1096,7 +1096,7 @@ class MultiuseInviteTest(ZulipTestCase): self.realm.save() def generate_multiuse_invite_link(self, streams: List[Stream]=None, - date_sent: Optional[datetime.datetime]=None) -> Text: + date_sent: Optional[datetime.datetime]=None) -> str: invite = MultiuseInvite(realm=self.realm, referred_by=self.example_user("iago")) invite.save() @@ -1111,7 +1111,7 @@ class MultiuseInviteTest(ZulipTestCase): return confirmation_url(key, self.realm.host, Confirmation.MULTIUSE_INVITE) - def check_user_able_to_register(self, email: Text, invite_link: Text) -> None: + def check_user_able_to_register(self, email: str, invite_link: str) -> None: password = "password" result = self.client_post(invite_link, {'email': email}) @@ -1550,7 +1550,7 @@ class RealmCreationTest(ZulipTestCase): class UserSignUpTest(ZulipTestCase): - def _assert_redirected_to(self, result: HttpResponse, url: Text) -> None: + def _assert_redirected_to(self, result: HttpResponse, url: str) -> None: self.assertEqual(result.status_code, 302) self.assertEqual(result['LOCATION'], url) diff --git a/zerver/tests/test_subs.py b/zerver/tests/test_subs.py index fae991eb1c..a7e714fd44 100644 --- a/zerver/tests/test_subs.py +++ b/zerver/tests/test_subs.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- -from typing import Any, Dict, List, Mapping, Optional, Sequence, Set, Text +from typing import Any, Dict, List, Mapping, Optional, Sequence, Set from django.conf import settings from django.http import HttpRequest, HttpResponse @@ -947,12 +947,12 @@ class StreamAdminTest(ZulipTestCase): status_code=403) class DefaultStreamTest(ZulipTestCase): - def get_default_stream_names(self, realm: Realm) -> Set[Text]: + def get_default_stream_names(self, realm: Realm) -> Set[str]: streams = get_default_streams_for_realm(realm.id) stream_names = [s.name for s in streams] return set(stream_names) - def get_default_stream_descriptions(self, realm: Realm) -> Set[Text]: + def get_default_stream_descriptions(self, realm: Realm) -> Set[str]: streams = get_default_streams_for_realm(realm.id) stream_descriptions = [s.description for s in streams] return set(stream_descriptions) @@ -963,7 +963,7 @@ class DefaultStreamTest(ZulipTestCase): "apple": {"description": "A red fruit", "invite_only": False}, "banana": {"description": "A yellow fruit", "invite_only": False}, "Carrot Cake": {"description": "A delicious treat", "invite_only": False} - } # type: Dict[Text, Dict[Text, Any]] + } # type: Dict[str, Dict[str, Any]] expected_names = list(stream_dict.keys()) expected_names.append("announce") expected_descriptions = [i["description"] for i in stream_dict.values()] + [""] @@ -981,7 +981,7 @@ class DefaultStreamTest(ZulipTestCase): "apple": {"description": "A red fruit", "invite_only": False}, "banana": {"description": "A yellow fruit", "invite_only": False}, "Carrot Cake": {"description": "A delicious treat", "invite_only": False} - } # type: Dict[Text, Dict[Text, Any]] + } # type: Dict[str, Dict[str, Any]] expected_names = list(stream_dict.keys()) expected_descriptions = [i["description"] for i in stream_dict.values()] set_default_streams(realm, stream_dict) @@ -1642,7 +1642,7 @@ class SubscriptionAPITest(ZulipTestCase): self.test_realm = self.user_profile.realm self.streams = self.get_streams(self.test_email, self.test_realm) - def make_random_stream_names(self, existing_stream_names: List[Text]) -> List[Text]: + def make_random_stream_names(self, existing_stream_names: List[str]) -> List[str]: """ Helper function to make up random stream names. It takes existing_stream_names and randomly appends a digit to the end of each, @@ -1676,11 +1676,11 @@ class SubscriptionAPITest(ZulipTestCase): # also check that this matches the list of your subscriptions self.assertEqual(sorted(list_streams), sorted(self.streams)) - def helper_check_subs_before_and_after_add(self, subscriptions: List[Text], + def helper_check_subs_before_and_after_add(self, subscriptions: List[str], other_params: Dict[str, Any], - subscribed: List[Text], - already_subscribed: List[Text], - email: Text, new_subs: List[Text], + subscribed: List[str], + already_subscribed: List[str], + email: str, new_subs: List[str], realm: Realm, invite_only: bool=False) -> None: """ @@ -1926,8 +1926,8 @@ class SubscriptionAPITest(ZulipTestCase): self.assert_json_error(result, "Invalid stream name '%s'" % (invalid_stream_name,)) - def assert_adding_subscriptions_for_principal(self, invitee_email: Text, invitee_realm: Realm, - streams: List[Text], invite_only: bool=False) -> None: + def assert_adding_subscriptions_for_principal(self, invitee_email: str, invitee_realm: Realm, + streams: List[str], invite_only: bool=False) -> None: """ Calling POST /json/users/me/subscriptions on behalf of another principal (for whom you have permission to add subscriptions) should successfully add @@ -2322,9 +2322,9 @@ class SubscriptionAPITest(ZulipTestCase): self.assert_json_error(result, "User not authorized to execute queries on behalf of '%s'" % (principal,), status_code=403) - def helper_check_subs_before_and_after_remove(self, subscriptions: List[Text], + def helper_check_subs_before_and_after_remove(self, subscriptions: List[str], json_dict: Dict[str, Any], - email: Text, new_subs: List[Text], + email: str, new_subs: List[str], realm: Realm) -> None: """ Check result of removing subscriptions. @@ -2378,7 +2378,7 @@ class SubscriptionAPITest(ZulipTestCase): {"subscriptions": ujson.dumps(streams_to_remove)}) self.assert_json_error(result, "Stream(s) (%s) do not exist" % (random_streams[0],)) - def helper_subscriptions_exists(self, stream: Text, expect_success: bool, subscribed: bool) -> None: + def helper_subscriptions_exists(self, stream: str, expect_success: bool, subscribed: bool) -> None: """ Call /json/subscriptions/exists on a stream and expect a certain result. """ @@ -2475,7 +2475,7 @@ class SubscriptionAPITest(ZulipTestCase): self.assertIn("subscribed", result.json()) self.assertTrue(result.json()["subscribed"]) - def get_subscription(self, user_profile: UserProfile, stream_name: Text) -> Subscription: + def get_subscription(self, user_profile: UserProfile, stream_name: str) -> Subscription: stream = get_stream(stream_name, self.test_realm) return Subscription.objects.get( user_profile=user_profile, @@ -2727,18 +2727,18 @@ class GetSubscribersTest(ZulipTestCase): self.email = self.user_profile.email self.login(self.email) - def assert_user_got_subscription_notification(self, expected_msg: Text) -> None: + def assert_user_got_subscription_notification(self, expected_msg: str) -> None: # verify that the user was sent a message informing them about the subscription msg = self.get_last_message() self.assertEqual(msg.recipient.type, msg.recipient.PERSONAL) self.assertEqual(msg.sender_id, self.notification_bot().id) - def non_ws(s: Text) -> Text: + def non_ws(s: str) -> str: return s.replace('\n', '').replace(' ', '') self.assertEqual(non_ws(msg.content), non_ws(expected_msg)) - def check_well_formed_result(self, result: Dict[str, Any], stream_name: Text, realm: Realm) -> None: + def check_well_formed_result(self, result: Dict[str, Any], stream_name: str, realm: Realm) -> None: """ A successful call to get_subscribers returns the list of subscribers in the form: @@ -2753,12 +2753,12 @@ class GetSubscribersTest(ZulipTestCase): stream_name, realm)] self.assertEqual(sorted(result["subscribers"]), sorted(true_subscribers)) - def make_subscriber_request(self, stream_id: int, email: Optional[Text]=None) -> HttpResponse: + def make_subscriber_request(self, stream_id: int, email: Optional[str]=None) -> HttpResponse: if email is None: email = self.email return self.api_get(email, "/api/v1/streams/%d/members" % (stream_id,)) - def make_successful_subscriber_request(self, stream_name: Text) -> None: + def make_successful_subscriber_request(self, stream_name: str) -> None: stream_id = get_stream(stream_name, self.user_profile.realm).id result = self.make_subscriber_request(stream_id) self.assert_json_success(result) @@ -3043,7 +3043,7 @@ class GetSubscribersTest(ZulipTestCase): result_dict = result.json() self.assertIn('subscribers', result_dict) self.assertIsInstance(result_dict['subscribers'], list) - subscribers = [] # type: List[Text] + subscribers = [] # type: List[str] for subscriber in result_dict['subscribers']: self.assertIsInstance(subscriber, str) subscribers.append(subscriber) diff --git a/zerver/tests/test_tornado.py b/zerver/tests/test_tornado.py index 4c13c9236f..384f7661f1 100644 --- a/zerver/tests/test_tornado.py +++ b/zerver/tests/test_tornado.py @@ -38,24 +38,24 @@ from http.cookies import SimpleCookie import urllib.parse from unittest.mock import patch -from typing import Any, Callable, Dict, Generator, Optional, Text, List, cast +from typing import Any, Callable, Dict, Generator, Optional, List, cast class TornadoWebTestCase(AsyncHTTPTestCase, ZulipTestCase): def setUp(self) -> None: super().setUp() signals.request_started.disconnect(close_old_connections) signals.request_finished.disconnect(close_old_connections) - self.session_cookie = None # type: Optional[Dict[Text, Text]] + self.session_cookie = None # type: Optional[Dict[str, str]] def tearDown(self) -> None: super().tearDown() - self.session_cookie = None # type: Optional[Dict[Text, Text]] + self.session_cookie = None # type: Optional[Dict[str, str]] @override_settings(DEBUG=False) def get_app(self) -> Application: return create_tornado_application() - def client_get(self, path: Text, **kwargs: Any) -> HTTPResponse: + def client_get(self, path: str, **kwargs: Any) -> HTTPResponse: self.add_session_cookie(kwargs) self.set_http_host(kwargs) if 'HTTP_HOST' in kwargs: @@ -63,7 +63,7 @@ class TornadoWebTestCase(AsyncHTTPTestCase, ZulipTestCase): del kwargs['HTTP_HOST'] return self.fetch(path, method='GET', **kwargs) - def fetch_async(self, method: Text, path: Text, **kwargs: Any) -> None: + def fetch_async(self, method: str, path: str, **kwargs: Any) -> None: self.add_session_cookie(kwargs) self.set_http_host(kwargs) if 'HTTP_HOST' in kwargs: @@ -76,7 +76,7 @@ class TornadoWebTestCase(AsyncHTTPTestCase, ZulipTestCase): **kwargs ) - def client_get_async(self, path: Text, **kwargs: Any) -> None: + def client_get_async(self, path: str, **kwargs: Any) -> None: self.set_http_host(kwargs) self.fetch_async('GET', path, **kwargs) @@ -88,7 +88,7 @@ class TornadoWebTestCase(AsyncHTTPTestCase, ZulipTestCase): "Cookie": "{}={}".format(session_cookie, session_key) } - def get_session_cookie(self) -> Dict[Text, Text]: + def get_session_cookie(self) -> Dict[str, str]: return {} if self.session_cookie is None else self.session_cookie def add_session_cookie(self, kwargs: Dict[str, Any]) -> None: @@ -211,7 +211,7 @@ class TornadoTestCase(WebSocketBaseTestCase): raise gen.Return([response_ack, response_message]) @staticmethod - def _get_queue_events_data(email: Text) -> Dict[str, Dict[str, str]]: + def _get_queue_events_data(email: str) -> Dict[str, Dict[str, str]]: user_profile = UserProfile.objects.filter(email=email).first() events_query = { 'queue_id': None, diff --git a/zerver/tests/test_upload.py b/zerver/tests/test_upload.py index ea3624c34c..4a92ba41b6 100644 --- a/zerver/tests/test_upload.py +++ b/zerver/tests/test_upload.py @@ -52,7 +52,7 @@ from django.http import HttpRequest from django.utils.timezone import now as timezone_now from sendfile import _get_sendfile -from typing import Any, Callable, Text +from typing import Any, Callable def destroy_uploads() -> None: if os.path.exists(settings.LOCAL_UPLOADS_DIR): @@ -464,7 +464,7 @@ class FileUploadTest(UploadSerializeMixin, ZulipTestCase): def test_cross_realm_file_access(self) -> None: - def create_user(email: Text, realm_id: Text) -> UserProfile: + def create_user(email: str, realm_id: str) -> UserProfile: self.register(email, 'test', subdomain=realm_id) return get_user(email, get_realm(realm_id)) @@ -574,8 +574,8 @@ class FileUploadTest(UploadSerializeMixin, ZulipTestCase): self.logout() def test_serve_local(self) -> None: - def check_xsend_links(name: Text, name_str_for_test: Text, - content_disposition: Text='') -> None: + def check_xsend_links(name: str, name_str_for_test: str, + content_disposition: str='') -> None: with self.settings(SENDFILE_BACKEND='sendfile.backends.nginx'): _get_sendfile.clear() # To clearout cached version of backend from djangosendfile self.login(self.example_email("hamlet")) diff --git a/zerver/tests/test_user_groups.py b/zerver/tests/test_user_groups.py index a9874bdd8b..ef134d09ee 100644 --- a/zerver/tests/test_user_groups.py +++ b/zerver/tests/test_user_groups.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -from typing import Any, List, Optional, Text +from typing import Any, List, Optional import ujson import django @@ -19,7 +19,7 @@ from zerver.models import UserProfile, UserGroup, get_realm, Realm, \ UserGroupMembership class UserGroupTestCase(ZulipTestCase): - def create_user_group_for_test(self, group_name: Text, + def create_user_group_for_test(self, group_name: str, realm: Realm=get_realm('zulip')) -> UserGroup: members = [self.example_user('othello')] return create_user_group(group_name, members, realm) diff --git a/zerver/tests/test_users.py b/zerver/tests/test_users.py index 6088b787f7..48d276bb95 100644 --- a/zerver/tests/test_users.py +++ b/zerver/tests/test_users.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- from typing import (Any, Dict, Iterable, List, Mapping, - Optional, TypeVar, Text, Union) + Optional, TypeVar, Union) from django.http import HttpResponse from django.test import TestCase @@ -501,7 +501,7 @@ class BulkUsersTest(ZulipTestCase): hamlet = self.example_user('hamlet') - def get_hamlet_avatar(client_gravatar: bool) -> Optional[Text]: + def get_hamlet_avatar(client_gravatar: bool) -> Optional[str]: data = dict(client_gravatar=ujson.dumps(client_gravatar)) result = self.client_get('/json/users', data) self.assert_json_success(result) @@ -531,12 +531,12 @@ class BulkUsersTest(ZulipTestCase): class GetProfileTest(ZulipTestCase): - def common_update_pointer(self, email: Text, pointer: int) -> None: + def common_update_pointer(self, email: str, pointer: int) -> None: self.login(email) result = self.client_post("/json/users/me/pointer", {"pointer": pointer}) self.assert_json_success(result) - def common_get_profile(self, user_id: str) -> Dict[Text, Any]: + def common_get_profile(self, user_id: str) -> Dict[str, Any]: # Assumes all users are example users in realm 'zulip' user_profile = self.example_user(user_id) self.send_stream_message(user_profile.email, "Verona", "hello")