zerver/tests: Change use of typing.Text to str.

This commit is contained in:
Aditya Bansal
2018-05-10 22:30:29 +05:30
committed by Tim Abbott
parent 5adf983c3c
commit 2f3b2fbf59
12 changed files with 43 additions and 46 deletions

View File

@@ -21,8 +21,6 @@ from zerver.models import (
UserProfile, UserProfile,
) )
from typing import Text
import ujson import ujson
class AlertWordTests(ZulipTestCase): class AlertWordTests(ZulipTestCase):
@@ -130,7 +128,7 @@ class AlertWordTests(ZulipTestCase):
self.assert_json_success(result) self.assert_json_success(result)
self.assertEqual(result.json()['alert_words'], ['two', 'three']) self.assertEqual(result.json()['alert_words'], ['two', 'three'])
def message_does_alert(self, user_profile: UserProfile, message: Text) -> bool: def message_does_alert(self, user_profile: UserProfile, message: str) -> bool:
"""Send a bunch of messages as othello, so Hamlet is notified""" """Send a bunch of messages as othello, so Hamlet is notified"""
self.send_stream_message(self.example_email("othello"), "Denmark", message) self.send_stream_message(self.example_email("othello"), "Denmark", message)
user_message = most_recent_usermessage(user_profile) user_message = most_recent_usermessage(user_profile)

View File

@@ -45,12 +45,12 @@ import sys
from io import StringIO from io import StringIO
from django.conf import settings from django.conf import settings
from typing import Any, Callable, Dict, Mapping, Union, Text, Optional from typing import Any, Callable, Dict, Mapping, Union, Optional
class TestEmailMirrorLibrary(ZulipTestCase): class TestEmailMirrorLibrary(ZulipTestCase):
def test_get_missed_message_token(self) -> None: def test_get_missed_message_token(self) -> None:
def get_token(address: Text) -> Text: def get_token(address: str) -> str:
with self.settings(EMAIL_GATEWAY_PATTERN="%s@example.com"): with self.settings(EMAIL_GATEWAY_PATTERN="%s@example.com"):
return get_missed_message_token_from_address(address) return get_missed_message_token_from_address(address)
@@ -422,7 +422,7 @@ class TestScriptMTA(ZulipTestCase):
class TestEmailMirrorTornadoView(ZulipTestCase): class TestEmailMirrorTornadoView(ZulipTestCase):
def send_private_message(self) -> Text: def send_private_message(self) -> str:
email = self.example_email('othello') email = self.example_email('othello')
self.login(email) self.login(email)
result = self.client_post( result = self.client_post(

View File

@@ -2,7 +2,7 @@
from unittest import mock from unittest import mock
from mock import patch from mock import patch
from typing import Any, Dict, Tuple, Text, Optional from typing import Any, Dict, Tuple, Optional
from zerver.lib.bot_lib import EmbeddedBotQuitException, EmbeddedBotHandler from zerver.lib.bot_lib import EmbeddedBotQuitException, EmbeddedBotHandler
from zerver.lib.test_classes import ZulipTestCase from zerver.lib.test_classes import ZulipTestCase
@@ -29,7 +29,7 @@ class TestEmbeddedBotMessaging(ZulipTestCase):
self.assertEqual(last_message.content, "beep boop") self.assertEqual(last_message.content, "beep boop")
self.assertEqual(last_message.sender_id, self.bot_profile.id) self.assertEqual(last_message.sender_id, self.bot_profile.id)
display_recipient = get_display_recipient(last_message.recipient) 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]]. # 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. # Otherwise this test will error, which is wanted behavior anyway.
self.assert_length(display_recipient, 1) # type: ignore self.assert_length(display_recipient, 1) # type: ignore

View File

