Skip to content

Commit

Permalink
pep8: Fix E301 pep8 violations.
Browse files Browse the repository at this point in the history
Fix "E301: expected (1 or 2) blank line" pep8 violations.
  • Loading branch information
refeed authored and timabbott committed Nov 29, 2016
1 parent 7a22829 commit 41bd88d
Show file tree
Hide file tree
Showing 35 changed files with 57 additions and 2 deletions.
1 change: 1 addition & 0 deletions analytics/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -655,6 +655,7 @@ def get_user_activity_summary(records):
# `Union[Dict[str, Dict[str, int]], Dict[str, Dict[str, datetime]]]`
#: but that would require this long `Union` to carry on throughout inner functions.
summary = {} # type: Dict[str, Dict[str, Any]]

def update(action, record):
# type: (str, QuerySet) -> None
if action not in summary:
Expand Down
2 changes: 2 additions & 0 deletions api/integrations/perforce/git_p4.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,11 @@ class CalledProcessError(Exception):
"""This exception is raised when a process run by check_call() returns
a non-zero exit status. The exit status will be stored in the
returncode attribute."""

def __init__(self, returncode, cmd):
self.returncode = returncode
self.cmd = cmd

def __str__(self):
return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode)

Expand Down
2 changes: 2 additions & 0 deletions api/zulip/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -398,6 +398,7 @@ def make_request(request=None):
if request is None:
request = {}
return request

def call(self, *args, **kwargs):
request = make_request(*args, **kwargs)
if computed_url is not None:
Expand All @@ -411,6 +412,7 @@ def call(self, *args, **kwargs):
def call_on_each_event(self, callback, event_types=None, narrow=None):
if narrow is None:
narrow = []

def do_register():
while True:
if event_types is None:
Expand Down
1 change: 1 addition & 0 deletions bots/irc-mirror.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ def on_nicknameinuse(self, c, e):
def on_welcome(self, c, e):
# type: (ServerConnection, Event) -> None
c.join(self.channel)

def forward_to_irc(msg):
# type: (Dict[str, Any]) -> None
if msg["type"] == "stream":
Expand Down
1 change: 1 addition & 0 deletions bots/zephyr_mirror.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ def die(signal, frame):
from zerver.lib.parallel import run_parallel
print("Starting parallel zephyr class mirroring bot")
jobs = list("0123456789abcdef")

def run_job(shard):
# type: (str) -> int
subprocess.call(args + ["--shard=%s" % (shard,)])
Expand Down
1 change: 1 addition & 0 deletions tools/lib/template_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,7 @@ def start_tag_matcher(start_token):
start_col = start_token.col

old_matcher = state.matcher

def f(end_token):
# type: (Token) -> None

