mirror of
https://github.com/zulip/zulip.git
synced 2025-11-04 22:13:26 +00:00
python: Normalize quotes with Black.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
This commit is contained in:
committed by
Tim Abbott
parent
11741543da
commit
6e4c3e41dc
@@ -88,12 +88,12 @@ class UploadSerializeMixin(SerializeMixin):
|
||||
while providing the required isolation.
|
||||
"""
|
||||
|
||||
lockfile = 'var/upload_lock'
|
||||
lockfile = "var/upload_lock"
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls: Any, *args: Any, **kwargs: Any) -> None:
|
||||
if not os.path.exists(cls.lockfile):
|
||||
with open(cls.lockfile, 'w'): # nocoverage - rare locking case
|
||||
with open(cls.lockfile, "w"): # nocoverage - rare locking case
|
||||
pass
|
||||
|
||||
super().setUpClass(*args, **kwargs)
|
||||
@@ -120,7 +120,7 @@ class ZulipTestCase(TestCase):
|
||||
translation.activate(settings.LANGUAGE_CODE)
|
||||
|
||||
# Clean up after using fakeldap in LDAP tests:
|
||||
if hasattr(self, 'mock_ldap') and hasattr(self, 'mock_initialize'):
|
||||
if hasattr(self, "mock_ldap") and hasattr(self, "mock_initialize"):
|
||||
if self.mock_ldap is not None:
|
||||
self.mock_ldap.reset()
|
||||
self.mock_initialize.stop()
|
||||
@@ -156,7 +156,7 @@ Output:
|
||||
raise ExtraConsoleOutputInTestException(exception_message)
|
||||
return test_result
|
||||
|
||||
'''
|
||||
"""
|
||||
WRAPPER_COMMENT:
|
||||
|
||||
We wrap calls to self.client.{patch,put,get,post,delete} for various
|
||||
@@ -167,19 +167,19 @@ Output:
|
||||
The linter will prevent direct calls to self.client.foo, so the wrapper
|
||||
functions have to fake out the linter by using a local variable called
|
||||
django_client to fool the regext.
|
||||
'''
|
||||
"""
|
||||
DEFAULT_SUBDOMAIN = "zulip"
|
||||
TOKENIZED_NOREPLY_REGEX = settings.TOKENIZED_NOREPLY_EMAIL_ADDRESS.format(token="[a-z0-9_]{24}")
|
||||
|
||||
def set_http_headers(self, kwargs: Dict[str, Any]) -> None:
|
||||
if 'subdomain' in kwargs:
|
||||
kwargs['HTTP_HOST'] = Realm.host_for_subdomain(kwargs['subdomain'])
|
||||
del kwargs['subdomain']
|
||||
elif 'HTTP_HOST' not in kwargs:
|
||||
kwargs['HTTP_HOST'] = Realm.host_for_subdomain(self.DEFAULT_SUBDOMAIN)
|
||||
if "subdomain" in kwargs:
|
||||
kwargs["HTTP_HOST"] = Realm.host_for_subdomain(kwargs["subdomain"])
|
||||
del kwargs["subdomain"]
|
||||
elif "HTTP_HOST" not in kwargs:
|
||||
kwargs["HTTP_HOST"] = Realm.host_for_subdomain(self.DEFAULT_SUBDOMAIN)
|
||||
|
||||
# set User-Agent
|
||||
if 'HTTP_AUTHORIZATION' in kwargs:
|
||||
if "HTTP_AUTHORIZATION" in kwargs:
|
||||
# An API request; use mobile as the default user agent
|
||||
default_user_agent = "ZulipMobile/26.22.145 (iOS 10.3.1)"
|
||||
else:
|
||||
@@ -189,19 +189,19 @@ Output:
|
||||
+ "AppleWebKit/537.36 (KHTML, like Gecko) "
|
||||
+ "Chrome/79.0.3945.130 Safari/537.36"
|
||||
)
|
||||
if kwargs.get('skip_user_agent'):
|
||||
if kwargs.get("skip_user_agent"):
|
||||
# Provide a way to disable setting User-Agent if desired.
|
||||
assert 'HTTP_USER_AGENT' not in kwargs
|
||||
del kwargs['skip_user_agent']
|
||||
elif 'HTTP_USER_AGENT' not in kwargs:
|
||||
kwargs['HTTP_USER_AGENT'] = default_user_agent
|
||||
assert "HTTP_USER_AGENT" not in kwargs
|
||||
del kwargs["skip_user_agent"]
|
||||
elif "HTTP_USER_AGENT" not in kwargs:
|
||||
kwargs["HTTP_USER_AGENT"] = default_user_agent
|
||||
|
||||
def extract_api_suffix_url(self, url: str) -> Tuple[str, Dict[str, Any]]:
|
||||
"""
|
||||
Function that extracts the URL after `/api/v1` or `/json` and also
|
||||
returns the query data in the URL, if there is any.
|
||||
"""
|
||||
url_split = url.split('?')
|
||||
url_split = url.split("?")
|
||||
data: Dict[str, Any] = {}
|
||||
if len(url_split) == 2:
|
||||
data = urllib.parse.parse_qs(url_split[1])
|
||||
@@ -231,7 +231,7 @@ Output:
|
||||
except orjson.JSONDecodeError:
|
||||
return
|
||||
json_url = False
|
||||
if url.startswith('/json'):
|
||||
if url.startswith("/json"):
|
||||
json_url = True
|
||||
url, query_data = self.extract_api_suffix_url(url)
|
||||
if len(query_data) != 0:
|
||||
@@ -369,20 +369,20 @@ Output:
|
||||
return result
|
||||
|
||||
example_user_map = dict(
|
||||
hamlet='hamlet@zulip.com',
|
||||
cordelia='cordelia@zulip.com',
|
||||
iago='iago@zulip.com',
|
||||
prospero='prospero@zulip.com',
|
||||
othello='othello@zulip.com',
|
||||
AARON='AARON@zulip.com',
|
||||
aaron='aaron@zulip.com',
|
||||
ZOE='ZOE@zulip.com',
|
||||
polonius='polonius@zulip.com',
|
||||
desdemona='desdemona@zulip.com',
|
||||
webhook_bot='webhook-bot@zulip.com',
|
||||
welcome_bot='welcome-bot@zulip.com',
|
||||
outgoing_webhook_bot='outgoing-webhook@zulip.com',
|
||||
default_bot='default-bot@zulip.com',
|
||||
hamlet="hamlet@zulip.com",
|
||||
cordelia="cordelia@zulip.com",
|
||||
iago="iago@zulip.com",
|
||||
prospero="prospero@zulip.com",
|
||||
othello="othello@zulip.com",
|
||||
AARON="AARON@zulip.com",
|
||||
aaron="aaron@zulip.com",
|
||||
ZOE="ZOE@zulip.com",
|
||||
polonius="polonius@zulip.com",
|
||||
desdemona="desdemona@zulip.com",
|
||||
webhook_bot="webhook-bot@zulip.com",
|
||||
welcome_bot="welcome-bot@zulip.com",
|
||||
outgoing_webhook_bot="outgoing-webhook@zulip.com",
|
||||
default_bot="default-bot@zulip.com",
|
||||
)
|
||||
|
||||
mit_user_map = dict(
|
||||
@@ -398,21 +398,21 @@ Output:
|
||||
|
||||
# Non-registered test users
|
||||
nonreg_user_map = dict(
|
||||
test='test@zulip.com',
|
||||
test1='test1@zulip.com',
|
||||
alice='alice@zulip.com',
|
||||
newuser='newuser@zulip.com',
|
||||
bob='bob@zulip.com',
|
||||
cordelia='cordelia@zulip.com',
|
||||
newguy='newguy@zulip.com',
|
||||
me='me@zulip.com',
|
||||
test="test@zulip.com",
|
||||
test1="test1@zulip.com",
|
||||
alice="alice@zulip.com",
|
||||
newuser="newuser@zulip.com",
|
||||
bob="bob@zulip.com",
|
||||
cordelia="cordelia@zulip.com",
|
||||
newguy="newguy@zulip.com",
|
||||
me="me@zulip.com",
|
||||
)
|
||||
|
||||
example_user_ldap_username_map = dict(
|
||||
hamlet='hamlet',
|
||||
cordelia='cordelia',
|
||||
hamlet="hamlet",
|
||||
cordelia="cordelia",
|
||||
# aaron's uid in our test directory is "letham".
|
||||
aaron='letham',
|
||||
aaron="letham",
|
||||
)
|
||||
|
||||
def nonreg_user(self, name: str) -> UserProfile:
|
||||
@@ -421,15 +421,15 @@ Output:
|
||||
|
||||
def example_user(self, name: str) -> UserProfile:
|
||||
email = self.example_user_map[name]
|
||||
return get_user_by_delivery_email(email, get_realm('zulip'))
|
||||
return get_user_by_delivery_email(email, get_realm("zulip"))
|
||||
|
||||
def mit_user(self, name: str) -> UserProfile:
|
||||
email = self.mit_user_map[name]
|
||||
return get_user(email, get_realm('zephyr'))
|
||||
return get_user(email, get_realm("zephyr"))
|
||||
|
||||
def lear_user(self, name: str) -> UserProfile:
|
||||
email = self.lear_user_map[name]
|
||||
return get_user(email, get_realm('lear'))
|
||||
return get_user(email, get_realm("lear"))
|
||||
|
||||
def nonreg_email(self, name: str) -> str:
|
||||
return self.nonreg_user_map[name]
|
||||
@@ -444,17 +444,17 @@ Output:
|
||||
return get_system_bot(settings.NOTIFICATION_BOT)
|
||||
|
||||
def create_test_bot(
|
||||
self, short_name: str, user_profile: UserProfile, full_name: str = 'Foo Bot', **extras: Any
|
||||
self, short_name: str, user_profile: UserProfile, full_name: str = "Foo Bot", **extras: Any
|
||||
) -> UserProfile:
|
||||
self.login_user(user_profile)
|
||||
bot_info = {
|
||||
'short_name': short_name,
|
||||
'full_name': full_name,
|
||||
"short_name": short_name,
|
||||
"full_name": full_name,
|
||||
}
|
||||
bot_info.update(extras)
|
||||
result = self.client_post("/json/bots", bot_info)
|
||||
self.assert_json_success(result)
|
||||
bot_email = f'{short_name}-bot@zulip.testserver'
|
||||
bot_email = f"{short_name}-bot@zulip.testserver"
|
||||
bot_profile = get_user(bot_email, user_profile.realm)
|
||||
return bot_profile
|
||||
|
||||
@@ -462,15 +462,15 @@ Output:
|
||||
self,
|
||||
short_name: str,
|
||||
user_profile: UserProfile,
|
||||
full_name: str = 'Foo Bot',
|
||||
full_name: str = "Foo Bot",
|
||||
*,
|
||||
assert_json_error_msg: str,
|
||||
**extras: Any,
|
||||
) -> None:
|
||||
self.login_user(user_profile)
|
||||
bot_info = {
|
||||
'short_name': short_name,
|
||||
'full_name': full_name,
|
||||
"short_name": short_name,
|
||||
"full_name": full_name,
|
||||
}
|
||||
bot_info.update(extras)
|
||||
result = self.client_post("/json/bots", bot_info)
|
||||
@@ -492,7 +492,7 @@ Output:
|
||||
# It is important to check `is_web_public_visitor` to verify
|
||||
# that we treated this request as a normal logged-in session,
|
||||
# not as a web-public visitor.
|
||||
self.assertEqual(page_params['is_web_public_visitor'], False)
|
||||
self.assertEqual(page_params["is_web_public_visitor"], False)
|
||||
|
||||
def check_rendered_web_public_visitor(self, result: HttpResponse) -> None:
|
||||
"""Verifies that a visit of / was a 200 that rendered page_params
|
||||
@@ -501,7 +501,7 @@ Output:
|
||||
page_params = self._get_page_params(result)
|
||||
# It is important to check `is_web_public_visitor` to verify
|
||||
# that we treated this request to render for a `web_public_visitor`
|
||||
self.assertEqual(page_params['is_web_public_visitor'], True)
|
||||
self.assertEqual(page_params["is_web_public_visitor"], True)
|
||||
|
||||
def login_with_return(
|
||||
self, email: str, password: Optional[str] = None, **kwargs: Any
|
||||
@@ -509,7 +509,7 @@ Output:
|
||||
if password is None:
|
||||
password = initial_password(email)
|
||||
result = self.client_post(
|
||||
'/accounts/login/', {'username': email, 'password': password}, **kwargs
|
||||
"/accounts/login/", {"username": email, "password": password}, **kwargs
|
||||
)
|
||||
self.assertNotEqual(result.status_code, 500)
|
||||
return result
|
||||
@@ -525,7 +525,7 @@ Output:
|
||||
|
||||
Try to use 'cordelia' or 'othello' as "other" users.
|
||||
"""
|
||||
assert '@' not in name, 'use login_by_email for email logins'
|
||||
assert "@" not in name, "use login_by_email for email logins"
|
||||
user = self.example_user(name)
|
||||
self.login_user(user)
|
||||
|
||||
@@ -580,7 +580,7 @@ Output:
|
||||
self.client.logout()
|
||||
|
||||
def register(self, email: str, password: str, **kwargs: Any) -> HttpResponse:
|
||||
self.client_post('/accounts/home/', {'email': email}, **kwargs)
|
||||
self.client_post("/accounts/home/", {"email": email}, **kwargs)
|
||||
return self.submit_reg_form_for_user(email, password, **kwargs)
|
||||
|
||||
def submit_reg_form_for_user(
|
||||
@@ -589,12 +589,12 @@ Output:
|
||||
password: str,
|
||||
realm_name: str = "Zulip Test",
|
||||
realm_subdomain: str = "zuliptest",
|
||||
from_confirmation: str = '',
|
||||
from_confirmation: str = "",
|
||||
full_name: Optional[str] = None,
|
||||
timezone: str = '',
|
||||
timezone: str = "",
|
||||
realm_in_root_domain: Optional[str] = None,
|
||||
default_stream_groups: Sequence[str] = [],
|
||||
source_realm: str = '',
|
||||
source_realm: str = "",
|
||||
key: Optional[str] = None,
|
||||
**kwargs: Any,
|
||||
) -> HttpResponse:
|
||||
@@ -609,20 +609,20 @@ Output:
|
||||
if full_name is None:
|
||||
full_name = email.replace("@", "_")
|
||||
payload = {
|
||||
'full_name': full_name,
|
||||
'password': password,
|
||||
'realm_name': realm_name,
|
||||
'realm_subdomain': realm_subdomain,
|
||||
'key': key if key is not None else find_key_by_email(email),
|
||||
'timezone': timezone,
|
||||
'terms': True,
|
||||
'from_confirmation': from_confirmation,
|
||||
'default_stream_group': default_stream_groups,
|
||||
'source_realm': source_realm,
|
||||
"full_name": full_name,
|
||||
"password": password,
|
||||
"realm_name": realm_name,
|
||||
"realm_subdomain": realm_subdomain,
|
||||
"key": key if key is not None else find_key_by_email(email),
|
||||
"timezone": timezone,
|
||||
"terms": True,
|
||||
"from_confirmation": from_confirmation,
|
||||
"default_stream_group": default_stream_groups,
|
||||
"source_realm": source_realm,
|
||||
}
|
||||
if realm_in_root_domain is not None:
|
||||
payload['realm_in_root_domain'] = realm_in_root_domain
|
||||
return self.client_post('/accounts/register/', payload, **kwargs)
|
||||
payload["realm_in_root_domain"] = realm_in_root_domain
|
||||
return self.client_post("/accounts/register/", payload, **kwargs)
|
||||
|
||||
def get_confirmation_url_from_outbox(
|
||||
self,
|
||||
@@ -665,7 +665,7 @@ Output:
|
||||
|
||||
def encode_email(self, email: str, realm: str = "zulip") -> str:
|
||||
# TODO: use encode_user where possible
|
||||
assert '@' in email
|
||||
assert "@" in email
|
||||
user = get_user_by_delivery_email(email, get_realm(realm))
|
||||
api_key = get_api_key(user)
|
||||
|
||||
@@ -676,34 +676,34 @@ Output:
|
||||
identifier: Can be an email or a remote server uuid.
|
||||
"""
|
||||
credentials = f"{identifier}:{api_key}"
|
||||
return 'Basic ' + base64.b64encode(credentials.encode('utf-8')).decode('utf-8')
|
||||
return "Basic " + base64.b64encode(credentials.encode("utf-8")).decode("utf-8")
|
||||
|
||||
def uuid_get(self, identifier: str, *args: Any, **kwargs: Any) -> HttpResponse:
|
||||
kwargs['HTTP_AUTHORIZATION'] = self.encode_uuid(identifier)
|
||||
kwargs["HTTP_AUTHORIZATION"] = self.encode_uuid(identifier)
|
||||
return self.client_get(*args, **kwargs)
|
||||
|
||||
def uuid_post(self, identifier: str, *args: Any, **kwargs: Any) -> HttpResponse:
|
||||
kwargs['HTTP_AUTHORIZATION'] = self.encode_uuid(identifier)
|
||||
kwargs["HTTP_AUTHORIZATION"] = self.encode_uuid(identifier)
|
||||
return self.client_post(*args, **kwargs)
|
||||
|
||||
def api_get(self, user: UserProfile, *args: Any, **kwargs: Any) -> HttpResponse:
|
||||
kwargs['HTTP_AUTHORIZATION'] = self.encode_user(user)
|
||||
kwargs["HTTP_AUTHORIZATION"] = self.encode_user(user)
|
||||
return self.client_get(*args, **kwargs)
|
||||
|
||||
def api_post(
|
||||
self, user: UserProfile, *args: Any, intentionally_undocumented: bool = False, **kwargs: Any
|
||||
) -> HttpResponse:
|
||||
kwargs['HTTP_AUTHORIZATION'] = self.encode_user(user)
|
||||
kwargs["HTTP_AUTHORIZATION"] = self.encode_user(user)
|
||||
return self.client_post(
|
||||
*args, intentionally_undocumented=intentionally_undocumented, **kwargs
|
||||
)
|
||||
|
||||
def api_patch(self, user: UserProfile, *args: Any, **kwargs: Any) -> HttpResponse:
|
||||
kwargs['HTTP_AUTHORIZATION'] = self.encode_user(user)
|
||||
kwargs["HTTP_AUTHORIZATION"] = self.encode_user(user)
|
||||
return self.client_patch(*args, **kwargs)
|
||||
|
||||
def api_delete(self, user: UserProfile, *args: Any, **kwargs: Any) -> HttpResponse:
|
||||
kwargs['HTTP_AUTHORIZATION'] = self.encode_user(user)
|
||||
kwargs["HTTP_AUTHORIZATION"] = self.encode_user(user)
|
||||
return self.client_delete(*args, **kwargs)
|
||||
|
||||
def get_streams(self, user_profile: UserProfile) -> List[str]:
|
||||
@@ -728,7 +728,7 @@ Output:
|
||||
return check_send_message(
|
||||
from_user,
|
||||
sending_client,
|
||||
'private',
|
||||
"private",
|
||||
recipient_list,
|
||||
None,
|
||||
content,
|
||||
@@ -749,7 +749,7 @@ Output:
|
||||
return check_send_message(
|
||||
from_user,
|
||||
sending_client,
|
||||
'private',
|
||||
"private",
|
||||
to_user_ids,
|
||||
None,
|
||||
content,
|
||||
@@ -800,7 +800,7 @@ Output:
|
||||
use_first_unread_anchor: bool = False,
|
||||
) -> List[Dict[str, Any]]:
|
||||
data = self.get_messages_response(anchor, num_before, num_after, use_first_unread_anchor)
|
||||
return data['messages']
|
||||
return data["messages"]
|
||||
|
||||
def users_subscribed_to_stream(self, stream_name: str, realm: Realm) -> List[UserProfile]:
|
||||
stream = Stream.objects.get(name=stream_name, realm=realm)
|
||||
@@ -822,8 +822,8 @@ Output:
|
||||
try:
|
||||
json = orjson.loads(result.content)
|
||||
except orjson.JSONDecodeError: # nocoverage
|
||||
json = {'msg': "Error parsing JSON in response!"}
|
||||
self.assertEqual(result.status_code, 200, json['msg'])
|
||||
json = {"msg": "Error parsing JSON in response!"}
|
||||
self.assertEqual(result.status_code, 200, json["msg"])
|
||||
self.assertEqual(json.get("result"), "success")
|
||||
# We have a msg key for consistency with errors, but it typically has an
|
||||
# empty value.
|
||||
@@ -835,10 +835,10 @@ Output:
|
||||
try:
|
||||
json = orjson.loads(result.content)
|
||||
except orjson.JSONDecodeError: # nocoverage
|
||||
json = {'msg': "Error parsing JSON in response!"}
|
||||
self.assertEqual(result.status_code, status_code, msg=json.get('msg'))
|
||||
json = {"msg": "Error parsing JSON in response!"}
|
||||
self.assertEqual(result.status_code, status_code, msg=json.get("msg"))
|
||||
self.assertEqual(json.get("result"), "error")
|
||||
return json['msg']
|
||||
return json["msg"]
|
||||
|
||||
def assert_json_error(self, result: HttpResponse, msg: str, status_code: int = 400) -> None:
|
||||
"""
|
||||
@@ -850,11 +850,11 @@ Output:
|
||||
def assert_length(self, items: List[Any], count: int) -> None:
|
||||
actual_count = len(items)
|
||||
if actual_count != count: # nocoverage
|
||||
print('ITEMS:\n')
|
||||
print("ITEMS:\n")
|
||||
for item in items:
|
||||
print(item)
|
||||
print(f"\nexpected length: {count}\nactual length: {actual_count}")
|
||||
raise AssertionError('List is unexpected size!')
|
||||
raise AssertionError("List is unexpected size!")
|
||||
|
||||
def assert_json_error_contains(
|
||||
self, result: HttpResponse, msg_substring: str, status_code: int = 400
|
||||
@@ -862,17 +862,17 @@ Output:
|
||||
self.assertIn(msg_substring, self.get_json_error(result, status_code=status_code))
|
||||
|
||||
def assert_in_response(self, substring: str, response: HttpResponse) -> None:
|
||||
self.assertIn(substring, response.content.decode('utf-8'))
|
||||
self.assertIn(substring, response.content.decode("utf-8"))
|
||||
|
||||
def assert_in_success_response(self, substrings: List[str], response: HttpResponse) -> None:
|
||||
self.assertEqual(response.status_code, 200)
|
||||
decoded = response.content.decode('utf-8')
|
||||
decoded = response.content.decode("utf-8")
|
||||
for substring in substrings:
|
||||
self.assertIn(substring, decoded)
|
||||
|
||||
def assert_not_in_success_response(self, substrings: List[str], response: HttpResponse) -> None:
|
||||
self.assertEqual(response.status_code, 200)
|
||||
decoded = response.content.decode('utf-8')
|
||||
decoded = response.content.decode("utf-8")
|
||||
for substring in substrings:
|
||||
self.assertNotIn(substring, decoded)
|
||||
|
||||
@@ -883,7 +883,7 @@ Output:
|
||||
"""
|
||||
self.assertEqual(get_session_dict_user(self.client.session), user_id)
|
||||
|
||||
def webhook_fixture_data(self, type: str, action: str, file_type: str = 'json') -> str:
|
||||
def webhook_fixture_data(self, type: str, action: str, file_type: str = "json") -> str:
|
||||
fn = os.path.join(
|
||||
os.path.dirname(__file__),
|
||||
f"../webhooks/{type}/fixtures/{action}.{file_type}",
|
||||
@@ -891,13 +891,13 @@ Output:
|
||||
with open(fn) as f:
|
||||
return f.read()
|
||||
|
||||
def fixture_file_name(self, file_name: str, type: str = '') -> str:
|
||||
def fixture_file_name(self, file_name: str, type: str = "") -> str:
|
||||
return os.path.join(
|
||||
os.path.dirname(__file__),
|
||||
f"../tests/fixtures/{type}/{file_name}",
|
||||
)
|
||||
|
||||
def fixture_data(self, file_name: str, type: str = '') -> str:
|
||||
def fixture_data(self, file_name: str, type: str = "") -> str:
|
||||
fn = self.fixture_file_name(file_name, type)
|
||||
with open(fn) as f:
|
||||
return f.read()
|
||||
@@ -911,7 +911,7 @@ Output:
|
||||
history_public_to_subscribers: Optional[bool] = None,
|
||||
) -> Stream:
|
||||
if realm is None:
|
||||
realm = get_realm('zulip')
|
||||
realm = get_realm("zulip")
|
||||
|
||||
history_public_to_subscribers = get_default_value_for_history_public_to_subscribers(
|
||||
realm, invite_only, history_public_to_subscribers
|
||||
@@ -927,11 +927,11 @@ Output:
|
||||
)
|
||||
except IntegrityError: # nocoverage -- this is for bugs in the tests
|
||||
raise Exception(
|
||||
f'''
|
||||
f"""
|
||||
{stream_name} already exists
|
||||
|
||||
Please call make_stream with a stream name
|
||||
that is not already in use.'''
|
||||
that is not already in use."""
|
||||
)
|
||||
|
||||
recipient = Recipient.objects.create(type_id=stream.id, type=Recipient.STREAM)
|
||||
@@ -943,7 +943,7 @@ Output:
|
||||
|
||||
def get_stream_id(self, name: str, realm: Optional[Realm] = None) -> int:
|
||||
if not realm:
|
||||
realm = get_realm('zulip')
|
||||
realm = get_realm("zulip")
|
||||
try:
|
||||
stream = get_realm_stream(name, realm.id)
|
||||
except Stream.DoesNotExist:
|
||||
@@ -977,9 +977,9 @@ Output:
|
||||
**kwargs: Any,
|
||||
) -> HttpResponse:
|
||||
post_data = {
|
||||
'subscriptions': orjson.dumps([{"name": stream} for stream in streams]).decode(),
|
||||
'is_web_public': orjson.dumps(is_web_public).decode(),
|
||||
'invite_only': orjson.dumps(invite_only).decode(),
|
||||
"subscriptions": orjson.dumps([{"name": stream} for stream in streams]).decode(),
|
||||
"is_web_public": orjson.dumps(is_web_public).decode(),
|
||||
"invite_only": orjson.dumps(invite_only).decode(),
|
||||
}
|
||||
post_data.update(extra_post_data)
|
||||
result = self.api_post(user, "/api/v1/users/me/subscriptions", post_data, **kwargs)
|
||||
@@ -1032,7 +1032,7 @@ Output:
|
||||
|
||||
if msg.id == prior_msg.id:
|
||||
raise Exception(
|
||||
'''
|
||||
"""
|
||||
Your test code called an endpoint that did
|
||||
not write any new messages. It is probably
|
||||
broken (but still returns 200 due to exception
|
||||
@@ -1041,7 +1041,7 @@ Output:
|
||||
One possible gotcha is that you forgot to
|
||||
subscribe the test user to the stream that
|
||||
the webhook sends to.
|
||||
'''
|
||||
"""
|
||||
) # nocoverage
|
||||
|
||||
self.assertEqual(msg.sender.email, user_profile.email)
|
||||
@@ -1049,10 +1049,10 @@ Output:
|
||||
return msg
|
||||
|
||||
def get_last_message(self) -> Message:
|
||||
return Message.objects.latest('id')
|
||||
return Message.objects.latest("id")
|
||||
|
||||
def get_second_to_last_message(self) -> Message:
|
||||
return Message.objects.all().order_by('-id')[1]
|
||||
return Message.objects.all().order_by("-id")[1]
|
||||
|
||||
@contextmanager
|
||||
def simulated_markdown_failure(self) -> Iterator[None]:
|
||||
@@ -1061,8 +1061,8 @@ Output:
|
||||
markdown.__init__.do_convert.
|
||||
"""
|
||||
with self.settings(ERROR_BOT=None), mock.patch(
|
||||
'zerver.lib.markdown.timeout', side_effect=subprocess.CalledProcessError(1, [])
|
||||
), mock.patch('zerver.lib.markdown.markdown_logger'):
|
||||
"zerver.lib.markdown.timeout", side_effect=subprocess.CalledProcessError(1, [])
|
||||
), mock.patch("zerver.lib.markdown.markdown_logger"):
|
||||
yield
|
||||
|
||||
def create_default_device(
|
||||
@@ -1070,11 +1070,11 @@ Output:
|
||||
) -> None:
|
||||
phone_device = PhoneDevice(
|
||||
user=user_profile,
|
||||
name='default',
|
||||
name="default",
|
||||
confirmed=True,
|
||||
number=number,
|
||||
key='abcd',
|
||||
method='sms',
|
||||
key="abcd",
|
||||
method="sms",
|
||||
)
|
||||
phone_device.save()
|
||||
|
||||
@@ -1094,7 +1094,7 @@ Output:
|
||||
return values
|
||||
|
||||
def find_by_id(self, data: List[Dict[str, Any]], db_id: int) -> Dict[str, Any]:
|
||||
return [r for r in data if r['id'] == db_id][0]
|
||||
return [r for r in data if r["id"] == db_id][0]
|
||||
|
||||
def init_default_ldap_database(self) -> None:
|
||||
"""
|
||||
@@ -1110,9 +1110,9 @@ Output:
|
||||
directory = orjson.loads(self.fixture_data("directory.json", type="ldap"))
|
||||
|
||||
for dn, attrs in directory.items():
|
||||
if 'uid' in attrs:
|
||||
if "uid" in attrs:
|
||||
# Generate a password for the LDAP account:
|
||||
attrs['userPassword'] = [self.ldap_password(attrs['uid'][0])]
|
||||
attrs["userPassword"] = [self.ldap_password(attrs["uid"][0])]
|
||||
|
||||
# Load binary attributes. If in "directory", an attribute as its value
|
||||
# has a string starting with "file:", the rest of the string is assumed
|
||||
@@ -1120,10 +1120,10 @@ Output:
|
||||
# as the actual value of the attribute in LDAP.
|
||||
for attr, value in attrs.items():
|
||||
if isinstance(value, str) and value.startswith("file:"):
|
||||
with open(value[5:], 'rb') as f:
|
||||
with open(value[5:], "rb") as f:
|
||||
attrs[attr] = [f.read()]
|
||||
|
||||
ldap_patcher = mock.patch('django_auth_ldap.config.ldap.initialize')
|
||||
ldap_patcher = mock.patch("django_auth_ldap.config.ldap.initialize")
|
||||
self.mock_initialize = ldap_patcher.start()
|
||||
self.mock_ldap = MockLDAP(directory)
|
||||
self.mock_initialize.return_value = self.mock_ldap
|
||||
@@ -1170,7 +1170,7 @@ class WebhookTestCase(ZulipTestCase):
|
||||
"""
|
||||
|
||||
STREAM_NAME: Optional[str] = None
|
||||
TEST_USER_EMAIL = 'webhook-bot@zulip.com'
|
||||
TEST_USER_EMAIL = "webhook-bot@zulip.com"
|
||||
URL_TEMPLATE: str
|
||||
FIXTURE_DIR_NAME: Optional[str] = None
|
||||
|
||||
@@ -1183,7 +1183,7 @@ class WebhookTestCase(ZulipTestCase):
|
||||
self.url = self.build_webhook_url()
|
||||
|
||||
def api_stream_message(self, user: UserProfile, *args: Any, **kwargs: Any) -> HttpResponse:
|
||||
kwargs['HTTP_AUTHORIZATION'] = self.encode_user(user)
|
||||
kwargs["HTTP_AUTHORIZATION"] = self.encode_user(user)
|
||||
return self.check_webhook(*args, **kwargs)
|
||||
|
||||
def check_webhook(
|
||||
@@ -1217,7 +1217,7 @@ class WebhookTestCase(ZulipTestCase):
|
||||
|
||||
payload = self.get_payload(fixture_name)
|
||||
if content_type is not None:
|
||||
kwargs['content_type'] = content_type
|
||||
kwargs["content_type"] = content_type
|
||||
if self.FIXTURE_DIR_NAME is not None:
|
||||
headers = get_fixture_http_headers(self.FIXTURE_DIR_NAME, fixture_name)
|
||||
headers = standardize_headers(headers)
|
||||
@@ -1263,14 +1263,14 @@ class WebhookTestCase(ZulipTestCase):
|
||||
check_webhook.
|
||||
"""
|
||||
payload = self.get_payload(fixture_name)
|
||||
kwargs['content_type'] = content_type
|
||||
kwargs["content_type"] = content_type
|
||||
|
||||
if self.FIXTURE_DIR_NAME is not None:
|
||||
headers = get_fixture_http_headers(self.FIXTURE_DIR_NAME, fixture_name)
|
||||
headers = standardize_headers(headers)
|
||||
kwargs.update(headers)
|
||||
# The sender profile shouldn't be passed any further in kwargs, so we pop it.
|
||||
sender = kwargs.pop('sender', self.test_user)
|
||||
sender = kwargs.pop("sender", self.test_user)
|
||||
|
||||
msg = self.send_webhook_payload(
|
||||
sender,
|
||||
@@ -1291,7 +1291,7 @@ class WebhookTestCase(ZulipTestCase):
|
||||
url = self.URL_TEMPLATE.format(stream=self.STREAM_NAME)
|
||||
|
||||
has_arguments = kwargs or args
|
||||
if has_arguments and url.find('?') == -1:
|
||||
if has_arguments and url.find("?") == -1:
|
||||
url = f"{url}?" # nocoverage
|
||||
else:
|
||||
url = f"{url}&"
|
||||
|
||||
Reference in New Issue
Block a user