@@ -11,7 +11,7 @@ from django.utils.log import AdminEmailHandler
from functools import wraps from functools import wraps
from mock import MagicMock, patch from mock import MagicMock, patch
from mypy_extensions import NoReturn from mypy_extensions import NoReturn
from typing import Any, Callable, Dict, Mapping, Optional, Text, Iterator from typing import Any, Callable, Dict, Mapping, Optional, Iterator
from zerver.lib.request import JsonableError from zerver.lib.request import JsonableError
from zerver.lib.types import ViewFuncT from zerver.lib.types import ViewFuncT
@@ -23,7 +23,7 @@ from zerver.worker.queue_processors import QueueProcessingWorker
captured_request = None # type: Optional[HttpRequest] captured_request = None # type: Optional[HttpRequest]
captured_exc_info = None captured_exc_info = None
def capture_and_throw(domain: Optional[Text]=None) -> Callable[[ViewFuncT], ViewFuncT]: def capture_and_throw(domain: Optional[str]=None) -> Callable[[ViewFuncT], ViewFuncT]:
def wrapper(view_func: ViewFuncT) -> ViewFuncT: def wrapper(view_func: ViewFuncT) -> ViewFuncT:
@wraps(view_func) @wraps(view_func)
def wrapped_view(request: HttpRequest, *args: Any, **kwargs: Any) -> NoReturn: def wrapped_view(request: HttpRequest, *args: Any, **kwargs: Any) -> NoReturn:

View File