Expand Down
3 changes: 1 addition & 2 deletions tools/lint-all
Original file line number Diff line number Diff line change
Expand Up @@ -83,10 +83,9 @@ def check_pep8(files):
failed = False
ignored_rules = [
'E402', 'E501', 'W503', 'E711', 'E201', 'E203', 'E202', 'E128', 'E226', 'E124', 'E125',
'E126', 'E127', 'E121', 'E122', 'E123', 'E266', 'E265', 'E261', 'E301', 'E221', 'E303',
'E126', 'E127', 'E121', 'E122', 'E123', 'E266', 'E265', 'E261', 'E701', 'E221', 'E303',
'E241', 'E712', 'E702', 'E401', 'E115', 'E114', 'E111', 'E222', 'E731', 'E302', 'E129',
'E741', 'E714', 'W391', 'E211', 'E713', 'E502', 'E131', 'E305', 'E251', 'E306', 'E231',
'E701',
]
pep8 = subprocess.Popen(
['pycodestyle'] + files + ['--ignore={rules}'.format(rules=','.join(ignored_rules))],
Expand Down
1 change: 1 addition & 0 deletions zerver/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ def get_post_parameters(self, request):
if var in filtered_post:
filtered_post[var] = '**********'
return filtered_post

def get_request_repr(self, request):
# type: (HttpRequest) -> str
if request is None:
Expand Down
3 changes: 3 additions & 0 deletions zerver/lib/bugdown/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -659,6 +659,7 @@ class ModalLink(markdown.inlinepatterns.Pattern):
"""
A pattern that allows including in-app modal links in messages.
"""

def handleMatch(self, match):
# type: (Match[text_type]) -> Element
relative_url = match.group('relative_url')
Expand Down Expand Up @@ -824,6 +825,7 @@ def run(self, lines):
# Based on markdown.inlinepatterns.LinkPattern
class LinkPattern(markdown.inlinepatterns.Pattern):
""" Return a link element from the given match. """

def handleMatch(self, m):
# type: (Match[text_type]) -> Optional[Element]
href = m.group(9)
Expand Down Expand Up @@ -853,6 +855,7 @@ def prepare_realm_pattern(source):
# using the provided format string to construct the URL.
class RealmFilterPattern(markdown.inlinepatterns.Pattern):
""" Applied a given realm filter to the input """

def __init__(self, source_pattern, format_string, markdown_instance=None):
# type: (text_type, text_type, Optional[markdown.Markdown]) -> None
self.pattern = prepare_realm_pattern(source_pattern)
Expand Down
1 change: 1 addition & 0 deletions zerver/lib/bugdown/fenced_code.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@ class BaseHandler(object):
def handle_line(self, line):
# type: (text_type) -> None
raise NotImplementedError()

def done(self):
# type: () -> None
raise NotImplementedError()
Expand Down
2 changes: 2 additions & 0 deletions zerver/lib/export.py
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,7 @@ class Config(object):
append itself to the parent's list of children.
'''

def __init__(self, table=None, model=None,
normal_parent=None, virtual_parent=None,
filter_args=None, custom_fetch=None, custom_tables=None,
Expand Down Expand Up @@ -1101,6 +1102,7 @@ def create_soft_link(source, in_progress=True):
def launch_user_message_subprocesses(threads, output_dir):
# type: (int, Path) -> None
logging.info('Launching %d PARALLEL subprocesses to export UserMessage rows' % (threads,))

def run_job(shard):
# type: (str) -> int
subprocess.call(["./manage.py", 'export_usermessage_batch', '--path',
Expand Down
1 change: 1 addition & 0 deletions zerver/lib/narrow.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ def build_narrow_filter(narrow):
"""Changes to this function should come with corresponding changes to
BuildNarrowFilterTest."""
check_supported_events_narrow_filter(narrow)

def narrow_filter(event):
# type: (Mapping[str, Any]) -> bool
message = event["message"]
Expand Down
1 change: 1 addition & 0 deletions zerver/lib/parallel.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ def wait_for_one():
import time
jobs = [10, 19, 18, 6, 14, 12, 8, 2, 1, 13, 3, 17, 9, 11, 5, 16, 7, 15, 4]
expected_output = [6, 10, 12, 2, 1, 14, 8, 3, 18, 19, 5, 9, 13, 11, 4, 7, 17, 16, 15]

def wait_and_print(x):
# type: (int) -> int
time.sleep(x * 0.1)
Expand Down
2 changes: 2 additions & 0 deletions zerver/lib/queue.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,7 @@ def drain_queue(self, queue_name, json=False):
# type: (str, bool) -> List[Dict[str, Any]]
"Returns all messages in the desired queue"
messages = []

def opened():
# type: () -> None
while True:
Expand Down Expand Up @@ -233,6 +234,7 @@ def _on_connection_closed(self, connection, reply_code, reply_text):

# Try to reconnect in two seconds
retry_seconds = 2

def on_timeout():
# type: () -> None
try:
Expand Down
1 change: 1 addition & 0 deletions zerver/lib/str_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ class ModelReprMixin(object):
Define __unicode__ on your model which returns a six.text_type object.
This mixin will automatically define __str__ and __repr__.
"""

def __unicode__(self):
# type: () -> Text
# Originally raised an exception, but Django (e.g. the ./manage.py shell)
Expand Down
2 changes: 2 additions & 0 deletions zerver/lib/test_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ def tornado_redirected_to_list(lst):
def simulated_empty_cache():
# type: () -> Generator[List[Tuple[str, Union[text_type, List[text_type]], text_type]], None, None]
cache_queries = [] # type: List[Tuple[str, Union[text_type, List[text_type]], text_type]]

def my_cache_get(key, cache_name=None):
# type: (text_type, Optional[str]) -> Any
cache_queries.append(('get', key, cache_name))
Expand Down Expand Up @@ -206,6 +207,7 @@ def __init__(self, post_data, user_profile):
class HostRequestMock(object):
"""A mock request object where get_host() works. Useful for testing
routes that use Zulip's subdomains feature"""

def __init__(self, host=settings.EXTERNAL_HOST):
# type: (text_type) -> None
self.host = host
Expand Down
1 change: 1 addition & 0 deletions zerver/lib/timeout.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

class TimeoutExpired(Exception):
'''Exception raised when a function times out.'''

def __str__(self):
# type: () -> str
return 'Function call timed out.'
Expand Down
1 change: 1 addition & 0 deletions zerver/management/commands/enqueue_digest_emails.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ class Command(BaseCommand):
help = """Enqueue digest emails for users that haven't checked the app
in a while.
"""

def handle(self, *args, **options):
# type: (*Any, **Any) -> None
# To be really conservative while we don't have user timezones or
Expand Down
1 change: 1 addition & 0 deletions zerver/management/commands/process_queue.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ def add_arguments(self, parser):
help="run all queues")

help = "Runs a queue processing worker"

def handle(self, *args, **options):
# type: (*Any, **Any) -> None
logging.basicConfig()
Expand Down
1 change: 1 addition & 0 deletions zerver/management/commands/purge_queue.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ def add_arguments(self, parser):
help="queue to purge")

help = "Discards all messages from the given queue"

def handle(self, *args, **options):
# type: (*Any, **str) -> None
queue_name = options['queue_name']
Expand Down
1 change: 1 addition & 0 deletions zerver/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,7 @@ class TagRequests(object):
def process_view(self, request, view_func, args, kwargs):
# type: (HttpRequest, Callable[..., HttpResponse], *str, **Any) -> None
self.process_request(request)

def process_request(self, request):
# type: (HttpRequest) -> None
if request.path.startswith("/api/") or request.path.startswith("/json/"):
Expand Down
1 change: 1 addition & 0 deletions zerver/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -852,6 +852,7 @@ def bulk_get_recipients(type, type_ids):
def cache_key_function(type_id):
# type: (int) -> Text
return get_recipient_cache_key(type, type_id)

def query_function(type_ids):
# type: (List[int]) -> Sequence[Recipient]
# TODO: Change return type to QuerySet[Recipient]
Expand Down
1 change: 1 addition & 0 deletions zerver/tests/test_auth_backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -1089,6 +1089,7 @@ class TestJWTLogin(ZulipTestCase):
"""
JWT uses ZulipDummyBackend.
"""

def test_login_success(self):
# type: () -> None
payload = {'user': 'hamlet', 'realm': 'zulip.com'}
Expand Down
4 changes: 4 additions & 0 deletions zerver/tests/test_decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,7 @@ class TestLoggingErrorException(Exception):
def test_internal_local_clients_skip_rate_limiting(self):
class Client(object):
name = 'internal'

class Request(object):
client = Client()
META = {'REMOTE_ADDR': '127.0.0.1'}
Expand All @@ -285,6 +286,7 @@ def f(req):
def test_debug_clients_skip_rate_limiting(self):
class Client(object):
name = 'internal'

class Request(object):
client = Client()
META = {'REMOTE_ADDR': '3.3.3.3'}
Expand All @@ -307,6 +309,7 @@ def f(req):
def test_rate_limit_setting_of_false_bypasses_rate_limiting(self):
class Client(object):
name = 'external'

class Request(object):
client = Client()
META = {'REMOTE_ADDR': '3.3.3.3'}
Expand All @@ -329,6 +332,7 @@ def f(req):
def test_rate_limiting_happens_in_normal_case(self):
class Client(object):
name = 'external'

class Request(object):
client = Client()
META = {'REMOTE_ADDR': '3.3.3.3'}
Expand Down
1 change: 1 addition & 0 deletions zerver/tests/test_external.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ def test_mailinglist(self):
self.assertRaises(ValidationError, email_is_not_mit_mailing_list, "[email protected]")
with mock.patch('DNS.dnslookup', side_effect=DNS.Base.ServerError('DNS query status: NXDOMAIN', 3)):
self.assertRaises(ValidationError, email_is_not_mit_mailing_list, "[email protected]")

def test_notmailinglist(self):
# type: () -> None
with mock.patch('DNS.dnslookup', return_value=[['POP IMAP.EXCHANGE.MIT.EDU starnine']]):
Expand Down
1 change: 1 addition & 0 deletions zerver/tests/test_narrow.py
Original file line number Diff line number Diff line change
Expand Up @@ -377,6 +377,7 @@ def test_get_old_messages_with_narrow_pm_with(self):
conversations with that user.
"""
me = '[email protected]'

def dr_emails(dr):
return ','.join(sorted(set([r['email'] for r in dr] + [me])))

Expand Down
1 change: 1 addition & 0 deletions zerver/tests/test_push_notifications.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,7 @@ def test_send(user, message, alert):
def test_do_push_to_apns_service(self, mock_push):
# type: (mock.MagicMock) -> None
msg = apn.APNsMessage(self.user_profile, self.tokens, alert="test")

def test_push(message):
# type: (Message) -> None
self.assertIs(message, msg.get_frame())
Expand Down
4 changes: 4 additions & 0 deletions zerver/tests/test_type_debug.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ class TypesPrintTest(TestCase):
def _pre_setup(self):
# type: () -> None
pass

def _post_teardown(self):
# type: () -> None
pass
Expand Down Expand Up @@ -91,13 +92,15 @@ def test_tuple(self):
def test_class(self):
# type: () -> None
class A(object): pass

class B(str): pass
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"))

def test_sequence(self):
# type: () -> None
class A(list): pass

class B(list): pass
self.check_signature("add(A([]), B([str])) -> [str]",
['two'], add, A([]), B(['two']))
Expand All @@ -109,6 +112,7 @@ class B(list): pass
def test_mapping(self):
# type: () -> None
class A(dict): pass

def to_A(l=[]):
# type: (Iterable[Tuple[Any, Any]]) -> A
return A(l)
Expand Down
1 change: 1 addition & 0 deletions zerver/tests/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -603,6 +603,7 @@ class TestWorker(queue_processors.QueueProcessingWorker):
def __init__(self):
# type: () -> None
super(TestWorker, self).__init__()

def consume(self, data):
# type: (Mapping[str, Any]) -> None
pass
Expand Down
1 change: 1 addition & 0 deletions zerver/tests/webhooks/test_gitlab.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,7 @@ def test_merge_request_created_without_assignee_event_message(self):
expected_message,
HTTP_X_GITLAB_EVENT="Merge Request Hook"
)

def test_merge_request_created_with_assignee_event_message(self):
# type: () -> None
expected_subject = u"my-awesome-project / MR #3 New Merge Request"
Expand Down
1 change: 1 addition & 0 deletions zerver/tests/webhooks/test_new_relic.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ def test_alert(self):
[View alert](https://rpm.newrelc.com/accounts/[account_id]/applications/[application_id]/incidents/[incident_id])'
self.send_and_test_stream_message('alert', expected_subject, expected_message,
content_type="application/x-www-form-urlencoded")

def test_deployment(self):
# type: () -> None
expected_subject = 'Test App deploy'
Expand Down
1 change: 1 addition & 0 deletions zerver/tornado/event_queue.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,7 @@ def connect_handler(self, handler_id, client_name):
self.current_client_name = client_name
set_descriptor_by_handler_id(handler_id, self)
self.last_connection_time = time.time()

def timeout_callback():
# type: () -> None
self._timeout_handle = None
Expand Down
2 changes: 2 additions & 0 deletions zerver/tornado/ioloop_logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
try:
# Tornado 2.4
orig_poll_impl = ioloop._poll # type: ignore # cross-version type variation is hard for mypy

def instrument_tornado_ioloop():
# type: () -> None
ioloop._poll = InstrumentedPoll # type: ignore # cross-version type variation is hard for mypy
Expand All @@ -21,6 +22,7 @@ def instrument_tornado_ioloop():
# will be without actually constructing an IOLoop, so we just assume it will
# be epoll.
orig_poll_impl = select.epoll # type: ignore # There is no stub for select.epoll on python 3

class InstrumentedPollIOLoop(PollIOLoop):
def initialize(self, **kwargs): # type: ignore # TODO investigate likely buggy monkey patching here
super(InstrumentedPollIOLoop, self).initialize(impl=InstrumentedPoll(), **kwargs)
Expand Down
Loading

0 comments on commit 41bd88d

Please sign in to comment.