mirror of
https://github.com/zulip/zulip.git
synced 2025-11-13 10:26:28 +00:00
zerver/tests: Use python 3 syntax for typing.
This patch was extracted by tabbott for just the files with no open PRs modifying them.
This commit is contained in:
@@ -28,8 +28,7 @@ from zerver.models import (
|
|||||||
import datetime
|
import datetime
|
||||||
|
|
||||||
class ActivityTest(ZulipTestCase):
|
class ActivityTest(ZulipTestCase):
|
||||||
def test_activity(self):
|
def test_activity(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
self.login(self.example_email("hamlet"))
|
self.login(self.example_email("hamlet"))
|
||||||
client, _ = Client.objects.get_or_create(name='website')
|
client, _ = Client.objects.get_or_create(name='website')
|
||||||
query = '/json/users/me/pointer'
|
query = '/json/users/me/pointer'
|
||||||
@@ -50,8 +49,7 @@ class ActivityTest(ZulipTestCase):
|
|||||||
self.assert_length(queries, 4)
|
self.assert_length(queries, 4)
|
||||||
|
|
||||||
class TestClientModel(ZulipTestCase):
|
class TestClientModel(ZulipTestCase):
|
||||||
def test_client_stringification(self):
|
def test_client_stringification(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
'''
|
'''
|
||||||
This test is designed to cover __str__ method for Client.
|
This test is designed to cover __str__ method for Client.
|
||||||
'''
|
'''
|
||||||
@@ -59,8 +57,7 @@ class TestClientModel(ZulipTestCase):
|
|||||||
self.assertEqual(str(client), '<Client: some_client>')
|
self.assertEqual(str(client), '<Client: some_client>')
|
||||||
|
|
||||||
class UserPresenceModelTests(ZulipTestCase):
|
class UserPresenceModelTests(ZulipTestCase):
|
||||||
def test_date_logic(self):
|
def test_date_logic(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
UserPresence.objects.all().delete()
|
UserPresence.objects.all().delete()
|
||||||
|
|
||||||
user_profile = self.example_user('hamlet')
|
user_profile = self.example_user('hamlet')
|
||||||
@@ -76,8 +73,7 @@ class UserPresenceModelTests(ZulipTestCase):
|
|||||||
self.assertEqual(len(presence_dct), 1)
|
self.assertEqual(len(presence_dct), 1)
|
||||||
self.assertEqual(presence_dct[email]['website']['status'], 'active')
|
self.assertEqual(presence_dct[email]['website']['status'], 'active')
|
||||||
|
|
||||||
def back_date(num_weeks):
|
def back_date(num_weeks: int) -> None:
|
||||||
# type: (int) -> None
|
|
||||||
user_presence = UserPresence.objects.filter(user_profile=user_profile)[0]
|
user_presence = UserPresence.objects.filter(user_profile=user_profile)[0]
|
||||||
user_presence.timestamp = timezone_now() - datetime.timedelta(weeks=num_weeks)
|
user_presence.timestamp = timezone_now() - datetime.timedelta(weeks=num_weeks)
|
||||||
user_presence.save()
|
user_presence.save()
|
||||||
@@ -92,8 +88,7 @@ class UserPresenceModelTests(ZulipTestCase):
|
|||||||
presence_dct = UserPresence.get_status_dict_by_realm(user_profile.realm_id)
|
presence_dct = UserPresence.get_status_dict_by_realm(user_profile.realm_id)
|
||||||
self.assertEqual(len(presence_dct), 0)
|
self.assertEqual(len(presence_dct), 0)
|
||||||
|
|
||||||
def test_push_tokens(self):
|
def test_push_tokens(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
UserPresence.objects.all().delete()
|
UserPresence.objects.all().delete()
|
||||||
|
|
||||||
user_profile = self.example_user('hamlet')
|
user_profile = self.example_user('hamlet')
|
||||||
@@ -103,8 +98,7 @@ class UserPresenceModelTests(ZulipTestCase):
|
|||||||
result = self.client_post("/json/users/me/presence", {'status': 'active'})
|
result = self.client_post("/json/users/me/presence", {'status': 'active'})
|
||||||
self.assert_json_success(result)
|
self.assert_json_success(result)
|
||||||
|
|
||||||
def pushable():
|
def pushable() -> bool:
|
||||||
# type: () -> bool
|
|
||||||
presence_dct = UserPresence.get_status_dict_by_realm(user_profile.realm_id)
|
presence_dct = UserPresence.get_status_dict_by_realm(user_profile.realm_id)
|
||||||
self.assertEqual(len(presence_dct), 1)
|
self.assertEqual(len(presence_dct), 1)
|
||||||
return presence_dct[email]['website']['pushable']
|
return presence_dct[email]['website']['pushable']
|
||||||
@@ -123,15 +117,13 @@ class UserPresenceModelTests(ZulipTestCase):
|
|||||||
self.assertTrue(pushable())
|
self.assertTrue(pushable())
|
||||||
|
|
||||||
class UserPresenceTests(ZulipTestCase):
|
class UserPresenceTests(ZulipTestCase):
|
||||||
def test_invalid_presence(self):
|
def test_invalid_presence(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
email = self.example_email("hamlet")
|
email = self.example_email("hamlet")
|
||||||
self.login(email)
|
self.login(email)
|
||||||
result = self.client_post("/json/users/me/presence", {'status': 'foo'})
|
result = self.client_post("/json/users/me/presence", {'status': 'foo'})
|
||||||
self.assert_json_error(result, 'Invalid status: foo')
|
self.assert_json_error(result, 'Invalid status: foo')
|
||||||
|
|
||||||
def test_set_idle(self):
|
def test_set_idle(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
email = self.example_email("hamlet")
|
email = self.example_email("hamlet")
|
||||||
self.login(email)
|
self.login(email)
|
||||||
client = 'website'
|
client = 'website'
|
||||||
@@ -155,8 +147,7 @@ class UserPresenceTests(ZulipTestCase):
|
|||||||
newer_timestamp = json['presences'][email][client]['timestamp']
|
newer_timestamp = json['presences'][email][client]['timestamp']
|
||||||
self.assertGreaterEqual(newer_timestamp, timestamp)
|
self.assertGreaterEqual(newer_timestamp, timestamp)
|
||||||
|
|
||||||
def test_set_active(self):
|
def test_set_active(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
self.login(self.example_email("hamlet"))
|
self.login(self.example_email("hamlet"))
|
||||||
client = 'website'
|
client = 'website'
|
||||||
|
|
||||||
@@ -179,8 +170,7 @@ class UserPresenceTests(ZulipTestCase):
|
|||||||
self.assertEqual(json['presences'][email][client]['status'], 'active')
|
self.assertEqual(json['presences'][email][client]['status'], 'active')
|
||||||
self.assertEqual(json['presences'][self.example_email("hamlet")][client]['status'], 'idle')
|
self.assertEqual(json['presences'][self.example_email("hamlet")][client]['status'], 'idle')
|
||||||
|
|
||||||
def test_no_mit(self):
|
def test_no_mit(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
"""Zephyr mirror realms such as MIT never get a list of users"""
|
"""Zephyr mirror realms such as MIT never get a list of users"""
|
||||||
self.login(self.mit_email("espuser"))
|
self.login(self.mit_email("espuser"))
|
||||||
result = self.client_post("/json/users/me/presence", {'status': 'idle'},
|
result = self.client_post("/json/users/me/presence", {'status': 'idle'},
|
||||||
@@ -188,15 +178,13 @@ class UserPresenceTests(ZulipTestCase):
|
|||||||
self.assert_json_success(result)
|
self.assert_json_success(result)
|
||||||
self.assertEqual(result.json()['presences'], {})
|
self.assertEqual(result.json()['presences'], {})
|
||||||
|
|
||||||
def test_mirror_presence(self):
|
def test_mirror_presence(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
"""Zephyr mirror realms find out the status of their mirror bot"""
|
"""Zephyr mirror realms find out the status of their mirror bot"""
|
||||||
user_profile = self.mit_user('espuser')
|
user_profile = self.mit_user('espuser')
|
||||||
email = user_profile.email
|
email = user_profile.email
|
||||||
self.login(email)
|
self.login(email)
|
||||||
|
|
||||||
def post_presence():
|
def post_presence() -> Dict[str, Any]:
|
||||||
# type: () -> Dict[str, Any]
|
|
||||||
result = self.client_post("/json/users/me/presence", {'status': 'idle'},
|
result = self.client_post("/json/users/me/presence", {'status': 'idle'},
|
||||||
subdomain="zephyr")
|
subdomain="zephyr")
|
||||||
self.assert_json_success(result)
|
self.assert_json_success(result)
|
||||||
@@ -210,8 +198,7 @@ class UserPresenceTests(ZulipTestCase):
|
|||||||
json = post_presence()
|
json = post_presence()
|
||||||
self.assertEqual(json['zephyr_mirror_active'], True)
|
self.assertEqual(json['zephyr_mirror_active'], True)
|
||||||
|
|
||||||
def _simulate_mirror_activity_for_user(self, user_profile):
|
def _simulate_mirror_activity_for_user(self, user_profile: UserProfile) -> None:
|
||||||
# type: (UserProfile) -> None
|
|
||||||
last_visit = timezone_now()
|
last_visit = timezone_now()
|
||||||
client = make_client('zephyr_mirror')
|
client = make_client('zephyr_mirror')
|
||||||
|
|
||||||
@@ -223,8 +210,7 @@ class UserPresenceTests(ZulipTestCase):
|
|||||||
last_visit=last_visit
|
last_visit=last_visit
|
||||||
)
|
)
|
||||||
|
|
||||||
def test_same_realm(self):
|
def test_same_realm(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
self.login(self.mit_email("espuser"))
|
self.login(self.mit_email("espuser"))
|
||||||
self.client_post("/json/users/me/presence", {'status': 'idle'},
|
self.client_post("/json/users/me/presence", {'status': 'idle'},
|
||||||
subdomain="zephyr")
|
subdomain="zephyr")
|
||||||
@@ -241,8 +227,7 @@ class UserPresenceTests(ZulipTestCase):
|
|||||||
self.assertEqual(email_to_domain(email), 'zulip.com')
|
self.assertEqual(email_to_domain(email), 'zulip.com')
|
||||||
|
|
||||||
class SingleUserPresenceTests(ZulipTestCase):
|
class SingleUserPresenceTests(ZulipTestCase):
|
||||||
def test_single_user_get(self):
|
def test_single_user_get(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
|
|
||||||
# First, we setup the test with some data
|
# First, we setup the test with some data
|
||||||
email = self.example_email("othello")
|
email = self.example_email("othello")
|
||||||
@@ -283,8 +268,7 @@ class SingleUserPresenceTests(ZulipTestCase):
|
|||||||
{"ZulipAndroid", "website", "aggregated"})
|
{"ZulipAndroid", "website", "aggregated"})
|
||||||
self.assertEqual(set(result_dict['presence']['website'].keys()), {"status", "timestamp"})
|
self.assertEqual(set(result_dict['presence']['website'].keys()), {"status", "timestamp"})
|
||||||
|
|
||||||
def test_ping_only(self):
|
def test_ping_only(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
|
|
||||||
self.login(self.example_email("othello"))
|
self.login(self.example_email("othello"))
|
||||||
req = dict(
|
req = dict(
|
||||||
@@ -295,8 +279,7 @@ class SingleUserPresenceTests(ZulipTestCase):
|
|||||||
self.assertEqual(result.json()['msg'], '')
|
self.assertEqual(result.json()['msg'], '')
|
||||||
|
|
||||||
class UserPresenceAggregationTests(ZulipTestCase):
|
class UserPresenceAggregationTests(ZulipTestCase):
|
||||||
def _send_presence_for_aggregated_tests(self, email, status, validate_time):
|
def _send_presence_for_aggregated_tests(self, email: str, status: str, validate_time: datetime.datetime) -> Dict[str, Dict[str, Any]]:
|
||||||
# type: (str, str, datetime.datetime) -> Dict[str, Dict[str, Any]]
|
|
||||||
self.login(email)
|
self.login(email)
|
||||||
timezone_util = 'zerver.views.presence.timezone_now'
|
timezone_util = 'zerver.views.presence.timezone_now'
|
||||||
with mock.patch(timezone_util, return_value=validate_time - datetime.timedelta(seconds=5)):
|
with mock.patch(timezone_util, return_value=validate_time - datetime.timedelta(seconds=5)):
|
||||||
@@ -321,8 +304,7 @@ class UserPresenceAggregationTests(ZulipTestCase):
|
|||||||
result = self.client_get("/json/users/%s/presence" % (email,))
|
result = self.client_get("/json/users/%s/presence" % (email,))
|
||||||
return result.json()
|
return result.json()
|
||||||
|
|
||||||
def test_aggregated_info(self):
|
def test_aggregated_info(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
email = self.example_email("othello")
|
email = self.example_email("othello")
|
||||||
validate_time = timezone_now()
|
validate_time = timezone_now()
|
||||||
self._send_presence_for_aggregated_tests(str(self.example_email("othello")), 'active', validate_time)
|
self._send_presence_for_aggregated_tests(str(self.example_email("othello")), 'active', validate_time)
|
||||||
@@ -341,8 +323,7 @@ class UserPresenceAggregationTests(ZulipTestCase):
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
def test_aggregated_presense_active(self):
|
def test_aggregated_presense_active(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
validate_time = timezone_now()
|
validate_time = timezone_now()
|
||||||
result_dict = self._send_presence_for_aggregated_tests(str(self.example_email("othello")), 'active',
|
result_dict = self._send_presence_for_aggregated_tests(str(self.example_email("othello")), 'active',
|
||||||
validate_time)
|
validate_time)
|
||||||
@@ -354,8 +335,7 @@ class UserPresenceAggregationTests(ZulipTestCase):
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
def test_aggregated_presense_idle(self):
|
def test_aggregated_presense_idle(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
validate_time = timezone_now()
|
validate_time = timezone_now()
|
||||||
result_dict = self._send_presence_for_aggregated_tests(str(self.example_email("othello")), 'idle',
|
result_dict = self._send_presence_for_aggregated_tests(str(self.example_email("othello")), 'idle',
|
||||||
validate_time)
|
validate_time)
|
||||||
@@ -367,8 +347,7 @@ class UserPresenceAggregationTests(ZulipTestCase):
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
def test_aggregated_presense_mixed(self):
|
def test_aggregated_presense_mixed(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
email = self.example_email("othello")
|
email = self.example_email("othello")
|
||||||
self.login(email)
|
self.login(email)
|
||||||
validate_time = timezone_now()
|
validate_time = timezone_now()
|
||||||
@@ -386,8 +365,7 @@ class UserPresenceAggregationTests(ZulipTestCase):
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
def test_aggregated_presense_offline(self):
|
def test_aggregated_presense_offline(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
email = self.example_email("othello")
|
email = self.example_email("othello")
|
||||||
self.login(email)
|
self.login(email)
|
||||||
validate_time = timezone_now()
|
validate_time = timezone_now()
|
||||||
|
|||||||
@@ -17,23 +17,21 @@ from zerver.worker import queue_processors
|
|||||||
|
|
||||||
class WorkerTest(ZulipTestCase):
|
class WorkerTest(ZulipTestCase):
|
||||||
class FakeClient:
|
class FakeClient:
|
||||||
def __init__(self):
|
def __init__(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
self.consumers = {} # type: Dict[str, Callable[[Dict[str, Any]], None]]
|
self.consumers = {} # type: Dict[str, Callable[[Dict[str, Any]], None]]
|
||||||
self.queue = [] # type: List[Tuple[str, Dict[str, Any]]]
|
self.queue = [] # type: List[Tuple[str, Dict[str, Any]]]
|
||||||
|
|
||||||
def register_json_consumer(self, queue_name, callback):
|
def register_json_consumer(self,
|
||||||
# type: (str, Callable[[Dict[str, Any]], None]) -> None
|
queue_name: str,
|
||||||
|
callback: Callable[[Dict[str, Any]], None]) -> None:
|
||||||
self.consumers[queue_name] = callback
|
self.consumers[queue_name] = callback
|
||||||
|
|
||||||
def start_consuming(self):
|
def start_consuming(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
for queue_name, data in self.queue:
|
for queue_name, data in self.queue:
|
||||||
callback = self.consumers[queue_name]
|
callback = self.consumers[queue_name]
|
||||||
callback(data)
|
callback(data)
|
||||||
|
|
||||||
def test_mirror_worker(self):
|
def test_mirror_worker(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
fake_client = self.FakeClient()
|
fake_client = self.FakeClient()
|
||||||
data = [
|
data = [
|
||||||
dict(
|
dict(
|
||||||
@@ -61,8 +59,7 @@ class WorkerTest(ZulipTestCase):
|
|||||||
worker.setup()
|
worker.setup()
|
||||||
worker.start()
|
worker.start()
|
||||||
|
|
||||||
def test_email_sending_worker_retries(self):
|
def test_email_sending_worker_retries(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
"""Tests the retry_send_email_failures decorator to make sure it
|
"""Tests the retry_send_email_failures decorator to make sure it
|
||||||
retries sending the email 3 times and then gives up."""
|
retries sending the email 3 times and then gives up."""
|
||||||
fake_client = self.FakeClient()
|
fake_client = self.FakeClient()
|
||||||
@@ -70,8 +67,9 @@ class WorkerTest(ZulipTestCase):
|
|||||||
data = {'test': 'test', 'id': 'test_missed'}
|
data = {'test': 'test', 'id': 'test_missed'}
|
||||||
fake_client.queue.append(('missedmessage_email_senders', data))
|
fake_client.queue.append(('missedmessage_email_senders', data))
|
||||||
|
|
||||||
def fake_publish(queue_name, event, processor):
|
def fake_publish(queue_name: str,
|
||||||
# type: (str, Dict[str, Any], Callable[[Any], None]) -> None
|
event: Dict[str, Any],
|
||||||
|
processor: Callable[[Any], None]) -> None:
|
||||||
fake_client.queue.append((queue_name, event))
|
fake_client.queue.append((queue_name, event))
|
||||||
|
|
||||||
with simulated_queue_client(lambda: fake_client):
|
with simulated_queue_client(lambda: fake_client):
|
||||||
@@ -86,8 +84,7 @@ class WorkerTest(ZulipTestCase):
|
|||||||
|
|
||||||
self.assertEqual(data['failed_tries'], 4)
|
self.assertEqual(data['failed_tries'], 4)
|
||||||
|
|
||||||
def test_signups_worker_retries(self):
|
def test_signups_worker_retries(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
"""Tests the retry logic of signups queue."""
|
"""Tests the retry logic of signups queue."""
|
||||||
fake_client = self.FakeClient()
|
fake_client = self.FakeClient()
|
||||||
|
|
||||||
@@ -95,8 +92,7 @@ class WorkerTest(ZulipTestCase):
|
|||||||
data = {'user_id': user_id, 'id': 'test_missed'}
|
data = {'user_id': user_id, 'id': 'test_missed'}
|
||||||
fake_client.queue.append(('signups', data))
|
fake_client.queue.append(('signups', data))
|
||||||
|
|
||||||
def fake_publish(queue_name, event, processor):
|
def fake_publish(queue_name: str, event: Dict[str, Any], processor: Callable[[Any], None]) -> None:
|
||||||
# type: (str, Dict[str, Any], Callable[[Any], None]) -> None
|
|
||||||
fake_client.queue.append((queue_name, event))
|
fake_client.queue.append((queue_name, event))
|
||||||
|
|
||||||
fake_response = MagicMock()
|
fake_response = MagicMock()
|
||||||
@@ -117,8 +113,7 @@ class WorkerTest(ZulipTestCase):
|
|||||||
|
|
||||||
self.assertEqual(data['failed_tries'], 4)
|
self.assertEqual(data['failed_tries'], 4)
|
||||||
|
|
||||||
def test_UserActivityWorker(self):
|
def test_UserActivityWorker(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
fake_client = self.FakeClient()
|
fake_client = self.FakeClient()
|
||||||
|
|
||||||
user = self.example_user('hamlet')
|
user = self.example_user('hamlet')
|
||||||
@@ -146,20 +141,17 @@ class WorkerTest(ZulipTestCase):
|
|||||||
self.assertTrue(len(activity_records), 1)
|
self.assertTrue(len(activity_records), 1)
|
||||||
self.assertTrue(activity_records[0].count, 1)
|
self.assertTrue(activity_records[0].count, 1)
|
||||||
|
|
||||||
def test_error_handling(self):
|
def test_error_handling(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
processed = []
|
processed = []
|
||||||
|
|
||||||
@queue_processors.assign_queue('unreliable_worker')
|
@queue_processors.assign_queue('unreliable_worker')
|
||||||
class UnreliableWorker(queue_processors.QueueProcessingWorker):
|
class UnreliableWorker(queue_processors.QueueProcessingWorker):
|
||||||
def consume(self, data):
|
def consume(self, data: Mapping[str, Any]) -> None:
|
||||||
# type: (Mapping[str, Any]) -> None
|
|
||||||
if data["type"] == 'unexpected behaviour':
|
if data["type"] == 'unexpected behaviour':
|
||||||
raise Exception('Worker task not performing as expected!')
|
raise Exception('Worker task not performing as expected!')
|
||||||
processed.append(data["type"])
|
processed.append(data["type"])
|
||||||
|
|
||||||
def _log_problem(self):
|
def _log_problem(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
|
|
||||||
# keep the tests quiet
|
# keep the tests quiet
|
||||||
pass
|
pass
|
||||||
@@ -184,25 +176,20 @@ class WorkerTest(ZulipTestCase):
|
|||||||
event = ujson.loads(line.split('\t')[1])
|
event = ujson.loads(line.split('\t')[1])
|
||||||
self.assertEqual(event["type"], 'unexpected behaviour')
|
self.assertEqual(event["type"], 'unexpected behaviour')
|
||||||
|
|
||||||
def test_worker_noname(self):
|
def test_worker_noname(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
class TestWorker(queue_processors.QueueProcessingWorker):
|
class TestWorker(queue_processors.QueueProcessingWorker):
|
||||||
def __init__(self):
|
def __init__(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
super().__init__()
|
super().__init__()
|
||||||
|
|
||||||
def consume(self, data):
|
def consume(self, data: Mapping[str, Any]) -> None:
|
||||||
# type: (Mapping[str, Any]) -> None
|
|
||||||
pass # nocoverage # this is intentionally not called
|
pass # nocoverage # this is intentionally not called
|
||||||
with self.assertRaises(queue_processors.WorkerDeclarationException):
|
with self.assertRaises(queue_processors.WorkerDeclarationException):
|
||||||
TestWorker()
|
TestWorker()
|
||||||
|
|
||||||
def test_worker_noconsume(self):
|
def test_worker_noconsume(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
@queue_processors.assign_queue('test_worker')
|
@queue_processors.assign_queue('test_worker')
|
||||||
class TestWorker(queue_processors.QueueProcessingWorker):
|
class TestWorker(queue_processors.QueueProcessingWorker):
|
||||||
def __init__(self):
|
def __init__(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
super().__init__()
|
super().__init__()
|
||||||
|
|
||||||
with self.assertRaises(queue_processors.WorkerDeclarationException):
|
with self.assertRaises(queue_processors.WorkerDeclarationException):
|
||||||
|
|||||||
@@ -16,8 +16,7 @@ import ujson
|
|||||||
|
|
||||||
|
|
||||||
class RealmDomainTest(ZulipTestCase):
|
class RealmDomainTest(ZulipTestCase):
|
||||||
def test_list_realm_domains(self):
|
def test_list_realm_domains(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
self.login(self.example_email("iago"))
|
self.login(self.example_email("iago"))
|
||||||
realm = get_realm('zulip')
|
realm = get_realm('zulip')
|
||||||
RealmDomain.objects.create(realm=realm, domain='acme.com', allow_subdomains=True)
|
RealmDomain.objects.create(realm=realm, domain='acme.com', allow_subdomains=True)
|
||||||
@@ -29,8 +28,7 @@ class RealmDomainTest(ZulipTestCase):
|
|||||||
sort_keys=True)
|
sort_keys=True)
|
||||||
self.assertEqual(received, expected)
|
self.assertEqual(received, expected)
|
||||||
|
|
||||||
def test_not_realm_admin(self):
|
def test_not_realm_admin(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
self.login(self.example_email("hamlet"))
|
self.login(self.example_email("hamlet"))
|
||||||
result = self.client_post("/json/realm/domains")
|
result = self.client_post("/json/realm/domains")
|
||||||
self.assert_json_error(result, 'Must be a realm administrator')
|
self.assert_json_error(result, 'Must be a realm administrator')
|
||||||
@@ -39,8 +37,7 @@ class RealmDomainTest(ZulipTestCase):
|
|||||||
result = self.client_delete("/json/realm/domains/15")
|
result = self.client_delete("/json/realm/domains/15")
|
||||||
self.assert_json_error(result, 'Must be a realm administrator')
|
self.assert_json_error(result, 'Must be a realm administrator')
|
||||||
|
|
||||||
def test_create_realm_domain(self):
|
def test_create_realm_domain(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
self.login(self.example_email("iago"))
|
self.login(self.example_email("iago"))
|
||||||
data = {'domain': ujson.dumps(''),
|
data = {'domain': ujson.dumps(''),
|
||||||
'allow_subdomains': ujson.dumps(True)}
|
'allow_subdomains': ujson.dumps(True)}
|
||||||
@@ -66,8 +63,7 @@ class RealmDomainTest(ZulipTestCase):
|
|||||||
HTTP_HOST=mit_user_profile.realm.host)
|
HTTP_HOST=mit_user_profile.realm.host)
|
||||||
self.assert_json_success(result)
|
self.assert_json_success(result)
|
||||||
|
|
||||||
def test_patch_realm_domain(self):
|
def test_patch_realm_domain(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
self.login(self.example_email("iago"))
|
self.login(self.example_email("iago"))
|
||||||
realm = get_realm('zulip')
|
realm = get_realm('zulip')
|
||||||
RealmDomain.objects.create(realm=realm, domain='acme.com',
|
RealmDomain.objects.create(realm=realm, domain='acme.com',
|
||||||
@@ -86,8 +82,7 @@ class RealmDomainTest(ZulipTestCase):
|
|||||||
self.assertEqual(result.status_code, 400)
|
self.assertEqual(result.status_code, 400)
|
||||||
self.assert_json_error(result, 'No entry found for domain non-existent.com.')
|
self.assert_json_error(result, 'No entry found for domain non-existent.com.')
|
||||||
|
|
||||||
def test_delete_realm_domain(self):
|
def test_delete_realm_domain(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
self.login(self.example_email("iago"))
|
self.login(self.example_email("iago"))
|
||||||
realm = get_realm('zulip')
|
realm = get_realm('zulip')
|
||||||
RealmDomain.objects.create(realm=realm, domain='acme.com')
|
RealmDomain.objects.create(realm=realm, domain='acme.com')
|
||||||
@@ -100,8 +95,7 @@ class RealmDomainTest(ZulipTestCase):
|
|||||||
self.assertFalse(RealmDomain.objects.filter(domain='acme.com').exists())
|
self.assertFalse(RealmDomain.objects.filter(domain='acme.com').exists())
|
||||||
self.assertTrue(realm.restricted_to_domain)
|
self.assertTrue(realm.restricted_to_domain)
|
||||||
|
|
||||||
def test_delete_all_realm_domains(self):
|
def test_delete_all_realm_domains(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
self.login(self.example_email("iago"))
|
self.login(self.example_email("iago"))
|
||||||
realm = get_realm('zulip')
|
realm = get_realm('zulip')
|
||||||
query = RealmDomain.objects.filter(realm=realm)
|
query = RealmDomain.objects.filter(realm=realm)
|
||||||
@@ -115,8 +109,7 @@ class RealmDomainTest(ZulipTestCase):
|
|||||||
# would not be updated.
|
# would not be updated.
|
||||||
self.assertFalse(get_realm('zulip').restricted_to_domain)
|
self.assertFalse(get_realm('zulip').restricted_to_domain)
|
||||||
|
|
||||||
def test_email_allowed_for_realm(self):
|
def test_email_allowed_for_realm(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
realm1 = do_create_realm('testrealm1', 'Test Realm 1', restricted_to_domain=True)
|
realm1 = do_create_realm('testrealm1', 'Test Realm 1', restricted_to_domain=True)
|
||||||
realm2 = do_create_realm('testrealm2', 'Test Realm 2', restricted_to_domain=True)
|
realm2 = do_create_realm('testrealm2', 'Test Realm 2', restricted_to_domain=True)
|
||||||
|
|
||||||
@@ -134,14 +127,12 @@ class RealmDomainTest(ZulipTestCase):
|
|||||||
self.assertEqual(email_allowed_for_realm('user@test2.test1.com', realm1), True)
|
self.assertEqual(email_allowed_for_realm('user@test2.test1.com', realm1), True)
|
||||||
self.assertEqual(email_allowed_for_realm('user@test2.com', realm1), False)
|
self.assertEqual(email_allowed_for_realm('user@test2.com', realm1), False)
|
||||||
|
|
||||||
def test_realm_realm_domains_uniqueness(self):
|
def test_realm_realm_domains_uniqueness(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
realm = get_realm('zulip')
|
realm = get_realm('zulip')
|
||||||
with self.assertRaises(IntegrityError):
|
with self.assertRaises(IntegrityError):
|
||||||
RealmDomain.objects.create(realm=realm, domain='zulip.com', allow_subdomains=True)
|
RealmDomain.objects.create(realm=realm, domain='zulip.com', allow_subdomains=True)
|
||||||
|
|
||||||
def test_validate_domain(self):
|
def test_validate_domain(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
invalid_domains = ['', 'test', 't.', 'test.', '.com', '-test', 'test...com',
|
invalid_domains = ['', 'test', 't.', 'test.', '.com', '-test', 'test...com',
|
||||||
'test-', 'test_domain.com', 'test.-domain.com']
|
'test-', 'test_domain.com', 'test.-domain.com']
|
||||||
for domain in invalid_domains:
|
for domain in invalid_domains:
|
||||||
|
|||||||
@@ -7,8 +7,7 @@ from zerver.models import RealmEmoji
|
|||||||
|
|
||||||
class RealmEmojiTest(ZulipTestCase):
|
class RealmEmojiTest(ZulipTestCase):
|
||||||
|
|
||||||
def test_list(self):
|
def test_list(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
email = self.example_email('iago')
|
email = self.example_email('iago')
|
||||||
self.login(email)
|
self.login(email)
|
||||||
realm = get_realm('zulip')
|
realm = get_realm('zulip')
|
||||||
@@ -18,8 +17,7 @@ class RealmEmojiTest(ZulipTestCase):
|
|||||||
self.assertEqual(200, result.status_code)
|
self.assertEqual(200, result.status_code)
|
||||||
self.assertEqual(len(result.json()["emoji"]), 2)
|
self.assertEqual(len(result.json()["emoji"]), 2)
|
||||||
|
|
||||||
def test_list_no_author(self):
|
def test_list_no_author(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
email = self.example_email('iago')
|
email = self.example_email('iago')
|
||||||
self.login(email)
|
self.login(email)
|
||||||
realm = get_realm('zulip')
|
realm = get_realm('zulip')
|
||||||
@@ -30,8 +28,7 @@ class RealmEmojiTest(ZulipTestCase):
|
|||||||
self.assertEqual(len(content["emoji"]), 2)
|
self.assertEqual(len(content["emoji"]), 2)
|
||||||
self.assertIsNone(content["emoji"]['my_emoji']['author'])
|
self.assertIsNone(content["emoji"]['my_emoji']['author'])
|
||||||
|
|
||||||
def test_list_admins_only(self):
|
def test_list_admins_only(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
email = self.example_email('othello')
|
email = self.example_email('othello')
|
||||||
self.login(email)
|
self.login(email)
|
||||||
realm = get_realm('zulip')
|
realm = get_realm('zulip')
|
||||||
@@ -44,8 +41,7 @@ class RealmEmojiTest(ZulipTestCase):
|
|||||||
self.assertEqual(len(content["emoji"]), 2)
|
self.assertEqual(len(content["emoji"]), 2)
|
||||||
self.assertIsNone(content["emoji"]['my_emoji']['author'])
|
self.assertIsNone(content["emoji"]['my_emoji']['author'])
|
||||||
|
|
||||||
def test_upload(self):
|
def test_upload(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
email = self.example_email('iago')
|
email = self.example_email('iago')
|
||||||
self.login(email)
|
self.login(email)
|
||||||
with get_test_image_file('img.png') as fp1:
|
with get_test_image_file('img.png') as fp1:
|
||||||
@@ -70,8 +66,7 @@ class RealmEmojiTest(ZulipTestCase):
|
|||||||
'<RealmEmoji(zulip): my_emoji my_emoji.png>'
|
'<RealmEmoji(zulip): my_emoji my_emoji.png>'
|
||||||
)
|
)
|
||||||
|
|
||||||
def test_upload_exception(self):
|
def test_upload_exception(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
email = self.example_email('iago')
|
email = self.example_email('iago')
|
||||||
self.login(email)
|
self.login(email)
|
||||||
with get_test_image_file('img.png') as fp1:
|
with get_test_image_file('img.png') as fp1:
|
||||||
@@ -79,8 +74,7 @@ class RealmEmojiTest(ZulipTestCase):
|
|||||||
result = self.client_post('/json/realm/emoji/my_em*oji', info=emoji_data)
|
result = self.client_post('/json/realm/emoji/my_em*oji', info=emoji_data)
|
||||||
self.assert_json_error(result, 'Invalid characters in emoji name')
|
self.assert_json_error(result, 'Invalid characters in emoji name')
|
||||||
|
|
||||||
def test_upload_uppercase_exception(self):
|
def test_upload_uppercase_exception(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
email = self.example_email('iago')
|
email = self.example_email('iago')
|
||||||
self.login(email)
|
self.login(email)
|
||||||
with get_test_image_file('img.png') as fp1:
|
with get_test_image_file('img.png') as fp1:
|
||||||
@@ -88,8 +82,7 @@ class RealmEmojiTest(ZulipTestCase):
|
|||||||
result = self.client_post('/json/realm/emoji/my_EMoji', info=emoji_data)
|
result = self.client_post('/json/realm/emoji/my_EMoji', info=emoji_data)
|
||||||
self.assert_json_error(result, 'Invalid characters in emoji name')
|
self.assert_json_error(result, 'Invalid characters in emoji name')
|
||||||
|
|
||||||
def test_upload_admins_only(self):
|
def test_upload_admins_only(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
email = self.example_email('othello')
|
email = self.example_email('othello')
|
||||||
self.login(email)
|
self.login(email)
|
||||||
realm = get_realm('zulip')
|
realm = get_realm('zulip')
|
||||||
@@ -100,8 +93,7 @@ class RealmEmojiTest(ZulipTestCase):
|
|||||||
result = self.client_post('/json/realm/emoji/my_emoji', info=emoji_data)
|
result = self.client_post('/json/realm/emoji/my_emoji', info=emoji_data)
|
||||||
self.assert_json_error(result, 'Must be a realm administrator')
|
self.assert_json_error(result, 'Must be a realm administrator')
|
||||||
|
|
||||||
def test_upload_anyone(self):
|
def test_upload_anyone(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
email = self.example_email('othello')
|
email = self.example_email('othello')
|
||||||
self.login(email)
|
self.login(email)
|
||||||
realm = get_realm('zulip')
|
realm = get_realm('zulip')
|
||||||
@@ -112,8 +104,7 @@ class RealmEmojiTest(ZulipTestCase):
|
|||||||
result = self.client_post('/json/realm/emoji/my_emoji', info=emoji_data)
|
result = self.client_post('/json/realm/emoji/my_emoji', info=emoji_data)
|
||||||
self.assert_json_success(result)
|
self.assert_json_success(result)
|
||||||
|
|
||||||
def test_delete(self):
|
def test_delete(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
email = self.example_email('iago')
|
email = self.example_email('iago')
|
||||||
self.login(email)
|
self.login(email)
|
||||||
realm = get_realm('zulip')
|
realm = get_realm('zulip')
|
||||||
@@ -129,8 +120,7 @@ class RealmEmojiTest(ZulipTestCase):
|
|||||||
self.assertEqual(len(emojis), 2)
|
self.assertEqual(len(emojis), 2)
|
||||||
self.assertEqual(emojis["my_emoji"]["deactivated"], True)
|
self.assertEqual(emojis["my_emoji"]["deactivated"], True)
|
||||||
|
|
||||||
def test_delete_admins_only(self):
|
def test_delete_admins_only(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
email = self.example_email('othello')
|
email = self.example_email('othello')
|
||||||
self.login(email)
|
self.login(email)
|
||||||
realm = get_realm('zulip')
|
realm = get_realm('zulip')
|
||||||
@@ -140,8 +130,7 @@ class RealmEmojiTest(ZulipTestCase):
|
|||||||
result = self.client_delete("/json/realm/emoji/my_emoji")
|
result = self.client_delete("/json/realm/emoji/my_emoji")
|
||||||
self.assert_json_error(result, 'Must be a realm administrator')
|
self.assert_json_error(result, 'Must be a realm administrator')
|
||||||
|
|
||||||
def test_delete_admin_or_author(self):
|
def test_delete_admin_or_author(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
# If any user in a realm can upload the emoji then the user who
|
# If any user in a realm can upload the emoji then the user who
|
||||||
# uploaded it as well as the admin should be able to delete it.
|
# uploaded it as well as the admin should be able to delete it.
|
||||||
realm = get_realm('zulip')
|
realm = get_realm('zulip')
|
||||||
@@ -165,23 +154,20 @@ class RealmEmojiTest(ZulipTestCase):
|
|||||||
result = self.client_delete("/json/realm/emoji/my_emoji_3")
|
result = self.client_delete("/json/realm/emoji/my_emoji_3")
|
||||||
self.assert_json_error(result, 'Must be a realm administrator or emoji author')
|
self.assert_json_error(result, 'Must be a realm administrator or emoji author')
|
||||||
|
|
||||||
def test_delete_exception(self):
|
def test_delete_exception(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
email = self.example_email('iago')
|
email = self.example_email('iago')
|
||||||
self.login(email)
|
self.login(email)
|
||||||
result = self.client_delete("/json/realm/emoji/invalid_emoji")
|
result = self.client_delete("/json/realm/emoji/invalid_emoji")
|
||||||
self.assert_json_error(result, "Emoji 'invalid_emoji' does not exist")
|
self.assert_json_error(result, "Emoji 'invalid_emoji' does not exist")
|
||||||
|
|
||||||
def test_multiple_upload(self):
|
def test_multiple_upload(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
email = self.example_email('iago')
|
email = self.example_email('iago')
|
||||||
self.login(email)
|
self.login(email)
|
||||||
with get_test_image_file('img.png') as fp1, get_test_image_file('img.png') as fp2:
|
with get_test_image_file('img.png') as fp1, get_test_image_file('img.png') as fp2:
|
||||||
result = self.client_post('/json/realm/emoji/my_emoji', {'f1': fp1, 'f2': fp2})
|
result = self.client_post('/json/realm/emoji/my_emoji', {'f1': fp1, 'f2': fp2})
|
||||||
self.assert_json_error(result, 'You must upload exactly one file.')
|
self.assert_json_error(result, 'You must upload exactly one file.')
|
||||||
|
|
||||||
def test_emoji_upload_file_size_error(self):
|
def test_emoji_upload_file_size_error(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
email = self.example_email('iago')
|
email = self.example_email('iago')
|
||||||
self.login(email)
|
self.login(email)
|
||||||
with get_test_image_file('img.png') as fp:
|
with get_test_image_file('img.png') as fp:
|
||||||
@@ -189,8 +175,7 @@ class RealmEmojiTest(ZulipTestCase):
|
|||||||
result = self.client_post('/json/realm/emoji/my_emoji', {'file': fp})
|
result = self.client_post('/json/realm/emoji/my_emoji', {'file': fp})
|
||||||
self.assert_json_error(result, 'Uploaded file is larger than the allowed limit of 0 MB')
|
self.assert_json_error(result, 'Uploaded file is larger than the allowed limit of 0 MB')
|
||||||
|
|
||||||
def test_upload_already_existed_emoji(self):
|
def test_upload_already_existed_emoji(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
email = self.example_email('iago')
|
email = self.example_email('iago')
|
||||||
self.login(email)
|
self.login(email)
|
||||||
with get_test_image_file('img.png') as fp1:
|
with get_test_image_file('img.png') as fp1:
|
||||||
|
|||||||
@@ -6,8 +6,7 @@ from zerver.models import RealmFilter
|
|||||||
|
|
||||||
class RealmFilterTest(ZulipTestCase):
|
class RealmFilterTest(ZulipTestCase):
|
||||||
|
|
||||||
def test_list(self):
|
def test_list(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
email = self.example_email('iago')
|
email = self.example_email('iago')
|
||||||
self.login(email)
|
self.login(email)
|
||||||
realm = get_realm('zulip')
|
realm = get_realm('zulip')
|
||||||
@@ -20,8 +19,7 @@ class RealmFilterTest(ZulipTestCase):
|
|||||||
self.assertEqual(200, result.status_code)
|
self.assertEqual(200, result.status_code)
|
||||||
self.assertEqual(len(result.json()["filters"]), 1)
|
self.assertEqual(len(result.json()["filters"]), 1)
|
||||||
|
|
||||||
def test_create(self):
|
def test_create(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
email = self.example_email('iago')
|
email = self.example_email('iago')
|
||||||
self.login(email)
|
self.login(email)
|
||||||
data = {"pattern": "", "url_format_string": "https://realm.com/my_realm_filter/%(id)s"}
|
data = {"pattern": "", "url_format_string": "https://realm.com/my_realm_filter/%(id)s"}
|
||||||
@@ -55,8 +53,7 @@ class RealmFilterTest(ZulipTestCase):
|
|||||||
result = self.client_post("/json/realm/filters", info=data)
|
result = self.client_post("/json/realm/filters", info=data)
|
||||||
self.assert_json_success(result)
|
self.assert_json_success(result)
|
||||||
|
|
||||||
def test_not_realm_admin(self):
|
def test_not_realm_admin(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
email = self.example_email('hamlet')
|
email = self.example_email('hamlet')
|
||||||
self.login(email)
|
self.login(email)
|
||||||
result = self.client_post("/json/realm/filters")
|
result = self.client_post("/json/realm/filters")
|
||||||
@@ -64,8 +61,7 @@ class RealmFilterTest(ZulipTestCase):
|
|||||||
result = self.client_delete("/json/realm/filters/15")
|
result = self.client_delete("/json/realm/filters/15")
|
||||||
self.assert_json_error(result, 'Must be a realm administrator')
|
self.assert_json_error(result, 'Must be a realm administrator')
|
||||||
|
|
||||||
def test_delete(self):
|
def test_delete(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
email = self.example_email('iago')
|
email = self.example_email('iago')
|
||||||
self.login(email)
|
self.login(email)
|
||||||
realm = get_realm('zulip')
|
realm = get_realm('zulip')
|
||||||
|
|||||||
@@ -11,23 +11,19 @@ from zerver.lib.utils import statsd
|
|||||||
import mock
|
import mock
|
||||||
import ujson
|
import ujson
|
||||||
|
|
||||||
def fix_params(raw_params):
|
def fix_params(raw_params: Dict[str, Any]) -> Dict[str, str]:
|
||||||
# type: (Dict[str, Any]) -> Dict[str, str]
|
|
||||||
# A few of our few legacy endpoints need their
|
# A few of our few legacy endpoints need their
|
||||||
# individual parameters serialized as JSON.
|
# individual parameters serialized as JSON.
|
||||||
return {k: ujson.dumps(v) for k, v in raw_params.items()}
|
return {k: ujson.dumps(v) for k, v in raw_params.items()}
|
||||||
|
|
||||||
class StatsMock:
|
class StatsMock:
|
||||||
def __init__(self, settings):
|
def __init__(self, settings: Callable[..., Any]) -> None:
|
||||||
# type: (Callable[..., Any]) -> None
|
|
||||||
self.settings = settings
|
self.settings = settings
|
||||||
self.real_impl = statsd
|
self.real_impl = statsd
|
||||||
self.func_calls = [] # type: List[Tuple[str, Iterable[Any]]]
|
self.func_calls = [] # type: List[Tuple[str, Iterable[Any]]]
|
||||||
|
|
||||||
def __getattr__(self, name):
|
def __getattr__(self, name: str) -> Callable[..., Any]:
|
||||||
# type: (str) -> Callable[..., Any]
|
def f(*args: Any) -> None:
|
||||||
def f(*args):
|
|
||||||
# type: (*Any) -> None
|
|
||||||
with self.settings(STATSD_HOST=''):
|
with self.settings(STATSD_HOST=''):
|
||||||
getattr(self.real_impl, name)(*args)
|
getattr(self.real_impl, name)(*args)
|
||||||
self.func_calls.append((name, args))
|
self.func_calls.append((name, args))
|
||||||
@@ -35,8 +31,7 @@ class StatsMock:
|
|||||||
return f
|
return f
|
||||||
|
|
||||||
class TestReport(ZulipTestCase):
|
class TestReport(ZulipTestCase):
|
||||||
def test_send_time(self):
|
def test_send_time(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
email = self.example_email('hamlet')
|
email = self.example_email('hamlet')
|
||||||
self.login(email)
|
self.login(email)
|
||||||
|
|
||||||
@@ -62,8 +57,7 @@ class TestReport(ZulipTestCase):
|
|||||||
]
|
]
|
||||||
self.assertEqual(stats_mock.func_calls, expected_calls)
|
self.assertEqual(stats_mock.func_calls, expected_calls)
|
||||||
|
|
||||||
def test_narrow_time(self):
|
def test_narrow_time(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
email = self.example_email('hamlet')
|
email = self.example_email('hamlet')
|
||||||
self.login(email)
|
self.login(email)
|
||||||
|
|
||||||
@@ -85,8 +79,7 @@ class TestReport(ZulipTestCase):
|
|||||||
]
|
]
|
||||||
self.assertEqual(stats_mock.func_calls, expected_calls)
|
self.assertEqual(stats_mock.func_calls, expected_calls)
|
||||||
|
|
||||||
def test_unnarrow_time(self):
|
def test_unnarrow_time(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
email = self.example_email('hamlet')
|
email = self.example_email('hamlet')
|
||||||
self.login(email)
|
self.login(email)
|
||||||
|
|
||||||
@@ -107,8 +100,7 @@ class TestReport(ZulipTestCase):
|
|||||||
self.assertEqual(stats_mock.func_calls, expected_calls)
|
self.assertEqual(stats_mock.func_calls, expected_calls)
|
||||||
|
|
||||||
@override_settings(BROWSER_ERROR_REPORTING=True)
|
@override_settings(BROWSER_ERROR_REPORTING=True)
|
||||||
def test_report_error(self):
|
def test_report_error(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
email = self.example_email('hamlet')
|
email = self.example_email('hamlet')
|
||||||
self.login(email)
|
self.login(email)
|
||||||
|
|
||||||
|
|||||||
@@ -18,8 +18,9 @@ from zerver.lib.test_classes import ZulipTestCase
|
|||||||
|
|
||||||
class TestSessions(ZulipTestCase):
|
class TestSessions(ZulipTestCase):
|
||||||
|
|
||||||
def do_test_session(self, user, action, expected_result):
|
def do_test_session(self, user: Text,
|
||||||
# type: (Text, Callable[[], Any], bool) -> None
|
action: Callable[[], Any],
|
||||||
|
expected_result: bool) -> None:
|
||||||
self.login(user)
|
self.login(user)
|
||||||
self.assertIn('_auth_user_id', self.client.session)
|
self.assertIn('_auth_user_id', self.client.session)
|
||||||
action()
|
action()
|
||||||
@@ -29,8 +30,7 @@ class TestSessions(ZulipTestCase):
|
|||||||
else:
|
else:
|
||||||
self.assertIn('_auth_user_id', self.client.session)
|
self.assertIn('_auth_user_id', self.client.session)
|
||||||
|
|
||||||
def test_delete_session(self):
|
def test_delete_session(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
user_profile = self.example_user('hamlet')
|
user_profile = self.example_user('hamlet')
|
||||||
email = user_profile.email
|
email = user_profile.email
|
||||||
self.login(email)
|
self.login(email)
|
||||||
@@ -40,26 +40,22 @@ class TestSessions(ZulipTestCase):
|
|||||||
result = self.client_get("/")
|
result = self.client_get("/")
|
||||||
self.assertEqual('/login', result.url)
|
self.assertEqual('/login', result.url)
|
||||||
|
|
||||||
def test_delete_user_sessions(self):
|
def test_delete_user_sessions(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
user_profile = self.example_user('hamlet')
|
user_profile = self.example_user('hamlet')
|
||||||
email = user_profile.email
|
email = user_profile.email
|
||||||
self.do_test_session(str(email), lambda: delete_user_sessions(user_profile), True)
|
self.do_test_session(str(email), lambda: delete_user_sessions(user_profile), True)
|
||||||
self.do_test_session(str(self.example_email("othello")), lambda: delete_user_sessions(user_profile), False)
|
self.do_test_session(str(self.example_email("othello")), lambda: delete_user_sessions(user_profile), False)
|
||||||
|
|
||||||
def test_delete_realm_user_sessions(self):
|
def test_delete_realm_user_sessions(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
realm = get_realm('zulip')
|
realm = get_realm('zulip')
|
||||||
self.do_test_session(self.example_email("hamlet"), lambda: delete_realm_user_sessions(realm), True)
|
self.do_test_session(self.example_email("hamlet"), lambda: delete_realm_user_sessions(realm), True)
|
||||||
self.do_test_session(self.mit_email("sipbtest"), lambda: delete_realm_user_sessions(realm), False)
|
self.do_test_session(self.mit_email("sipbtest"), lambda: delete_realm_user_sessions(realm), False)
|
||||||
|
|
||||||
def test_delete_all_user_sessions(self):
|
def test_delete_all_user_sessions(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
self.do_test_session(self.example_email("hamlet"), lambda: delete_all_user_sessions(), True)
|
self.do_test_session(self.example_email("hamlet"), lambda: delete_all_user_sessions(), True)
|
||||||
self.do_test_session(self.mit_email("sipbtest"), lambda: delete_all_user_sessions(), True)
|
self.do_test_session(self.mit_email("sipbtest"), lambda: delete_all_user_sessions(), True)
|
||||||
|
|
||||||
def test_delete_all_deactivated_user_sessions(self):
|
def test_delete_all_deactivated_user_sessions(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
|
|
||||||
# Test that no exception is thrown with a logged-out session
|
# Test that no exception is thrown with a logged-out session
|
||||||
self.login(self.example_email("othello"))
|
self.login(self.example_email("othello"))
|
||||||
|
|||||||
@@ -12,14 +12,12 @@ from zerver.models import get_realm, get_user, UserProfile
|
|||||||
|
|
||||||
class ChangeSettingsTest(ZulipTestCase):
|
class ChangeSettingsTest(ZulipTestCase):
|
||||||
|
|
||||||
def check_well_formed_change_settings_response(self, result):
|
def check_well_formed_change_settings_response(self, result: Dict[str, Any]) -> None:
|
||||||
# type: (Dict[str, Any]) -> None
|
|
||||||
self.assertIn("full_name", result)
|
self.assertIn("full_name", result)
|
||||||
|
|
||||||
# DEPRECATED, to be deleted after all uses of check_for_toggle_param
|
# DEPRECATED, to be deleted after all uses of check_for_toggle_param
|
||||||
# are converted into check_for_toggle_param_patch.
|
# are converted into check_for_toggle_param_patch.
|
||||||
def check_for_toggle_param(self, pattern, param):
|
def check_for_toggle_param(self, pattern: str, param: str) -> None:
|
||||||
# type: (str, str) -> None
|
|
||||||
self.login(self.example_email("hamlet"))
|
self.login(self.example_email("hamlet"))
|
||||||
user_profile = self.example_user('hamlet')
|
user_profile = self.example_user('hamlet')
|
||||||
json_result = self.client_post(pattern,
|
json_result = self.client_post(pattern,
|
||||||
@@ -38,8 +36,7 @@ class ChangeSettingsTest(ZulipTestCase):
|
|||||||
|
|
||||||
# TODO: requires method consolidation, right now, there's no alternative
|
# TODO: requires method consolidation, right now, there's no alternative
|
||||||
# for check_for_toggle_param for PATCH.
|
# for check_for_toggle_param for PATCH.
|
||||||
def check_for_toggle_param_patch(self, pattern, param):
|
def check_for_toggle_param_patch(self, pattern: str, param: str) -> None:
|
||||||
# type: (str, str) -> None
|
|
||||||
self.login(self.example_email("hamlet"))
|
self.login(self.example_email("hamlet"))
|
||||||
user_profile = self.example_user('hamlet')
|
user_profile = self.example_user('hamlet')
|
||||||
json_result = self.client_patch(pattern,
|
json_result = self.client_patch(pattern,
|
||||||
@@ -56,8 +53,7 @@ class ChangeSettingsTest(ZulipTestCase):
|
|||||||
user_profile = self.example_user('hamlet')
|
user_profile = self.example_user('hamlet')
|
||||||
self.assertEqual(getattr(user_profile, param), False)
|
self.assertEqual(getattr(user_profile, param), False)
|
||||||
|
|
||||||
def test_successful_change_settings(self):
|
def test_successful_change_settings(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
"""
|
"""
|
||||||
A call to /json/settings with valid parameters changes the user's
|
A call to /json/settings with valid parameters changes the user's
|
||||||
settings correctly and returns correct values.
|
settings correctly and returns correct values.
|
||||||
@@ -81,8 +77,7 @@ class ChangeSettingsTest(ZulipTestCase):
|
|||||||
user_profile = self.example_user('hamlet')
|
user_profile = self.example_user('hamlet')
|
||||||
self.assertEqual(get_session_dict_user(self.client.session), user_profile.id)
|
self.assertEqual(get_session_dict_user(self.client.session), user_profile.id)
|
||||||
|
|
||||||
def test_illegal_name_changes(self):
|
def test_illegal_name_changes(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
user = self.example_user('hamlet')
|
user = self.example_user('hamlet')
|
||||||
email = user.email
|
email = user.email
|
||||||
self.login(email)
|
self.login(email)
|
||||||
@@ -110,8 +105,7 @@ class ChangeSettingsTest(ZulipTestCase):
|
|||||||
dict(full_name='x'))
|
dict(full_name='x'))
|
||||||
self.assert_json_error(json_result, 'Name too short!')
|
self.assert_json_error(json_result, 'Name too short!')
|
||||||
|
|
||||||
def test_illegal_characters_in_name_changes(self):
|
def test_illegal_characters_in_name_changes(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
email = self.example_email("hamlet")
|
email = self.example_email("hamlet")
|
||||||
self.login(email)
|
self.login(email)
|
||||||
|
|
||||||
@@ -121,30 +115,25 @@ class ChangeSettingsTest(ZulipTestCase):
|
|||||||
self.assert_json_error(json_result, 'Invalid characters in name!')
|
self.assert_json_error(json_result, 'Invalid characters in name!')
|
||||||
|
|
||||||
# This is basically a don't-explode test.
|
# This is basically a don't-explode test.
|
||||||
def test_notify_settings(self):
|
def test_notify_settings(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
for notification_setting in UserProfile.notification_setting_types:
|
for notification_setting in UserProfile.notification_setting_types:
|
||||||
self.check_for_toggle_param_patch("/json/settings/notifications",
|
self.check_for_toggle_param_patch("/json/settings/notifications",
|
||||||
notification_setting)
|
notification_setting)
|
||||||
|
|
||||||
def test_ui_settings(self):
|
def test_ui_settings(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
self.check_for_toggle_param_patch("/json/settings/ui", "autoscroll_forever")
|
self.check_for_toggle_param_patch("/json/settings/ui", "autoscroll_forever")
|
||||||
self.check_for_toggle_param_patch("/json/settings/ui", "default_desktop_notifications")
|
self.check_for_toggle_param_patch("/json/settings/ui", "default_desktop_notifications")
|
||||||
|
|
||||||
def test_toggling_boolean_user_display_settings(self):
|
def test_toggling_boolean_user_display_settings(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
"""Test updating each boolean setting in UserProfile property_types"""
|
"""Test updating each boolean setting in UserProfile property_types"""
|
||||||
boolean_settings = (s for s in UserProfile.property_types if UserProfile.property_types[s] is bool)
|
boolean_settings = (s for s in UserProfile.property_types if UserProfile.property_types[s] is bool)
|
||||||
for display_setting in boolean_settings:
|
for display_setting in boolean_settings:
|
||||||
self.check_for_toggle_param_patch("/json/settings/display", display_setting)
|
self.check_for_toggle_param_patch("/json/settings/display", display_setting)
|
||||||
|
|
||||||
def test_enter_sends_setting(self):
|
def test_enter_sends_setting(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
self.check_for_toggle_param('/json/users/me/enter-sends', "enter_sends")
|
self.check_for_toggle_param('/json/users/me/enter-sends', "enter_sends")
|
||||||
|
|
||||||
def test_mismatching_passwords(self):
|
def test_mismatching_passwords(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
"""
|
"""
|
||||||
new_password and confirm_password must match
|
new_password and confirm_password must match
|
||||||
"""
|
"""
|
||||||
@@ -158,8 +147,7 @@ class ChangeSettingsTest(ZulipTestCase):
|
|||||||
self.assert_json_error(result,
|
self.assert_json_error(result,
|
||||||
"New password must match confirmation password!")
|
"New password must match confirmation password!")
|
||||||
|
|
||||||
def test_wrong_old_password(self):
|
def test_wrong_old_password(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
"""
|
"""
|
||||||
new_password and confirm_password must match
|
new_password and confirm_password must match
|
||||||
"""
|
"""
|
||||||
@@ -173,8 +161,7 @@ class ChangeSettingsTest(ZulipTestCase):
|
|||||||
))
|
))
|
||||||
self.assert_json_error(result, "Wrong password!")
|
self.assert_json_error(result, "Wrong password!")
|
||||||
|
|
||||||
def test_changing_nothing_returns_error(self):
|
def test_changing_nothing_returns_error(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
"""
|
"""
|
||||||
We need to supply at least one non-empty parameter
|
We need to supply at least one non-empty parameter
|
||||||
to this API, or it should fail. (Eventually, we should
|
to this API, or it should fail. (Eventually, we should
|
||||||
@@ -185,8 +172,7 @@ class ChangeSettingsTest(ZulipTestCase):
|
|||||||
dict(old_password='ignored',))
|
dict(old_password='ignored',))
|
||||||
self.assert_json_error(result, "No new data supplied")
|
self.assert_json_error(result, "No new data supplied")
|
||||||
|
|
||||||
def do_test_change_user_display_setting(self, setting_name):
|
def do_test_change_user_display_setting(self, setting_name: str) -> None:
|
||||||
# type: (str) -> None
|
|
||||||
|
|
||||||
test_changes = dict(
|
test_changes = dict(
|
||||||
default_language = 'de',
|
default_language = 'de',
|
||||||
@@ -219,8 +205,7 @@ class ChangeSettingsTest(ZulipTestCase):
|
|||||||
user_profile = self.example_user('hamlet')
|
user_profile = self.example_user('hamlet')
|
||||||
self.assertNotEqual(getattr(user_profile, setting_name), invalid_value)
|
self.assertNotEqual(getattr(user_profile, setting_name), invalid_value)
|
||||||
|
|
||||||
def test_change_user_display_setting(self):
|
def test_change_user_display_setting(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
"""Test updating each non-boolean setting in UserProfile property_types"""
|
"""Test updating each non-boolean setting in UserProfile property_types"""
|
||||||
user_settings = (s for s in UserProfile.property_types if UserProfile.property_types[s] is not bool)
|
user_settings = (s for s in UserProfile.property_types if UserProfile.property_types[s] is not bool)
|
||||||
for setting in user_settings:
|
for setting in user_settings:
|
||||||
@@ -228,8 +213,7 @@ class ChangeSettingsTest(ZulipTestCase):
|
|||||||
|
|
||||||
|
|
||||||
class UserChangesTest(ZulipTestCase):
|
class UserChangesTest(ZulipTestCase):
|
||||||
def test_update_api_key(self):
|
def test_update_api_key(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
user = self.example_user('hamlet')
|
user = self.example_user('hamlet')
|
||||||
email = user.email
|
email = user.email
|
||||||
self.login(email)
|
self.login(email)
|
||||||
|
|||||||
@@ -15,8 +15,7 @@ from zerver.models import (
|
|||||||
|
|
||||||
class UserSoftDeactivationTests(ZulipTestCase):
|
class UserSoftDeactivationTests(ZulipTestCase):
|
||||||
|
|
||||||
def test_do_soft_deactivate_user(self):
|
def test_do_soft_deactivate_user(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
user = self.example_user('hamlet')
|
user = self.example_user('hamlet')
|
||||||
self.assertFalse(user.long_term_idle)
|
self.assertFalse(user.long_term_idle)
|
||||||
|
|
||||||
@@ -25,8 +24,7 @@ class UserSoftDeactivationTests(ZulipTestCase):
|
|||||||
user.refresh_from_db()
|
user.refresh_from_db()
|
||||||
self.assertTrue(user.long_term_idle)
|
self.assertTrue(user.long_term_idle)
|
||||||
|
|
||||||
def test_do_soft_deactivate_users(self):
|
def test_do_soft_deactivate_users(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
users = [
|
users = [
|
||||||
self.example_user('hamlet'),
|
self.example_user('hamlet'),
|
||||||
self.example_user('iago'),
|
self.example_user('iago'),
|
||||||
@@ -45,8 +43,7 @@ class UserSoftDeactivationTests(ZulipTestCase):
|
|||||||
user.refresh_from_db()
|
user.refresh_from_db()
|
||||||
self.assertTrue(user.long_term_idle)
|
self.assertTrue(user.long_term_idle)
|
||||||
|
|
||||||
def test_get_users_for_soft_deactivation(self):
|
def test_get_users_for_soft_deactivation(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
users = [
|
users = [
|
||||||
self.example_user('hamlet'),
|
self.example_user('hamlet'),
|
||||||
self.example_user('iago'),
|
self.example_user('iago'),
|
||||||
@@ -75,8 +72,7 @@ class UserSoftDeactivationTests(ZulipTestCase):
|
|||||||
for user in users_to_deactivate:
|
for user in users_to_deactivate:
|
||||||
self.assertTrue(user in users)
|
self.assertTrue(user in users)
|
||||||
|
|
||||||
def test_do_soft_activate_users(self):
|
def test_do_soft_activate_users(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
users = [
|
users = [
|
||||||
self.example_user('hamlet'),
|
self.example_user('hamlet'),
|
||||||
self.example_user('iago'),
|
self.example_user('iago'),
|
||||||
|
|||||||
@@ -8,11 +8,9 @@ from zerver.lib.subdomains import get_subdomain
|
|||||||
from zerver.models import Realm
|
from zerver.models import Realm
|
||||||
|
|
||||||
class SubdomainsTest(TestCase):
|
class SubdomainsTest(TestCase):
|
||||||
def test_get_subdomain(self):
|
def test_get_subdomain(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
|
|
||||||
def request_mock(host):
|
def request_mock(host: str) -> Any:
|
||||||
# type: (str) -> Any
|
|
||||||
request = mock.Mock(spec=['get_host'])
|
request = mock.Mock(spec=['get_host'])
|
||||||
request.attach_mock(mock.Mock(return_value=host), 'get_host')
|
request.attach_mock(mock.Mock(return_value=host), 'get_host')
|
||||||
return request
|
return request
|
||||||
|
|||||||
@@ -11,8 +11,7 @@ from dateutil import parser
|
|||||||
import pytz
|
import pytz
|
||||||
|
|
||||||
class TestTimestamp(ZulipTestCase):
|
class TestTimestamp(ZulipTestCase):
|
||||||
def test_datetime_and_timestamp_conversions(self):
|
def test_datetime_and_timestamp_conversions(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
timestamp = 1483228800
|
timestamp = 1483228800
|
||||||
for dt in [
|
for dt in [
|
||||||
parser.parse('2017-01-01 00:00:00.123 UTC'),
|
parser.parse('2017-01-01 00:00:00.123 UTC'),
|
||||||
@@ -27,8 +26,7 @@ class TestTimestamp(ZulipTestCase):
|
|||||||
with self.assertRaises(TimezoneNotUTCException):
|
with self.assertRaises(TimezoneNotUTCException):
|
||||||
datetime_to_timestamp(dt)
|
datetime_to_timestamp(dt)
|
||||||
|
|
||||||
def test_convert_to_UTC(self):
|
def test_convert_to_UTC(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
utc_datetime = parser.parse('2017-01-01 00:00:00.123 UTC')
|
utc_datetime = parser.parse('2017-01-01 00:00:00.123 UTC')
|
||||||
for dt in [
|
for dt in [
|
||||||
parser.parse('2017-01-01 00:00:00.123').replace(tzinfo=timezone_utc),
|
parser.parse('2017-01-01 00:00:00.123').replace(tzinfo=timezone_utc),
|
||||||
@@ -36,8 +34,7 @@ class TestTimestamp(ZulipTestCase):
|
|||||||
parser.parse('2017-01-01 05:00:00.123+05')]:
|
parser.parse('2017-01-01 05:00:00.123+05')]:
|
||||||
self.assertEqual(convert_to_UTC(dt), utc_datetime)
|
self.assertEqual(convert_to_UTC(dt), utc_datetime)
|
||||||
|
|
||||||
def test_enforce_UTC(self):
|
def test_enforce_UTC(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
non_utc_datetime = parser.parse('2017-01-01 00:00:00.123')
|
non_utc_datetime = parser.parse('2017-01-01 00:00:00.123')
|
||||||
for function in [floor_to_hour, floor_to_day, ceiling_to_hour, ceiling_to_hour]:
|
for function in [floor_to_hour, floor_to_day, ceiling_to_hour, ceiling_to_hour]:
|
||||||
with self.assertRaises(TimezoneNotUTCException):
|
with self.assertRaises(TimezoneNotUTCException):
|
||||||
|
|||||||
@@ -8,8 +8,7 @@ from typing import Any, Dict
|
|||||||
import ujson
|
import ujson
|
||||||
|
|
||||||
class TutorialTests(ZulipTestCase):
|
class TutorialTests(ZulipTestCase):
|
||||||
def setUp(self):
|
def setUp(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
# This emulates the welcome message sent by the welcome bot to hamlet@zulip.com
|
# This emulates the welcome message sent by the welcome bot to hamlet@zulip.com
|
||||||
# This is only a quick fix - ideally, we would have this message sent by the initialization
|
# This is only a quick fix - ideally, we would have this message sent by the initialization
|
||||||
# code in populate_db.py
|
# code in populate_db.py
|
||||||
@@ -18,8 +17,7 @@ class TutorialTests(ZulipTestCase):
|
|||||||
content = 'Shortened welcome message.'
|
content = 'Shortened welcome message.'
|
||||||
self.send_personal_message(bot_email, user_email, content)
|
self.send_personal_message(bot_email, user_email, content)
|
||||||
|
|
||||||
def test_tutorial_status(self):
|
def test_tutorial_status(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
email = self.example_email('hamlet')
|
email = self.example_email('hamlet')
|
||||||
self.login(email)
|
self.login(email)
|
||||||
|
|
||||||
@@ -34,8 +32,7 @@ class TutorialTests(ZulipTestCase):
|
|||||||
user = self.example_user('hamlet')
|
user = self.example_user('hamlet')
|
||||||
self.assertEqual(user.tutorial_status, expected_db_status)
|
self.assertEqual(user.tutorial_status, expected_db_status)
|
||||||
|
|
||||||
def test_single_response_to_pm(self):
|
def test_single_response_to_pm(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
realm = get_realm('zulip')
|
realm = get_realm('zulip')
|
||||||
user_email = 'hamlet@zulip.com'
|
user_email = 'hamlet@zulip.com'
|
||||||
bot_email = 'welcome-bot@zulip.com'
|
bot_email = 'welcome-bot@zulip.com'
|
||||||
@@ -52,8 +49,7 @@ class TutorialTests(ZulipTestCase):
|
|||||||
self.send_personal_message(user_email, bot_email, content)
|
self.send_personal_message(user_email, bot_email, content)
|
||||||
self.assertEqual(message_stream_count(user), user_messages+1)
|
self.assertEqual(message_stream_count(user), user_messages+1)
|
||||||
|
|
||||||
def test_no_response_to_group_pm(self):
|
def test_no_response_to_group_pm(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
realm = get_realm('zulip') # Assume realm is always 'zulip'
|
realm = get_realm('zulip') # Assume realm is always 'zulip'
|
||||||
user1_email = self.example_email('hamlet')
|
user1_email = self.example_email('hamlet')
|
||||||
user2_email = self.example_email('cordelia')
|
user2_email = self.example_email('cordelia')
|
||||||
|
|||||||
@@ -9,27 +9,22 @@ from typing import Any, Callable, Dict, Iterable, Tuple, TypeVar, List
|
|||||||
|
|
||||||
T = TypeVar('T')
|
T = TypeVar('T')
|
||||||
|
|
||||||
def add(x=0, y=0):
|
def add(x: Any=0, y: Any=0) -> Any:
|
||||||
# type: (Any, Any) -> Any
|
|
||||||
return x + y
|
return x + y
|
||||||
|
|
||||||
def to_dict(v=[]):
|
def to_dict(v: Iterable[Tuple[Any, Any]]=[]) -> Dict[Any, Any]:
|
||||||
# type: (Iterable[Tuple[Any, Any]]) -> Dict[Any, Any]
|
|
||||||
return dict(v)
|
return dict(v)
|
||||||
|
|
||||||
class TypesPrintTest(TestCase):
|
class TypesPrintTest(TestCase):
|
||||||
|
|
||||||
# These 2 methods are needed to run tests with our custom test-runner
|
# These 2 methods are needed to run tests with our custom test-runner
|
||||||
def _pre_setup(self):
|
def _pre_setup(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def _post_teardown(self):
|
def _post_teardown(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def check_signature(self, signature, retval, func, *args, **kwargs):
|
def check_signature(self, signature: str, retval: T, func: Callable[..., T], *args: Any, **kwargs: Any) -> None:
|
||||||
# type: (str, T, Callable[..., T], *Any, **Any) -> None
|
|
||||||
"""
|
"""
|
||||||
Checks if print_types outputs `signature` when func is called with *args and **kwargs.
|
Checks if print_types outputs `signature` when func is called with *args and **kwargs.
|
||||||
Do not decorate func with print_types before passing into this function.
|
Do not decorate func with print_types before passing into this function.
|
||||||
@@ -43,16 +38,13 @@ class TypesPrintTest(TestCase):
|
|||||||
finally:
|
finally:
|
||||||
sys.stdout = original_stdout
|
sys.stdout = original_stdout
|
||||||
|
|
||||||
def test_empty(self):
|
def test_empty(self) -> None:
|
||||||
# type: () -> None
|
def empty_func() -> None:
|
||||||
def empty_func():
|
|
||||||
# type: () -> None
|
|
||||||
pass
|
pass
|
||||||
self.check_signature("empty_func() -> None", None, empty_func)
|
self.check_signature("empty_func() -> None", None, empty_func)
|
||||||
self.check_signature("<lambda>() -> None", None, (lambda: None)) # type: ignore # https://github.com/python/mypy/issues/1932
|
self.check_signature("<lambda>() -> None", None, (lambda: None)) # type: ignore # https://github.com/python/mypy/issues/1932
|
||||||
|
|
||||||
def test_basic(self):
|
def test_basic(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
self.check_signature("add(float, int) -> float",
|
self.check_signature("add(float, int) -> float",
|
||||||
5.0, add, 2.0, 3)
|
5.0, add, 2.0, 3)
|
||||||
self.check_signature("add(float, y=int) -> float",
|
self.check_signature("add(float, y=int) -> float",
|
||||||
@@ -60,8 +52,7 @@ class TypesPrintTest(TestCase):
|
|||||||
self.check_signature("add(x=int) -> int", 2, add, x=2)
|
self.check_signature("add(x=int) -> int", 2, add, x=2)
|
||||||
self.check_signature("add() -> int", 0, add)
|
self.check_signature("add() -> int", 0, add)
|
||||||
|
|
||||||
def test_list(self):
|
def test_list(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
self.check_signature("add([], [str]) -> [str]",
|
self.check_signature("add([], [str]) -> [str]",
|
||||||
['two'], add, [], ['two'])
|
['two'], add, [], ['two'])
|
||||||
self.check_signature("add([int], [str]) -> [int, ...]",
|
self.check_signature("add([int], [str]) -> [int, ...]",
|
||||||
@@ -69,8 +60,7 @@ class TypesPrintTest(TestCase):
|
|||||||
self.check_signature("add([int, ...], y=[]) -> [int, ...]",
|
self.check_signature("add([int, ...], y=[]) -> [int, ...]",
|
||||||
[2, 'two'], add, [2, 'two'], y=[])
|
[2, 'two'], add, [2, 'two'], y=[])
|
||||||
|
|
||||||
def test_dict(self):
|
def test_dict(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
self.check_signature("to_dict() -> {}", {}, to_dict)
|
self.check_signature("to_dict() -> {}", {}, to_dict)
|
||||||
self.check_signature("to_dict([(int, str)]) -> {int: str}",
|
self.check_signature("to_dict([(int, str)]) -> {int: str}",
|
||||||
{2: 'two'}, to_dict, [(2, 'two')])
|
{2: 'two'}, to_dict, [(2, 'two')])
|
||||||
@@ -79,8 +69,7 @@ class TypesPrintTest(TestCase):
|
|||||||
self.check_signature("to_dict([(int, str), ...]) -> {int: str, ...}",
|
self.check_signature("to_dict([(int, str), ...]) -> {int: str, ...}",
|
||||||
{1: 'one', 2: 'two'}, to_dict, [(1, 'one'), (2, 'two')])
|
{1: 'one', 2: 'two'}, to_dict, [(1, 'one'), (2, 'two')])
|
||||||
|
|
||||||
def test_tuple(self):
|
def test_tuple(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
self.check_signature("add((), ()) -> ()",
|
self.check_signature("add((), ()) -> ()",
|
||||||
(), add, (), ())
|
(), add, (), ())
|
||||||
self.check_signature("add((int,), (str,)) -> (int, str)",
|
self.check_signature("add((int,), (str,)) -> (int, str)",
|
||||||
@@ -88,8 +77,7 @@ class TypesPrintTest(TestCase):
|
|||||||
self.check_signature("add(((),), ((),)) -> ((), ())",
|
self.check_signature("add(((),), ((),)) -> ((), ())",
|
||||||
((), ()), add, ((),), ((),))
|
((), ()), add, ((),), ((),))
|
||||||
|
|
||||||
def test_class(self):
|
def test_class(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
class A:
|
class A:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@@ -99,8 +87,7 @@ class TypesPrintTest(TestCase):
|
|||||||
self.check_signature("<lambda>(A) -> str", 'A', (lambda x: x.__class__.__name__), A())
|
self.check_signature("<lambda>(A) -> str", 'A', (lambda x: x.__class__.__name__), A())
|
||||||
self.check_signature("<lambda>(B) -> int", 5, (lambda x: len(x)), B("hello"))
|
self.check_signature("<lambda>(B) -> int", 5, (lambda x: len(x)), B("hello"))
|
||||||
|
|
||||||
def test_sequence(self):
|
def test_sequence(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
class A(List[Any]):
|
class A(List[Any]):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@@ -114,13 +101,11 @@ class TypesPrintTest(TestCase):
|
|||||||
self.check_signature("add(A([int, ...]), y=B([])) -> [int, ...]",
|
self.check_signature("add(A([int, ...]), y=B([])) -> [int, ...]",
|
||||||
[2, 'two'], add, A([2, 'two']), y=B([]))
|
[2, 'two'], add, A([2, 'two']), y=B([]))
|
||||||
|
|
||||||
def test_mapping(self):
|
def test_mapping(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
class A(Dict[Any, Any]):
|
class A(Dict[Any, Any]):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def to_A(v=[]):
|
def to_A(v: Iterable[Tuple[Any, Any]]=[]) -> A:
|
||||||
# type: (Iterable[Tuple[Any, Any]]) -> A
|
|
||||||
return A(v)
|
return A(v)
|
||||||
|
|
||||||
self.check_signature("to_A() -> A([])", A(()), to_A)
|
self.check_signature("to_A() -> A([])", A(()), to_A)
|
||||||
|
|||||||
@@ -11,8 +11,7 @@ from zerver.lib.test_classes import (
|
|||||||
from zerver.models import get_realm, get_user
|
from zerver.models import get_realm, get_user
|
||||||
|
|
||||||
class TypingNotificationOperatorTest(ZulipTestCase):
|
class TypingNotificationOperatorTest(ZulipTestCase):
|
||||||
def test_missing_parameter(self):
|
def test_missing_parameter(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
"""
|
"""
|
||||||
Sending typing notification without op parameter fails
|
Sending typing notification without op parameter fails
|
||||||
"""
|
"""
|
||||||
@@ -22,8 +21,7 @@ class TypingNotificationOperatorTest(ZulipTestCase):
|
|||||||
**self.api_auth(sender))
|
**self.api_auth(sender))
|
||||||
self.assert_json_error(result, 'Missing \'op\' argument')
|
self.assert_json_error(result, 'Missing \'op\' argument')
|
||||||
|
|
||||||
def test_invalid_parameter(self):
|
def test_invalid_parameter(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
"""
|
"""
|
||||||
Sending typing notification with invalid value for op parameter fails
|
Sending typing notification with invalid value for op parameter fails
|
||||||
"""
|
"""
|
||||||
@@ -34,8 +32,7 @@ class TypingNotificationOperatorTest(ZulipTestCase):
|
|||||||
self.assert_json_error(result, 'Invalid \'op\' value (should be start or stop)')
|
self.assert_json_error(result, 'Invalid \'op\' value (should be start or stop)')
|
||||||
|
|
||||||
class TypingNotificationRecipientsTest(ZulipTestCase):
|
class TypingNotificationRecipientsTest(ZulipTestCase):
|
||||||
def test_missing_recipient(self):
|
def test_missing_recipient(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
"""
|
"""
|
||||||
Sending typing notification without recipient fails
|
Sending typing notification without recipient fails
|
||||||
"""
|
"""
|
||||||
@@ -44,8 +41,7 @@ class TypingNotificationRecipientsTest(ZulipTestCase):
|
|||||||
**self.api_auth(sender))
|
**self.api_auth(sender))
|
||||||
self.assert_json_error(result, 'Missing parameter: \'to\' (recipient)')
|
self.assert_json_error(result, 'Missing parameter: \'to\' (recipient)')
|
||||||
|
|
||||||
def test_invalid_recipient(self):
|
def test_invalid_recipient(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
"""
|
"""
|
||||||
Sending typing notification to invalid recipient fails
|
Sending typing notification to invalid recipient fails
|
||||||
"""
|
"""
|
||||||
@@ -55,8 +51,7 @@ class TypingNotificationRecipientsTest(ZulipTestCase):
|
|||||||
**self.api_auth(sender))
|
**self.api_auth(sender))
|
||||||
self.assert_json_error(result, 'Invalid email \'' + invalid + '\'')
|
self.assert_json_error(result, 'Invalid email \'' + invalid + '\'')
|
||||||
|
|
||||||
def test_single_recipient(self):
|
def test_single_recipient(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
"""
|
"""
|
||||||
Sending typing notification to a single recipient is successful
|
Sending typing notification to a single recipient is successful
|
||||||
"""
|
"""
|
||||||
@@ -86,8 +81,7 @@ class TypingNotificationRecipientsTest(ZulipTestCase):
|
|||||||
self.assertEqual(event['type'], 'typing')
|
self.assertEqual(event['type'], 'typing')
|
||||||
self.assertEqual(event['op'], 'start')
|
self.assertEqual(event['op'], 'start')
|
||||||
|
|
||||||
def test_multiple_recipients(self):
|
def test_multiple_recipients(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
"""
|
"""
|
||||||
Sending typing notification to a single recipient is successful
|
Sending typing notification to a single recipient is successful
|
||||||
"""
|
"""
|
||||||
@@ -117,8 +111,7 @@ class TypingNotificationRecipientsTest(ZulipTestCase):
|
|||||||
self.assertEqual(event['op'], 'start')
|
self.assertEqual(event['op'], 'start')
|
||||||
|
|
||||||
class TypingStartedNotificationTest(ZulipTestCase):
|
class TypingStartedNotificationTest(ZulipTestCase):
|
||||||
def test_send_notification_to_self_event(self):
|
def test_send_notification_to_self_event(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
"""
|
"""
|
||||||
Sending typing notification to yourself
|
Sending typing notification to yourself
|
||||||
is successful.
|
is successful.
|
||||||
@@ -147,8 +140,7 @@ class TypingStartedNotificationTest(ZulipTestCase):
|
|||||||
self.assertEqual(event['type'], 'typing')
|
self.assertEqual(event['type'], 'typing')
|
||||||
self.assertEqual(event['op'], 'start')
|
self.assertEqual(event['op'], 'start')
|
||||||
|
|
||||||
def test_send_notification_to_another_user_event(self):
|
def test_send_notification_to_another_user_event(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
"""
|
"""
|
||||||
Sending typing notification to another user
|
Sending typing notification to another user
|
||||||
is successful.
|
is successful.
|
||||||
@@ -180,8 +172,7 @@ class TypingStartedNotificationTest(ZulipTestCase):
|
|||||||
self.assertEqual(event['op'], 'start')
|
self.assertEqual(event['op'], 'start')
|
||||||
|
|
||||||
class StoppedTypingNotificationTest(ZulipTestCase):
|
class StoppedTypingNotificationTest(ZulipTestCase):
|
||||||
def test_send_notification_to_self_event(self):
|
def test_send_notification_to_self_event(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
"""
|
"""
|
||||||
Sending stopped typing notification to yourself
|
Sending stopped typing notification to yourself
|
||||||
is successful.
|
is successful.
|
||||||
@@ -211,8 +202,7 @@ class StoppedTypingNotificationTest(ZulipTestCase):
|
|||||||
self.assertEqual(event['type'], 'typing')
|
self.assertEqual(event['type'], 'typing')
|
||||||
self.assertEqual(event['op'], 'stop')
|
self.assertEqual(event['op'], 'stop')
|
||||||
|
|
||||||
def test_send_notification_to_another_user_event(self):
|
def test_send_notification_to_another_user_event(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
"""
|
"""
|
||||||
Sending stopped typing notification to another user
|
Sending stopped typing notification to another user
|
||||||
is successful.
|
is successful.
|
||||||
|
|||||||
@@ -34,8 +34,7 @@ import ujson
|
|||||||
|
|
||||||
class PointerTest(ZulipTestCase):
|
class PointerTest(ZulipTestCase):
|
||||||
|
|
||||||
def test_update_pointer(self):
|
def test_update_pointer(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
"""
|
"""
|
||||||
Posting a pointer to /update (in the form {"pointer": pointer}) changes
|
Posting a pointer to /update (in the form {"pointer": pointer}) changes
|
||||||
the pointer we store for your UserProfile.
|
the pointer we store for your UserProfile.
|
||||||
@@ -47,8 +46,7 @@ class PointerTest(ZulipTestCase):
|
|||||||
self.assert_json_success(result)
|
self.assert_json_success(result)
|
||||||
self.assertEqual(self.example_user('hamlet').pointer, msg_id)
|
self.assertEqual(self.example_user('hamlet').pointer, msg_id)
|
||||||
|
|
||||||
def test_api_update_pointer(self):
|
def test_api_update_pointer(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
"""
|
"""
|
||||||
Same as above, but for the API view
|
Same as above, but for the API view
|
||||||
"""
|
"""
|
||||||
@@ -61,8 +59,7 @@ class PointerTest(ZulipTestCase):
|
|||||||
self.assert_json_success(result)
|
self.assert_json_success(result)
|
||||||
self.assertEqual(get_user(email, user.realm).pointer, msg_id)
|
self.assertEqual(get_user(email, user.realm).pointer, msg_id)
|
||||||
|
|
||||||
def test_missing_pointer(self):
|
def test_missing_pointer(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
"""
|
"""
|
||||||
Posting json to /json/users/me/pointer which does not contain a pointer key/value pair
|
Posting json to /json/users/me/pointer which does not contain a pointer key/value pair
|
||||||
returns a 400 and error message.
|
returns a 400 and error message.
|
||||||
@@ -73,8 +70,7 @@ class PointerTest(ZulipTestCase):
|
|||||||
self.assert_json_error(result, "Missing 'pointer' argument")
|
self.assert_json_error(result, "Missing 'pointer' argument")
|
||||||
self.assertEqual(self.example_user('hamlet').pointer, -1)
|
self.assertEqual(self.example_user('hamlet').pointer, -1)
|
||||||
|
|
||||||
def test_invalid_pointer(self):
|
def test_invalid_pointer(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
"""
|
"""
|
||||||
Posting json to /json/users/me/pointer with an invalid pointer returns a 400 and error
|
Posting json to /json/users/me/pointer with an invalid pointer returns a 400 and error
|
||||||
message.
|
message.
|
||||||
@@ -85,8 +81,7 @@ class PointerTest(ZulipTestCase):
|
|||||||
self.assert_json_error(result, "Bad value for 'pointer': foo")
|
self.assert_json_error(result, "Bad value for 'pointer': foo")
|
||||||
self.assertEqual(self.example_user('hamlet').pointer, -1)
|
self.assertEqual(self.example_user('hamlet').pointer, -1)
|
||||||
|
|
||||||
def test_pointer_out_of_range(self):
|
def test_pointer_out_of_range(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
"""
|
"""
|
||||||
Posting json to /json/users/me/pointer with an out of range (< 0) pointer returns a 400
|
Posting json to /json/users/me/pointer with an out of range (< 0) pointer returns a 400
|
||||||
and error message.
|
and error message.
|
||||||
@@ -97,8 +92,7 @@ class PointerTest(ZulipTestCase):
|
|||||||
self.assert_json_error(result, "Bad value for 'pointer': -2")
|
self.assert_json_error(result, "Bad value for 'pointer': -2")
|
||||||
self.assertEqual(self.example_user('hamlet').pointer, -1)
|
self.assertEqual(self.example_user('hamlet').pointer, -1)
|
||||||
|
|
||||||
def test_use_first_unread_anchor_interaction_with_pointer(self):
|
def test_use_first_unread_anchor_interaction_with_pointer(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
"""
|
"""
|
||||||
Getting old messages (a get request to /json/messages) should never
|
Getting old messages (a get request to /json/messages) should never
|
||||||
return an unread message older than the current pointer, when there's
|
return an unread message older than the current pointer, when there's
|
||||||
@@ -177,8 +171,7 @@ class PointerTest(ZulipTestCase):
|
|||||||
self.assertEqual(messages[0]['id'], new_message_id)
|
self.assertEqual(messages[0]['id'], new_message_id)
|
||||||
|
|
||||||
class UnreadCountTests(ZulipTestCase):
|
class UnreadCountTests(ZulipTestCase):
|
||||||
def setUp(self):
|
def setUp(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
self.unread_msg_ids = [
|
self.unread_msg_ids = [
|
||||||
self.send_personal_message(
|
self.send_personal_message(
|
||||||
self.example_email("iago"), self.example_email("hamlet"), "hello"),
|
self.example_email("iago"), self.example_email("hamlet"), "hello"),
|
||||||
@@ -186,8 +179,7 @@ class UnreadCountTests(ZulipTestCase):
|
|||||||
self.example_email("iago"), self.example_email("hamlet"), "hello2")]
|
self.example_email("iago"), self.example_email("hamlet"), "hello2")]
|
||||||
|
|
||||||
# Sending a new message results in unread UserMessages being created
|
# Sending a new message results in unread UserMessages being created
|
||||||
def test_new_message(self):
|
def test_new_message(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
self.login(self.example_email("hamlet"))
|
self.login(self.example_email("hamlet"))
|
||||||
content = "Test message for unset read bit"
|
content = "Test message for unset read bit"
|
||||||
last_msg = self.send_stream_message(self.example_email("hamlet"), "Verona", content)
|
last_msg = self.send_stream_message(self.example_email("hamlet"), "Verona", content)
|
||||||
@@ -198,8 +190,7 @@ class UnreadCountTests(ZulipTestCase):
|
|||||||
if um.user_profile.email != self.example_email("hamlet"):
|
if um.user_profile.email != self.example_email("hamlet"):
|
||||||
self.assertFalse(um.flags.read)
|
self.assertFalse(um.flags.read)
|
||||||
|
|
||||||
def test_update_flags(self):
|
def test_update_flags(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
self.login(self.example_email("hamlet"))
|
self.login(self.example_email("hamlet"))
|
||||||
|
|
||||||
result = self.client_post("/json/messages/flags",
|
result = self.client_post("/json/messages/flags",
|
||||||
@@ -228,8 +219,7 @@ class UnreadCountTests(ZulipTestCase):
|
|||||||
elif msg['id'] == self.unread_msg_ids[1]:
|
elif msg['id'] == self.unread_msg_ids[1]:
|
||||||
self.assertEqual(msg['flags'], [])
|
self.assertEqual(msg['flags'], [])
|
||||||
|
|
||||||
def test_mark_all_in_stream_read(self):
|
def test_mark_all_in_stream_read(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
self.login(self.example_email("hamlet"))
|
self.login(self.example_email("hamlet"))
|
||||||
user_profile = self.example_user('hamlet')
|
user_profile = self.example_user('hamlet')
|
||||||
stream = self.subscribe(user_profile, "test_stream")
|
stream = self.subscribe(user_profile, "test_stream")
|
||||||
@@ -269,8 +259,7 @@ class UnreadCountTests(ZulipTestCase):
|
|||||||
if msg.user_profile.email == self.example_email("hamlet"):
|
if msg.user_profile.email == self.example_email("hamlet"):
|
||||||
self.assertFalse(msg.flags.read)
|
self.assertFalse(msg.flags.read)
|
||||||
|
|
||||||
def test_mark_all_in_invalid_stream_read(self):
|
def test_mark_all_in_invalid_stream_read(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
self.login(self.example_email("hamlet"))
|
self.login(self.example_email("hamlet"))
|
||||||
invalid_stream_id = "12345678"
|
invalid_stream_id = "12345678"
|
||||||
result = self.client_post("/json/mark_stream_as_read", {
|
result = self.client_post("/json/mark_stream_as_read", {
|
||||||
@@ -278,8 +267,7 @@ class UnreadCountTests(ZulipTestCase):
|
|||||||
})
|
})
|
||||||
self.assert_json_error(result, 'Invalid stream id')
|
self.assert_json_error(result, 'Invalid stream id')
|
||||||
|
|
||||||
def test_mark_all_topics_unread_with_invalid_stream_name(self):
|
def test_mark_all_topics_unread_with_invalid_stream_name(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
self.login(self.example_email("hamlet"))
|
self.login(self.example_email("hamlet"))
|
||||||
invalid_stream_id = "12345678"
|
invalid_stream_id = "12345678"
|
||||||
result = self.client_post("/json/mark_topic_as_read", {
|
result = self.client_post("/json/mark_topic_as_read", {
|
||||||
@@ -288,8 +276,7 @@ class UnreadCountTests(ZulipTestCase):
|
|||||||
})
|
})
|
||||||
self.assert_json_error(result, "Invalid stream id")
|
self.assert_json_error(result, "Invalid stream id")
|
||||||
|
|
||||||
def test_mark_all_in_stream_topic_read(self):
|
def test_mark_all_in_stream_topic_read(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
self.login(self.example_email("hamlet"))
|
self.login(self.example_email("hamlet"))
|
||||||
user_profile = self.example_user('hamlet')
|
user_profile = self.example_user('hamlet')
|
||||||
self.subscribe(user_profile, "test_stream")
|
self.subscribe(user_profile, "test_stream")
|
||||||
@@ -326,8 +313,7 @@ class UnreadCountTests(ZulipTestCase):
|
|||||||
if msg.user_profile.email == self.example_email("hamlet"):
|
if msg.user_profile.email == self.example_email("hamlet"):
|
||||||
self.assertFalse(msg.flags.read)
|
self.assertFalse(msg.flags.read)
|
||||||
|
|
||||||
def test_mark_all_in_invalid_topic_read(self):
|
def test_mark_all_in_invalid_topic_read(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
self.login(self.example_email("hamlet"))
|
self.login(self.example_email("hamlet"))
|
||||||
invalid_topic_name = "abc"
|
invalid_topic_name = "abc"
|
||||||
result = self.client_post("/json/mark_topic_as_read", {
|
result = self.client_post("/json/mark_topic_as_read", {
|
||||||
@@ -337,13 +323,11 @@ class UnreadCountTests(ZulipTestCase):
|
|||||||
self.assert_json_error(result, 'No such topic \'abc\'')
|
self.assert_json_error(result, 'No such topic \'abc\'')
|
||||||
|
|
||||||
class FixUnreadTests(ZulipTestCase):
|
class FixUnreadTests(ZulipTestCase):
|
||||||
def test_fix_unreads(self):
|
def test_fix_unreads(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
user = self.example_user('hamlet')
|
user = self.example_user('hamlet')
|
||||||
realm = get_realm('zulip')
|
realm = get_realm('zulip')
|
||||||
|
|
||||||
def send_message(stream_name, topic_name):
|
def send_message(stream_name: Text, topic_name: Text) -> int:
|
||||||
# type: (Text, Text) -> 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,
|
||||||
@@ -353,18 +337,15 @@ class FixUnreadTests(ZulipTestCase):
|
|||||||
message_id=msg_id)
|
message_id=msg_id)
|
||||||
return um.id
|
return um.id
|
||||||
|
|
||||||
def assert_read(user_message_id):
|
def assert_read(user_message_id: int) -> None:
|
||||||
# type: (int) -> None
|
|
||||||
um = UserMessage.objects.get(id=user_message_id)
|
um = UserMessage.objects.get(id=user_message_id)
|
||||||
self.assertTrue(um.flags.read)
|
self.assertTrue(um.flags.read)
|
||||||
|
|
||||||
def assert_unread(user_message_id):
|
def assert_unread(user_message_id: int) -> None:
|
||||||
# type: (int) -> None
|
|
||||||
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):
|
def mute_stream(stream_name: Text) -> None:
|
||||||
# type: (Text) -> 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(
|
||||||
@@ -374,8 +355,7 @@ class FixUnreadTests(ZulipTestCase):
|
|||||||
subscription.in_home_view = False
|
subscription.in_home_view = False
|
||||||
subscription.save()
|
subscription.save()
|
||||||
|
|
||||||
def mute_topic(stream_name, topic_name):
|
def mute_topic(stream_name: Text, topic_name: Text) -> None:
|
||||||
# type: (Text, Text) -> 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)
|
||||||
|
|
||||||
@@ -386,8 +366,7 @@ class FixUnreadTests(ZulipTestCase):
|
|||||||
topic_name=topic_name,
|
topic_name=topic_name,
|
||||||
)
|
)
|
||||||
|
|
||||||
def force_unsubscribe(stream_name):
|
def force_unsubscribe(stream_name: Text) -> None:
|
||||||
# type: (Text) -> 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
|
||||||
|
|||||||
@@ -19,8 +19,7 @@ class PublicURLTest(ZulipTestCase):
|
|||||||
URLs redirect to a page.
|
URLs redirect to a page.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def fetch(self, method, urls, expected_status):
|
def fetch(self, method: str, urls: List[str], expected_status: int) -> None:
|
||||||
# type: (str, List[str], int) -> None
|
|
||||||
for url in urls:
|
for url in urls:
|
||||||
# e.g. self.client_post(url) if method is "post"
|
# e.g. self.client_post(url) if method is "post"
|
||||||
response = getattr(self, method)(url)
|
response = getattr(self, method)(url)
|
||||||
@@ -29,8 +28,7 @@ class PublicURLTest(ZulipTestCase):
|
|||||||
expected_status, response.status_code, method, url))
|
expected_status, response.status_code, method, url))
|
||||||
|
|
||||||
@slow("Tests dozens of endpoints, including all of our /help/ documents")
|
@slow("Tests dozens of endpoints, including all of our /help/ documents")
|
||||||
def test_public_urls(self):
|
def test_public_urls(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
"""
|
"""
|
||||||
Test which views are accessible when not logged in.
|
Test which views are accessible when not logged in.
|
||||||
"""
|
"""
|
||||||
@@ -89,8 +87,7 @@ class PublicURLTest(ZulipTestCase):
|
|||||||
for status_code, url_set in put_urls.items():
|
for status_code, url_set in put_urls.items():
|
||||||
self.fetch("client_put", url_set, status_code)
|
self.fetch("client_put", url_set, status_code)
|
||||||
|
|
||||||
def test_get_gcid_when_not_configured(self):
|
def test_get_gcid_when_not_configured(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
with self.settings(GOOGLE_CLIENT_ID=None):
|
with self.settings(GOOGLE_CLIENT_ID=None):
|
||||||
resp = self.client_get("/api/v1/fetch_google_client_id")
|
resp = self.client_get("/api/v1/fetch_google_client_id")
|
||||||
self.assertEqual(400, resp.status_code,
|
self.assertEqual(400, resp.status_code,
|
||||||
@@ -98,8 +95,7 @@ class PublicURLTest(ZulipTestCase):
|
|||||||
resp.status_code,))
|
resp.status_code,))
|
||||||
self.assertEqual('error', resp.json()['result'])
|
self.assertEqual('error', resp.json()['result'])
|
||||||
|
|
||||||
def test_get_gcid_when_configured(self):
|
def test_get_gcid_when_configured(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
with self.settings(GOOGLE_CLIENT_ID="ABCD"):
|
with self.settings(GOOGLE_CLIENT_ID="ABCD"):
|
||||||
resp = self.client_get("/api/v1/fetch_google_client_id")
|
resp = self.client_get("/api/v1/fetch_google_client_id")
|
||||||
self.assertEqual(200, resp.status_code,
|
self.assertEqual(200, resp.status_code,
|
||||||
@@ -110,20 +106,17 @@ class PublicURLTest(ZulipTestCase):
|
|||||||
self.assertEqual('ABCD', data['google_client_id'])
|
self.assertEqual('ABCD', data['google_client_id'])
|
||||||
|
|
||||||
class URLResolutionTest(TestCase):
|
class URLResolutionTest(TestCase):
|
||||||
def get_callback_string(self, pattern):
|
def get_callback_string(self, pattern: django.core.urlresolvers.RegexURLPattern) -> Optional[str]:
|
||||||
# type: (django.core.urlresolvers.RegexURLPattern) -> Optional[str]
|
|
||||||
callback_str = hasattr(pattern, 'lookup_str') and 'lookup_str'
|
callback_str = hasattr(pattern, 'lookup_str') and 'lookup_str'
|
||||||
callback_str = callback_str or '_callback_str'
|
callback_str = callback_str or '_callback_str'
|
||||||
return getattr(pattern, callback_str, None)
|
return getattr(pattern, callback_str, None)
|
||||||
|
|
||||||
def check_function_exists(self, module_name, view):
|
def check_function_exists(self, module_name: str, view: str) -> None:
|
||||||
# type: (str, str) -> None
|
|
||||||
module = importlib.import_module(module_name)
|
module = importlib.import_module(module_name)
|
||||||
self.assertTrue(hasattr(module, view), "View %s.%s does not exist" % (module_name, view))
|
self.assertTrue(hasattr(module, view), "View %s.%s does not exist" % (module_name, view))
|
||||||
|
|
||||||
# Tests that all views in urls.v1_api_and_json_patterns exist
|
# Tests that all views in urls.v1_api_and_json_patterns exist
|
||||||
def test_rest_api_url_resolution(self):
|
def test_rest_api_url_resolution(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
for pattern in urls.v1_api_and_json_patterns:
|
for pattern in urls.v1_api_and_json_patterns:
|
||||||
callback_str = self.get_callback_string(pattern)
|
callback_str = self.get_callback_string(pattern)
|
||||||
if callback_str and hasattr(pattern, "default_args"):
|
if callback_str and hasattr(pattern, "default_args"):
|
||||||
@@ -136,8 +129,7 @@ class URLResolutionTest(TestCase):
|
|||||||
# Tests function-based views declared in urls.urlpatterns for
|
# Tests function-based views declared in urls.urlpatterns for
|
||||||
# whether the function exists. We at present do not test the
|
# whether the function exists. We at present do not test the
|
||||||
# class-based views.
|
# class-based views.
|
||||||
def test_non_api_url_resolution(self):
|
def test_non_api_url_resolution(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
for pattern in urls.urlpatterns:
|
for pattern in urls.urlpatterns:
|
||||||
callback_str = self.get_callback_string(pattern)
|
callback_str = self.get_callback_string(pattern)
|
||||||
if callback_str:
|
if callback_str:
|
||||||
@@ -145,8 +137,7 @@ class URLResolutionTest(TestCase):
|
|||||||
self.check_function_exists(module_name, base_view)
|
self.check_function_exists(module_name, base_view)
|
||||||
|
|
||||||
class ErrorPageTest(TestCase):
|
class ErrorPageTest(TestCase):
|
||||||
def test_bogus_http_host(self):
|
def test_bogus_http_host(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
# This tests that we've successfully worked around a certain bug in
|
# This tests that we've successfully worked around a certain bug in
|
||||||
# Django's exception handling. The enforce_csrf_checks=True,
|
# Django's exception handling. The enforce_csrf_checks=True,
|
||||||
# secure=True, and HTTP_REFERER with an `https:` scheme are all
|
# secure=True, and HTTP_REFERER with an `https:` scheme are all
|
||||||
|
|||||||
@@ -47,16 +47,14 @@ import ujson
|
|||||||
|
|
||||||
K = TypeVar('K')
|
K = TypeVar('K')
|
||||||
V = TypeVar('V')
|
V = TypeVar('V')
|
||||||
def find_dict(lst, k, v):
|
def find_dict(lst: Iterable[Dict[K, V]], k: K, v: V) -> Dict[K, V]:
|
||||||
# type: (Iterable[Dict[K, V]], K, V) -> Dict[K, V]
|
|
||||||
for dct in lst:
|
for dct in lst:
|
||||||
if dct[k] == v:
|
if dct[k] == v:
|
||||||
return dct
|
return dct
|
||||||
raise AssertionError('Cannot find element in list where key %s == %s' % (k, v))
|
raise AssertionError('Cannot find element in list where key %s == %s' % (k, v))
|
||||||
|
|
||||||
class PermissionTest(ZulipTestCase):
|
class PermissionTest(ZulipTestCase):
|
||||||
def test_get_admin_users(self):
|
def test_get_admin_users(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
user_profile = self.example_user('hamlet')
|
user_profile = self.example_user('hamlet')
|
||||||
do_change_is_admin(user_profile, False)
|
do_change_is_admin(user_profile, False)
|
||||||
admin_users = user_profile.realm.get_admin_users()
|
admin_users = user_profile.realm.get_admin_users()
|
||||||
@@ -65,8 +63,7 @@ class PermissionTest(ZulipTestCase):
|
|||||||
admin_users = user_profile.realm.get_admin_users()
|
admin_users = user_profile.realm.get_admin_users()
|
||||||
self.assertTrue(user_profile in admin_users)
|
self.assertTrue(user_profile in admin_users)
|
||||||
|
|
||||||
def test_updating_non_existent_user(self):
|
def test_updating_non_existent_user(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
self.login(self.example_email("hamlet"))
|
self.login(self.example_email("hamlet"))
|
||||||
admin = self.example_user('hamlet')
|
admin = self.example_user('hamlet')
|
||||||
do_change_is_admin(admin, True)
|
do_change_is_admin(admin, True)
|
||||||
@@ -74,8 +71,7 @@ class PermissionTest(ZulipTestCase):
|
|||||||
result = self.client_patch('/json/users/nonexistentuser@zulip.com', {})
|
result = self.client_patch('/json/users/nonexistentuser@zulip.com', {})
|
||||||
self.assert_json_error(result, 'No such user')
|
self.assert_json_error(result, 'No such user')
|
||||||
|
|
||||||
def test_admin_api(self):
|
def test_admin_api(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
self.login(self.example_email("hamlet"))
|
self.login(self.example_email("hamlet"))
|
||||||
admin = self.example_user('hamlet')
|
admin = self.example_user('hamlet')
|
||||||
user = self.example_user('othello')
|
user = self.example_user('othello')
|
||||||
@@ -137,8 +133,7 @@ class PermissionTest(ZulipTestCase):
|
|||||||
result = self.client_patch('/json/users/hamlet@zulip.com', req)
|
result = self.client_patch('/json/users/hamlet@zulip.com', req)
|
||||||
self.assert_json_error(result, 'Insufficient permission')
|
self.assert_json_error(result, 'Insufficient permission')
|
||||||
|
|
||||||
def test_admin_user_can_change_full_name(self):
|
def test_admin_user_can_change_full_name(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
new_name = 'new name'
|
new_name = 'new name'
|
||||||
self.login(self.example_email("iago"))
|
self.login(self.example_email("iago"))
|
||||||
req = dict(full_name=ujson.dumps(new_name))
|
req = dict(full_name=ujson.dumps(new_name))
|
||||||
@@ -147,31 +142,27 @@ class PermissionTest(ZulipTestCase):
|
|||||||
hamlet = self.example_user('hamlet')
|
hamlet = self.example_user('hamlet')
|
||||||
self.assertEqual(hamlet.full_name, new_name)
|
self.assertEqual(hamlet.full_name, new_name)
|
||||||
|
|
||||||
def test_non_admin_cannot_change_full_name(self):
|
def test_non_admin_cannot_change_full_name(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
self.login(self.example_email("hamlet"))
|
self.login(self.example_email("hamlet"))
|
||||||
req = dict(full_name=ujson.dumps('new name'))
|
req = dict(full_name=ujson.dumps('new name'))
|
||||||
result = self.client_patch('/json/users/othello@zulip.com', req)
|
result = self.client_patch('/json/users/othello@zulip.com', req)
|
||||||
self.assert_json_error(result, 'Insufficient permission')
|
self.assert_json_error(result, 'Insufficient permission')
|
||||||
|
|
||||||
def test_admin_cannot_set_long_full_name(self):
|
def test_admin_cannot_set_long_full_name(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
new_name = 'a' * (UserProfile.MAX_NAME_LENGTH + 1)
|
new_name = 'a' * (UserProfile.MAX_NAME_LENGTH + 1)
|
||||||
self.login(self.example_email("iago"))
|
self.login(self.example_email("iago"))
|
||||||
req = dict(full_name=ujson.dumps(new_name))
|
req = dict(full_name=ujson.dumps(new_name))
|
||||||
result = self.client_patch('/json/users/hamlet@zulip.com', req)
|
result = self.client_patch('/json/users/hamlet@zulip.com', req)
|
||||||
self.assert_json_error(result, 'Name too long!')
|
self.assert_json_error(result, 'Name too long!')
|
||||||
|
|
||||||
def test_admin_cannot_set_short_full_name(self):
|
def test_admin_cannot_set_short_full_name(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
new_name = 'a'
|
new_name = 'a'
|
||||||
self.login(self.example_email("iago"))
|
self.login(self.example_email("iago"))
|
||||||
req = dict(full_name=ujson.dumps(new_name))
|
req = dict(full_name=ujson.dumps(new_name))
|
||||||
result = self.client_patch('/json/users/hamlet@zulip.com', req)
|
result = self.client_patch('/json/users/hamlet@zulip.com', req)
|
||||||
self.assert_json_error(result, 'Name too short!')
|
self.assert_json_error(result, 'Name too short!')
|
||||||
|
|
||||||
def test_admin_cannot_set_full_name_with_invalid_characters(self):
|
def test_admin_cannot_set_full_name_with_invalid_characters(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
new_name = 'Opheli*'
|
new_name = 'Opheli*'
|
||||||
self.login(self.example_email("iago"))
|
self.login(self.example_email("iago"))
|
||||||
req = dict(full_name=ujson.dumps(new_name))
|
req = dict(full_name=ujson.dumps(new_name))
|
||||||
@@ -179,8 +170,7 @@ class PermissionTest(ZulipTestCase):
|
|||||||
self.assert_json_error(result, 'Invalid characters in name!')
|
self.assert_json_error(result, 'Invalid characters in name!')
|
||||||
|
|
||||||
class AdminCreateUserTest(ZulipTestCase):
|
class AdminCreateUserTest(ZulipTestCase):
|
||||||
def test_create_user_backend(self):
|
def test_create_user_backend(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
|
|
||||||
# This test should give us complete coverage on
|
# This test should give us complete coverage on
|
||||||
# create_user_backend. It mostly exercises error
|
# create_user_backend. It mostly exercises error
|
||||||
@@ -254,16 +244,14 @@ class AdminCreateUserTest(ZulipTestCase):
|
|||||||
"Email 'romeo@zulip.net' already in use")
|
"Email 'romeo@zulip.net' already in use")
|
||||||
|
|
||||||
class UserProfileTest(ZulipTestCase):
|
class UserProfileTest(ZulipTestCase):
|
||||||
def test_get_emails_from_user_ids(self):
|
def test_get_emails_from_user_ids(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
hamlet = self.example_user('hamlet')
|
hamlet = self.example_user('hamlet')
|
||||||
othello = self.example_user('othello')
|
othello = self.example_user('othello')
|
||||||
dct = get_emails_from_user_ids([hamlet.id, othello.id])
|
dct = get_emails_from_user_ids([hamlet.id, othello.id])
|
||||||
self.assertEqual(dct[hamlet.id], self.example_email("hamlet"))
|
self.assertEqual(dct[hamlet.id], self.example_email("hamlet"))
|
||||||
self.assertEqual(dct[othello.id], self.example_email("othello"))
|
self.assertEqual(dct[othello.id], self.example_email("othello"))
|
||||||
|
|
||||||
def test_cache_invalidation(self):
|
def test_cache_invalidation(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
hamlet = self.example_user('hamlet')
|
hamlet = self.example_user('hamlet')
|
||||||
with mock.patch('zerver.lib.cache.delete_display_recipient_cache') as m:
|
with mock.patch('zerver.lib.cache.delete_display_recipient_cache') as m:
|
||||||
hamlet.full_name = 'Hamlet Junior'
|
hamlet.full_name = 'Hamlet Junior'
|
||||||
@@ -278,16 +266,14 @@ class UserProfileTest(ZulipTestCase):
|
|||||||
self.assertFalse(m.called)
|
self.assertFalse(m.called)
|
||||||
|
|
||||||
class ActivateTest(ZulipTestCase):
|
class ActivateTest(ZulipTestCase):
|
||||||
def test_basics(self):
|
def test_basics(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
user = self.example_user('hamlet')
|
user = self.example_user('hamlet')
|
||||||
do_deactivate_user(user)
|
do_deactivate_user(user)
|
||||||
self.assertFalse(user.is_active)
|
self.assertFalse(user.is_active)
|
||||||
do_reactivate_user(user)
|
do_reactivate_user(user)
|
||||||
self.assertTrue(user.is_active)
|
self.assertTrue(user.is_active)
|
||||||
|
|
||||||
def test_api(self):
|
def test_api(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
admin = self.example_user('othello')
|
admin = self.example_user('othello')
|
||||||
do_change_is_admin(admin, True)
|
do_change_is_admin(admin, True)
|
||||||
self.login(self.example_email("othello"))
|
self.login(self.example_email("othello"))
|
||||||
@@ -305,8 +291,7 @@ class ActivateTest(ZulipTestCase):
|
|||||||
user = self.example_user('hamlet')
|
user = self.example_user('hamlet')
|
||||||
self.assertTrue(user.is_active)
|
self.assertTrue(user.is_active)
|
||||||
|
|
||||||
def test_api_me_user(self):
|
def test_api_me_user(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
"""This test helps ensure that our URL patterns for /users/me URLs
|
"""This test helps ensure that our URL patterns for /users/me URLs
|
||||||
handle email addresses starting with "me" correctly."""
|
handle email addresses starting with "me" correctly."""
|
||||||
self.register(self.nonreg_email('me'), "testpassword")
|
self.register(self.nonreg_email('me'), "testpassword")
|
||||||
@@ -322,8 +307,7 @@ class ActivateTest(ZulipTestCase):
|
|||||||
user = self.nonreg_user('me')
|
user = self.nonreg_user('me')
|
||||||
self.assertTrue(user.is_active)
|
self.assertTrue(user.is_active)
|
||||||
|
|
||||||
def test_api_with_nonexistent_user(self):
|
def test_api_with_nonexistent_user(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
admin = self.example_user('othello')
|
admin = self.example_user('othello')
|
||||||
do_change_is_admin(admin, True)
|
do_change_is_admin(admin, True)
|
||||||
self.login(self.example_email("othello"))
|
self.login(self.example_email("othello"))
|
||||||
@@ -346,8 +330,7 @@ class ActivateTest(ZulipTestCase):
|
|||||||
result = self.client_post('/json/users/nonexistent@zulip.com/reactivate')
|
result = self.client_post('/json/users/nonexistent@zulip.com/reactivate')
|
||||||
self.assert_json_error(result, 'No such user')
|
self.assert_json_error(result, 'No such user')
|
||||||
|
|
||||||
def test_api_with_insufficient_permissions(self):
|
def test_api_with_insufficient_permissions(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
non_admin = self.example_user('othello')
|
non_admin = self.example_user('othello')
|
||||||
do_change_is_admin(non_admin, False)
|
do_change_is_admin(non_admin, False)
|
||||||
self.login(self.example_email("othello"))
|
self.login(self.example_email("othello"))
|
||||||
@@ -360,8 +343,7 @@ class ActivateTest(ZulipTestCase):
|
|||||||
result = self.client_post('/json/users/hamlet@zulip.com/reactivate')
|
result = self.client_post('/json/users/hamlet@zulip.com/reactivate')
|
||||||
self.assert_json_error(result, 'Insufficient permission')
|
self.assert_json_error(result, 'Insufficient permission')
|
||||||
|
|
||||||
def test_clear_scheduled_jobs(self):
|
def test_clear_scheduled_jobs(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
user = self.example_user('hamlet')
|
user = self.example_user('hamlet')
|
||||||
send_future_email('zerver/emails/followup_day1', to_user_id=user.id, delay=datetime.timedelta(hours=1))
|
send_future_email('zerver/emails/followup_day1', to_user_id=user.id, delay=datetime.timedelta(hours=1))
|
||||||
self.assertEqual(ScheduledEmail.objects.count(), 1)
|
self.assertEqual(ScheduledEmail.objects.count(), 1)
|
||||||
@@ -369,8 +351,7 @@ class ActivateTest(ZulipTestCase):
|
|||||||
self.assertEqual(ScheduledEmail.objects.count(), 0)
|
self.assertEqual(ScheduledEmail.objects.count(), 0)
|
||||||
|
|
||||||
class RecipientInfoTest(ZulipTestCase):
|
class RecipientInfoTest(ZulipTestCase):
|
||||||
def test_stream_recipient_info(self):
|
def test_stream_recipient_info(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
hamlet = self.example_user('hamlet')
|
hamlet = self.example_user('hamlet')
|
||||||
cordelia = self.example_user('cordelia')
|
cordelia = self.example_user('cordelia')
|
||||||
othello = self.example_user('othello')
|
othello = self.example_user('othello')
|
||||||
@@ -470,14 +451,12 @@ class RecipientInfoTest(ZulipTestCase):
|
|||||||
self.assertEqual(info['default_bot_user_ids'], {normal_bot.id})
|
self.assertEqual(info['default_bot_user_ids'], {normal_bot.id})
|
||||||
|
|
||||||
class BulkUsersTest(ZulipTestCase):
|
class BulkUsersTest(ZulipTestCase):
|
||||||
def test_client_gravatar_option(self):
|
def test_client_gravatar_option(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
self.login(self.example_email('cordelia'))
|
self.login(self.example_email('cordelia'))
|
||||||
|
|
||||||
hamlet = self.example_user('hamlet')
|
hamlet = self.example_user('hamlet')
|
||||||
|
|
||||||
def get_hamlet_avatar(client_gravatar):
|
def get_hamlet_avatar(client_gravatar: bool) -> Optional[Text]:
|
||||||
# type: (bool) -> Optional[Text]
|
|
||||||
data = dict(client_gravatar=ujson.dumps(client_gravatar))
|
data = dict(client_gravatar=ujson.dumps(client_gravatar))
|
||||||
result = self.client_get('/json/users', data)
|
result = self.client_get('/json/users', data)
|
||||||
self.assert_json_success(result)
|
self.assert_json_success(result)
|
||||||
@@ -507,14 +486,12 @@ class BulkUsersTest(ZulipTestCase):
|
|||||||
|
|
||||||
class GetProfileTest(ZulipTestCase):
|
class GetProfileTest(ZulipTestCase):
|
||||||
|
|
||||||
def common_update_pointer(self, email, pointer):
|
def common_update_pointer(self, email: Text, pointer: int) -> None:
|
||||||
# type: (Text, int) -> None
|
|
||||||
self.login(email)
|
self.login(email)
|
||||||
result = self.client_post("/json/users/me/pointer", {"pointer": pointer})
|
result = self.client_post("/json/users/me/pointer", {"pointer": pointer})
|
||||||
self.assert_json_success(result)
|
self.assert_json_success(result)
|
||||||
|
|
||||||
def common_get_profile(self, user_id):
|
def common_get_profile(self, user_id: str) -> Dict[Text, Any]:
|
||||||
# type: (str) -> Dict[Text, Any]
|
|
||||||
# Assumes all users are example users in realm 'zulip'
|
# Assumes all users are example users in realm 'zulip'
|
||||||
user_profile = self.example_user(user_id)
|
user_profile = self.example_user(user_id)
|
||||||
self.send_stream_message(user_profile.email, "Verona", "hello")
|
self.send_stream_message(user_profile.email, "Verona", "hello")
|
||||||
@@ -533,16 +510,14 @@ class GetProfileTest(ZulipTestCase):
|
|||||||
self.assertEqual(json["max_message_id"], max_id)
|
self.assertEqual(json["max_message_id"], max_id)
|
||||||
return json
|
return json
|
||||||
|
|
||||||
def test_get_pointer(self):
|
def test_get_pointer(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
email = self.example_email("hamlet")
|
email = self.example_email("hamlet")
|
||||||
self.login(email)
|
self.login(email)
|
||||||
result = self.client_get("/json/users/me/pointer")
|
result = self.client_get("/json/users/me/pointer")
|
||||||
self.assert_json_success(result)
|
self.assert_json_success(result)
|
||||||
self.assertIn("pointer", result.json())
|
self.assertIn("pointer", result.json())
|
||||||
|
|
||||||
def test_cache_behavior(self):
|
def test_cache_behavior(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
"""Tests whether fetching a user object the normal way, with
|
"""Tests whether fetching a user object the normal way, with
|
||||||
`get_user`, makes 1 cache query and 1 database query.
|
`get_user`, makes 1 cache query and 1 database query.
|
||||||
"""
|
"""
|
||||||
@@ -556,8 +531,7 @@ class GetProfileTest(ZulipTestCase):
|
|||||||
self.assert_length(cache_queries, 1)
|
self.assert_length(cache_queries, 1)
|
||||||
self.assertEqual(user_profile.email, email)
|
self.assertEqual(user_profile.email, email)
|
||||||
|
|
||||||
def test_get_user_profile(self):
|
def test_get_user_profile(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
self.login(self.example_email("hamlet"))
|
self.login(self.example_email("hamlet"))
|
||||||
result = ujson.loads(self.client_get('/json/users/me').content)
|
result = ujson.loads(self.client_get('/json/users/me').content)
|
||||||
self.assertEqual(result['short_name'], 'hamlet')
|
self.assertEqual(result['short_name'], 'hamlet')
|
||||||
@@ -574,16 +548,14 @@ class GetProfileTest(ZulipTestCase):
|
|||||||
self.assertFalse(result['is_bot'])
|
self.assertFalse(result['is_bot'])
|
||||||
self.assertTrue(result['is_admin'])
|
self.assertTrue(result['is_admin'])
|
||||||
|
|
||||||
def test_api_get_empty_profile(self):
|
def test_api_get_empty_profile(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
"""
|
"""
|
||||||
Ensure GET /users/me returns a max message id and returns successfully
|
Ensure GET /users/me returns a max message id and returns successfully
|
||||||
"""
|
"""
|
||||||
json = self.common_get_profile("othello")
|
json = self.common_get_profile("othello")
|
||||||
self.assertEqual(json["pointer"], -1)
|
self.assertEqual(json["pointer"], -1)
|
||||||
|
|
||||||
def test_profile_with_pointer(self):
|
def test_profile_with_pointer(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
"""
|
"""
|
||||||
Ensure GET /users/me returns a proper pointer id after the pointer is updated
|
Ensure GET /users/me returns a proper pointer id after the pointer is updated
|
||||||
"""
|
"""
|
||||||
@@ -604,8 +576,7 @@ class GetProfileTest(ZulipTestCase):
|
|||||||
result = self.client_post("/json/users/me/pointer", {"pointer": 99999999})
|
result = self.client_post("/json/users/me/pointer", {"pointer": 99999999})
|
||||||
self.assert_json_error(result, "Invalid message ID")
|
self.assert_json_error(result, "Invalid message ID")
|
||||||
|
|
||||||
def test_get_all_profiles_avatar_urls(self):
|
def test_get_all_profiles_avatar_urls(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
user_profile = self.example_user('hamlet')
|
user_profile = self.example_user('hamlet')
|
||||||
result = self.client_get("/api/v1/users", **self.api_auth(self.example_email("hamlet")))
|
result = self.client_get("/api/v1/users", **self.api_auth(self.example_email("hamlet")))
|
||||||
self.assert_json_success(result)
|
self.assert_json_success(result)
|
||||||
|
|||||||
Reference in New Issue
Block a user