@@ -42,25 +42,25 @@ from zerver.views.messages import (
LARGER_THAN_MAX_MESSAGE_ID, LARGER_THAN_MAX_MESSAGE_ID,
) )
from typing import Dict, List, Mapping, Sequence, Tuple, Generic, Union, Any, Optional, Text from typing import Dict, List, Mapping, Sequence, Tuple, Generic, Union, Any, Optional
import mock import mock
import os import os
import re import re
import ujson import ujson
def get_sqlalchemy_query_params(query: Text) -> Dict[Text, Text]: def get_sqlalchemy_query_params(query: str) -> Dict[str, str]:
dialect = get_sqlalchemy_connection().dialect dialect = get_sqlalchemy_connection().dialect
comp = compiler.SQLCompiler(dialect, query) comp = compiler.SQLCompiler(dialect, query)
return comp.params return comp.params
def fix_ws(s: Text) -> Text: def fix_ws(s: str) -> str:
return re.sub('\s+', ' ', str(s)).strip() return re.sub('\s+', ' ', str(s)).strip()
def get_recipient_id_for_stream_name(realm: Realm, stream_name: Text) -> Text: def get_recipient_id_for_stream_name(realm: Realm, stream_name: str) -> str:
stream = get_stream(stream_name, realm) stream = get_stream(stream_name, realm)
return get_stream_recipient(stream.id).id return get_stream_recipient(stream.id).id
def mute_stream(realm: Realm, user_profile: Text, stream_name: Text) -> None: def mute_stream(realm: Realm, user_profile: str, stream_name: str) -> None:
stream = get_stream(stream_name, realm) stream = get_stream(stream_name, realm)
recipient = get_stream_recipient(stream.id) recipient = get_stream_recipient(stream.id)
subscription = Subscription.objects.get(recipient=recipient, user_profile=user_profile) subscription = Subscription.objects.get(recipient=recipient, user_profile=user_profile)
@@ -333,7 +333,7 @@ class NarrowBuilderTest(ZulipTestCase):
query = self._build_query(term) query = self._build_query(term)
self.assertEqual(str(query), 'SELECT id \nFROM zerver_message') self.assertEqual(str(query), 'SELECT id \nFROM zerver_message')
def _do_add_term_test(self, term: Dict[str, Any], where_clause: Text, def _do_add_term_test(self, term: Dict[str, Any], where_clause: str,
params: Optional[Dict[str, Any]]=None) -> None: params: Optional[Dict[str, Any]]=None) -> None:
query = self._build_query(term) query = self._build_query(term)
if params is not None: if params is not None:
@@ -664,11 +664,11 @@ class GetOldMessagesTest(ZulipTestCase):
for message in result["messages"]: for message in result["messages"]:
assert(message["id"] in message_ids) assert(message["id"] in message_ids)
def get_query_ids(self) -> Dict[Text, int]: def get_query_ids(self) -> Dict[str, int]:
hamlet_user = self.example_user('hamlet') hamlet_user = self.example_user('hamlet')
othello_user = self.example_user('othello') othello_user = self.example_user('othello')
query_ids = {} # type: Dict[Text, int] query_ids = {} # type: Dict[str, int]
scotland_stream = get_stream('Scotland', hamlet_user.realm) scotland_stream = get_stream('Scotland', hamlet_user.realm)
query_ids['scotland_recipient'] = get_stream_recipient(scotland_stream.id).id query_ids['scotland_recipient'] = get_stream_recipient(scotland_stream.id).id
@@ -685,7 +685,7 @@ class GetOldMessagesTest(ZulipTestCase):
""" """
self.login(self.example_email("hamlet")) self.login(self.example_email("hamlet"))
def get_content_type(apply_markdown: bool) -> Text: def get_content_type(apply_markdown: bool) -> str:
req = dict( req = dict(
apply_markdown=ujson.dumps(apply_markdown), apply_markdown=ujson.dumps(apply_markdown),
) # type: Dict[str, Any] ) # type: Dict[str, Any]
@@ -768,7 +768,7 @@ class GetOldMessagesTest(ZulipTestCase):
""" """
me = self.example_email('hamlet') me = self.example_email('hamlet')
def dr_emails(dr: Union[Text, List[Dict[str, Any]]]) -> Text: def dr_emails(dr: Union[str, List[Dict[str, Any]]]) -> str:
assert isinstance(dr, list) assert isinstance(dr, list)
return ','.join(sorted(set([r['email'] for r in dr] + [me]))) return ','.join(sorted(set([r['email'] for r in dr] + [me])))
@@ -1124,7 +1124,7 @@ class GetOldMessagesTest(ZulipTestCase):
email = self.example_email("cordelia") email = self.example_email("cordelia")
self.login(email) self.login(email)
def send(content: Text) -> int: def send(content: str) -> int:
msg_id = self.send_stream_message( msg_id = self.send_stream_message(
sender_email=email, sender_email=email,
stream_name="Verona", stream_name="Verona",
@@ -1442,7 +1442,7 @@ class GetOldMessagesTest(ZulipTestCase):
email = self.example_email("cordelia") email = self.example_email("cordelia")
self.login(email) self.login(email)
def send(content: Text) -> int: def send(content: str) -> int:
msg_id = self.send_stream_message( msg_id = self.send_stream_message(
sender_email=email, sender_email=email,
stream_name="Verona", stream_name="Verona",
@@ -1633,7 +1633,7 @@ class GetOldMessagesTest(ZulipTestCase):
""" """
self.login(self.example_email("hamlet")) self.login(self.example_email("hamlet"))
required_args = (("anchor", 1), ("num_before", 1), ("num_after", 1)) # type: Tuple[Tuple[Text, int], ...] required_args = (("anchor", 1), ("num_before", 1), ("num_after", 1)) # type: Tuple[Tuple[str, int], ...]
for i in range(len(required_args)): for i in range(len(required_args)):
post_params = dict(required_args[:i] + required_args[i + 1:]) post_params = dict(required_args[:i] + required_args[i + 1:])
@@ -1670,7 +1670,7 @@ class GetOldMessagesTest(ZulipTestCase):
""" """
self.login(self.example_email("hamlet")) self.login(self.example_email("hamlet"))
other_params = [("anchor", 0), ("num_before", 0), ("num_after", 0)] # type: List[Tuple[Text, Union[int, str, bool]]] other_params = [("anchor", 0), ("num_before", 0), ("num_after", 0)] # type: List[Tuple[str, Union[int, str, bool]]]
bad_types = (False, 0, '', '{malformed json,', bad_types = (False, 0, '', '{malformed json,',
'{foo: 3}', '[1,2]', '[["x","y","z"]]') # type: Tuple[Union[int, str, bool], ...] '{foo: 3}', '[1,2]', '[["x","y","z"]]') # type: Tuple[Union[int, str, bool], ...]
@@ -1703,9 +1703,9 @@ class GetOldMessagesTest(ZulipTestCase):
result = self.client_get("/json/messages", params) result = self.client_get("/json/messages", params)
self.assert_json_error_contains(result, 'elem["operand"] is not a string') self.assert_json_error_contains(result, 'elem["operand"] is not a string')
def exercise_bad_narrow_operand(self, operator: Text, def exercise_bad_narrow_operand(self, operator: str,
operands: Sequence[Any], operands: Sequence[Any],
error_msg: Text) -> None: error_msg: str) -> None:
other_params = [("anchor", 0), ("num_before", 0), ("num_after", 0)] # type: List[Tuple[str, Any]] other_params = [("anchor", 0), ("num_before", 0), ("num_after", 0)] # type: List[Tuple[str, Any]]
for operand in operands: for operand in operands:
post_params = dict(other_params + [ post_params = dict(other_params + [
@@ -1719,7 +1719,7 @@ class GetOldMessagesTest(ZulipTestCase):
returned. returned.
""" """
self.login(self.example_email("hamlet")) self.login(self.example_email("hamlet"))
bad_stream_content = (0, [], ["x", "y"]) # type: Tuple[int, List[None], List[Text]] bad_stream_content = (0, [], ["x", "y"]) # type: Tuple[int, List[None], List[str]]
self.exercise_bad_narrow_operand("stream", bad_stream_content, self.exercise_bad_narrow_operand("stream", bad_stream_content,
"Bad value for 'narrow'") "Bad value for 'narrow'")
@@ -1729,7 +1729,7 @@ class GetOldMessagesTest(ZulipTestCase):
error is returned. error is returned.
""" """
self.login(self.example_email("hamlet")) self.login(self.example_email("hamlet"))
bad_stream_content = (0, [], ["x", "y"]) # type: Tuple[int, List[None], List[Text]] bad_stream_content = (0, [], ["x", "y"]) # type: Tuple[int, List[None], List[str]]
self.exercise_bad_narrow_operand("pm-with", bad_stream_content, self.exercise_bad_narrow_operand("pm-with", bad_stream_content,
"Bad value for 'narrow'") "Bad value for 'narrow'")
@@ -1752,7 +1752,7 @@ class GetOldMessagesTest(ZulipTestCase):
MessageDict.finalize_payload(d, apply_markdown=True, client_gravatar=False) MessageDict.finalize_payload(d, apply_markdown=True, client_gravatar=False)
self.assertEqual(d['content'], '<p>test content</p>') self.assertEqual(d['content'], '<p>test content</p>')
def common_check_get_messages_query(self, query_params: Dict[str, object], expected: Text) -> None: def common_check_get_messages_query(self, query_params: Dict[str, object], expected: str) -> None:
user_profile = self.example_user('hamlet') user_profile = self.example_user('hamlet')
request = POSTRequestMock(query_params, user_profile) request = POSTRequestMock(query_params, user_profile)
with queries_captured() as queries: with queries_captured() as queries:
@@ -2180,7 +2180,7 @@ class GetOldMessagesTest(ZulipTestCase):
def test_get_messages_with_search_queries(self) -> None: def test_get_messages_with_search_queries(self) -> None:
query_ids = self.get_query_ids() query_ids = self.get_query_ids()
sql_template = "SELECT anon_1.message_id, anon_1.flags, anon_1.subject, anon_1.rendered_content, anon_1.content_matches, anon_1.subject_matches \nFROM (SELECT message_id, flags, subject, rendered_content, ts_match_locs_array('zulip.english_us_search', rendered_content, plainto_tsquery('zulip.english_us_search', 'jumping')) AS content_matches, ts_match_locs_array('zulip.english_us_search', escape_html(subject), plainto_tsquery('zulip.english_us_search', 'jumping')) AS subject_matches \nFROM zerver_usermessage JOIN zerver_message ON zerver_usermessage.message_id = zerver_message.id \nWHERE user_profile_id = {hamlet_id} AND (search_tsvector @@ plainto_tsquery('zulip.english_us_search', 'jumping')) ORDER BY message_id ASC \n LIMIT 10) AS anon_1 ORDER BY message_id ASC" # type: Text sql_template = "SELECT anon_1.message_id, anon_1.flags, anon_1.subject, anon_1.rendered_content, anon_1.content_matches, anon_1.subject_matches \nFROM (SELECT message_id, flags, subject, rendered_content, ts_match_locs_array('zulip.english_us_search', rendered_content, plainto_tsquery('zulip.english_us_search', 'jumping')) AS content_matches, ts_match_locs_array('zulip.english_us_search', escape_html(subject), plainto_tsquery('zulip.english_us_search', 'jumping')) AS subject_matches \nFROM zerver_usermessage JOIN zerver_message ON zerver_usermessage.message_id = zerver_message.id \nWHERE user_profile_id = {hamlet_id} AND (search_tsvector @@ plainto_tsquery('zulip.english_us_search', 'jumping')) ORDER BY message_id ASC \n LIMIT 10) AS anon_1 ORDER BY message_id ASC" # type: str
sql = sql_template.format(**query_ids) sql = sql_template.format(**query_ids)
self.common_check_get_messages_query({'anchor': 0, 'num_before': 0, 'num_after': 9, self.common_check_get_messages_query({'anchor': 0, 'num_before': 0, 'num_after': 9,
'narrow': '[["search", "jumping"]]'}, 'narrow': '[["search", "jumping"]]'},

View File

@@ -2,7 +2,7 @@
import ujson import ujson
from django.http import HttpResponse from django.http import HttpResponse
from typing import Any, Dict, List, Mapping, Text from typing import Any, Dict, List, Mapping
from unittest import mock from unittest import mock
from zerver.lib.emoji import emoji_name_to_emoji_code from zerver.lib.emoji import emoji_name_to_emoji_code

View File

@@ -2,7 +2,7 @@
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
from django.db.utils import IntegrityError from django.db.utils import IntegrityError
from typing import Optional, Text from typing import Optional
from zerver.lib.actions import do_change_is_admin, \ from zerver.lib.actions import do_change_is_admin, \
do_change_realm_domain, do_create_realm, \ do_change_realm_domain, do_create_realm, \

View File

@@ -1,4 +1,4 @@
from typing import Any, Callable, Text from typing import Any, Callable
from zerver.lib.sessions import ( from zerver.lib.sessions import (
user_sessions, user_sessions,
@@ -18,7 +18,7 @@ from zerver.lib.test_classes import ZulipTestCase
class TestSessions(ZulipTestCase): class TestSessions(ZulipTestCase):
def do_test_session(self, user: Text, def do_test_session(self, user: str,
action: Callable[[], Any], action: Callable[[], Any],
realm: Realm, realm: Realm,
expected_result: bool) -> None: expected_result: bool) -> None:

View File

@@ -46,7 +46,7 @@ import shutil
import requests import requests
import os import os
import mock import mock
from typing import Any, AnyStr, Dict, List, Optional, Set, Tuple, Text from typing import Any, AnyStr, Dict, List, Optional, Set, Tuple
def remove_folder(path: str) -> None: def remove_folder(path: str) -> None:
if os.path.exists(path): if os.path.exists(path):

View File

@@ -13,11 +13,11 @@ from zerver.lib import mdiff
import ujson import ujson
import os import os
from typing import Any, AnyStr, Dict, List, Optional, Set, Tuple, Text from typing import Any, AnyStr, Dict, List, Optional, Set, Tuple
class SlackMessageConversion(ZulipTestCase): class SlackMessageConversion(ZulipTestCase):
def assertEqual(self, first: Any, second: Any, msg: Text = "") -> None: def assertEqual(self, first: Any, second: Any, msg: str="") -> None:
if isinstance(first, Text) and isinstance(second, Text): if isinstance(first, str) and isinstance(second, str):
if first != second: if first != second:
raise AssertionError("Actual and expected outputs do not match; showing diff.\n" + raise AssertionError("Actual and expected outputs do not match; showing diff.\n" +
mdiff.diff_strings(first, second) + msg) mdiff.diff_strings(first, second) + msg)

View File

@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-AA # -*- coding: utf-8 -*-AA
from typing import Any, Dict, List, Mapping, Text from typing import Any, Dict, List, Mapping
from django.db import connection from django.db import connection
@@ -361,7 +361,7 @@ class FixUnreadTests(ZulipTestCase):
user = self.example_user('hamlet') user = self.example_user('hamlet')
realm = get_realm('zulip') realm = get_realm('zulip')
def send_message(stream_name: Text, topic_name: Text) -> int: def send_message(stream_name: str, topic_name: str) -> int:
msg_id = self.send_stream_message( msg_id = self.send_stream_message(
self.example_email("othello"), self.example_email("othello"),
stream_name, stream_name,
@@ -379,7 +379,7 @@ class FixUnreadTests(ZulipTestCase):
um = UserMessage.objects.get(id=user_message_id) um = UserMessage.objects.get(id=user_message_id)
self.assertFalse(um.flags.read) self.assertFalse(um.flags.read)
def mute_stream(stream_name: Text) -> None: def mute_stream(stream_name: str) -> None:
stream = get_stream(stream_name, realm) stream = get_stream(stream_name, realm)
recipient = get_stream_recipient(stream.id) recipient = get_stream_recipient(stream.id)
subscription = Subscription.objects.get( subscription = Subscription.objects.get(
@@ -389,7 +389,7 @@ class FixUnreadTests(ZulipTestCase):
subscription.in_home_view = False subscription.in_home_view = False
subscription.save() subscription.save()
def mute_topic(stream_name: Text, topic_name: Text) -> None: def mute_topic(stream_name: str, topic_name: str) -> None:
stream = get_stream(stream_name, realm) stream = get_stream(stream_name, realm)
recipient = get_stream_recipient(stream.id) recipient = get_stream_recipient(stream.id)
@@ -400,7 +400,7 @@ class FixUnreadTests(ZulipTestCase):
topic_name=topic_name, topic_name=topic_name,
) )
def force_unsubscribe(stream_name: Text) -> None: def force_unsubscribe(stream_name: str) -> None:
''' '''
We don't want side effects here, since the eventual We don't want side effects here, since the eventual
unsubscribe path may mark messages as read, defeating unsubscribe path may mark messages as read, defeating

View File

@@ -1,5 +1,4 @@
from typing import Text # -*- coding: utf-8 -*-
from zerver.lib.test_classes import ZulipTestCase, WebhookTestCase from zerver.lib.test_classes import ZulipTestCase, WebhookTestCase
from zerver.lib.webhooks.common import \ from zerver.lib.webhooks.common import \
validate_extract_webhook_http_header, \ validate_extract_webhook_http_header, \
@@ -71,5 +70,5 @@ class MissingEventHeaderTestCase(WebhookTestCase):
self.assertEqual(msg.sender.email, notification_bot.email) self.assertEqual(msg.sender.email, notification_bot.email)
self.assertEqual(msg.content, expected_message) self.assertEqual(msg.content, expected_message)
def get_body(self, fixture_name: Text) -> Text: def get_body(self, fixture_name: str) -> str:
return self.webhook_fixture_data("groove", fixture_name, file_type="json") return self.webhook_fixture_data("groove", fixture_name, file_type="json")